Compare commits

..
Author SHA1 Message Date
Kurt Himebauch bc49b8ac34 fix(epic): keep the in-app sign-in and add a browser fallback that takes Epic's code from the clipboard 2026-11-16 10:54:40 -05:00
Kurt Himebauch de92fef457 fix(epic): say the sign-in waits for Confirm and why Epic calls it Fortnite instead of showing the code 2026-11-16 10:04:22 -05:00
Kurt Himebauch d415782c56 Merge remote-tracking branch 'origin/fix/epic-chrome-localhost-auth' into fix/epic-chrome-localhost-auth 2026-11-16 09:55:45 -05:00
Kurt Himebauch 1c2857ddb2 fix(epic): float the Epic code over Chrome so DroidDeck returns once the sign-in is confirmed 2026-11-16 09:55:31 -05:00
Kurt Himebauch 2a86074246 Merge branch 'main' into fix/epic-chrome-localhost-auth 2026-11-16 09:45:50 -05:00
Kurt Himebauch cc27e51d4d fix(epic): sign in through Chrome with Epic's device code instead of a loopback redirect 2026-11-16 09:44:07 -05:00
Kurt Himebauch 9b4ee449ad fix(epic): force the sign-in form in the browser sign-in so an existing session cannot end in an error 2026-11-16 13:22:25 +00:00
Kurt Himebauch 484a655aca fix(epic): restore the embedded sign-in when the browser sign-in cannot start 2026-11-16 06:30:56 +00:00
Kurt Himebauch cad5d3fe63 fix(epic): ignore stale embedded sign-in errors after a browser attempt starts 2026-11-16 06:17:33 +00:00
Kurt Himebauch a761901b96 fix(epic): bound each loopback request read by the remaining request deadline 2026-11-16 06:11:12 +00:00
Kurt Himebauch 7acddbe294 fix(epic): bound and close loopback sign-in connections and ignore replaced browser attempts 2026-11-16 05:50:54 +00:00
Kurt Himebauch 12ecc14135 feat(epic): sign in to Epic through the system browser with a loopback callback 2026-11-16 05:24:42 +00:00
717 changed files with 11882 additions and 38524 deletions

No files matched your search

-1
View File
@@ -1,6 +1,5 @@
ASEbrahim ASEbrahim
FX192 FX192
FryMcNugget
K11MCH1 K11MCH1
KeegantheVeganat0r KeegantheVeganat0r
kingokksa kingokksa
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
validate: validate:
name: Validate source and build result name: Validate source and build result
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 70 timeout-minutes: 5
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
@@ -1,34 +0,0 @@
name: Build bionic runtime pack and DroidDeck-Bionic tool
on:
push:
paths:
- 'tools/bionic-runtime/**'
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
- 'app/src/main/cpp/fakeinput_steam.cpp'
- '.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/*
+13 -22
View File
@@ -152,9 +152,6 @@ jobs:
runs-on: ${{ fromJSON(needs.components-runner.outputs.labels) }} runs-on: ${{ fromJSON(needs.components-runner.outputs.labels) }}
timeout-minutes: 40 timeout-minutes: 40
steps: steps:
- name: Reclaim files a cancelled container build left owned by root
if: runner.environment == 'self-hosted'
run: sudo -n chown -R "$(id -u):$(id -g)" "$GITHUB_WORKSPACE" || echo "::warning::could not reclaim $GITHUB_WORKSPACE"
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
@@ -195,17 +192,17 @@ jobs:
app/src/main/assets/linuxfs app/src/main/assets/linuxfs
!app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet !app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet
!app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox !app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
!app/src/main/assets/linuxfs/i386/libddsession.so !app/src/main/assets/linuxfs/i386/libblsession.so
!app/src/main/assets/linuxfs/i386/libfakeinput.so !app/src/main/assets/linuxfs/i386/libfakeinput.so
!app/src/main/assets/linuxfs/i386/libfaultreport.so !app/src/main/assets/linuxfs/i386/libfaultreport.so
!app/src/main/assets/linuxfs/libddaudit.so !app/src/main/assets/linuxfs/libblaudit.so
!app/src/main/assets/linuxfs/libddfastpath.so !app/src/main/assets/linuxfs/libblfastpath.so
!app/src/main/assets/linuxfs/libddnatv-hook.so !app/src/main/assets/linuxfs/libddnatv-hook.so
!app/src/main/assets/linuxfs/libddsession.so !app/src/main/assets/linuxfs/libblsession.so
!app/src/main/assets/linuxfs/libfakeinput.so !app/src/main/assets/linuxfs/libfakeinput.so
!app/src/main/assets/linuxfs/libssbs.so !app/src/main/assets/linuxfs/libssbs.so
!app/src/main/assets/linuxfs/usr/local/bin/droiddeck-clipboard !app/src/main/assets/linuxfs/usr/local/bin/droiddeck-clipboard
!app/src/main/assets/linuxfs/x86_64/libddsession.so !app/src/main/assets/linuxfs/x86_64/libblsession.so
!app/src/main/assets/linuxfs/x86_64/libfakeinput.so !app/src/main/assets/linuxfs/x86_64/libfakeinput.so
!app/src/main/assets/linuxfs/x86_64/libfaultreport.so !app/src/main/assets/linuxfs/x86_64/libfaultreport.so
!app/src/main/assets/linuxfs/x86_64/libvulkan-thunk.so !app/src/main/assets/linuxfs/x86_64/libvulkan-thunk.so
@@ -291,7 +288,7 @@ jobs:
- name: Build the non-Adreno test additions (Mali bridge client, Venus GL probe, Xclipse layer) - name: Build the non-Adreno test additions (Mali bridge client, Venus GL probe, Xclipse layer)
run: | run: |
set -euo pipefail set -euo pipefail
bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libc6-dev-arm64-cross libvulkan-dev bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libvulkan-dev
D=app/src/main/assets/linuxfs D=app/src/main/assets/linuxfs
mkdir -p "$D/usr/local/bin" "$D/usr/local/lib/droiddeck-xclipse" mkdir -p "$D/usr/local/bin" "$D/usr/local/lib/droiddeck-xclipse"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \ aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
@@ -353,9 +350,6 @@ jobs:
outputs: outputs:
variants: ${{ steps.variants.outputs.list }} variants: ${{ steps.variants.outputs.list }}
steps: steps:
- name: Reclaim files a cancelled container build left owned by root
if: runner.environment == 'self-hosted'
run: sudo -n chown -R "$(id -u):$(id -g)" "$GITHUB_WORKSPACE" || echo "::warning::could not reclaim $GITHUB_WORKSPACE"
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
@@ -619,18 +613,14 @@ jobs:
export NDK="$ANDROID_HOME/ndk/$NDK_VERSION" export NDK="$ANDROID_HOME/ndk/$NDK_VERSION"
tools/syncthing/build.sh app/src/main/jniLibs/arm64-v8a tools/syncthing/build.sh app/src/main/jniLibs/arm64-v8a
- name: Check the proot pack pin against this build - name: Note when the proot pack pin is behind this build
run: | run: |
set -euo pipefail set -euo pipefail
# shellcheck disable=SC1091 # shellcheck disable=SC1091
source tools/packs/proot/release.env source tools/packs/proot/release.env
sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1) sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1)
size=$(stat -c %s app/build/packs/proot.tar.zst) if [ "$sha" != "$PROOT_PACK_SHA256" ]; then
if [ "$sha" != "$PROOT_PACK_SHA256" ] || [ "$size" != "$PROOT_PACK_SIZE" ]; then echo "::warning::built proot pack $sha does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256). This build publishes the pack it just built. Source builds keep downloading the pinned pack until release.env is updated."
level=warning
if [ "$GITHUB_EVENT_NAME" = pull_request ]; then level=error; fi
echo "::$level::built proot pack $sha ($size bytes) does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256, $PROOT_PACK_SIZE bytes). Source builds download the pinned pack, so set PROOT_PACK_SHA256=$sha and PROOT_PACK_SIZE=$size in tools/packs/proot/release.env."
if [ "$level" = error ]; then exit 1; fi
fi fi
- name: Check out MaliBridge - name: Check out MaliBridge
@@ -769,6 +759,7 @@ jobs:
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 15 timeout-minutes: 15
continue-on-error: true
permissions: permissions:
contents: read contents: read
actions: read actions: read
@@ -814,6 +805,7 @@ jobs:
stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}- stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-
- name: Store engines host unit tests - name: Store engines host unit tests
timeout-minutes: 10 timeout-minutes: 10
continue-on-error: true
run: | run: |
set -o pipefail set -o pipefail
cd app/src/main/rust/stores cd app/src/main/rust/stores
@@ -902,7 +894,7 @@ jobs:
checks: checks:
name: Compile and test APK name: Compile and test APK
needs: [build, python-tests, store-tests] needs: [build, python-tests]
if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 5 timeout-minutes: 5
@@ -911,8 +903,7 @@ jobs:
env: env:
BUILD_RESULT: ${{ needs.build.result }} BUILD_RESULT: ${{ needs.build.result }}
PYTHON_RESULT: ${{ needs.python-tests.result }} PYTHON_RESULT: ${{ needs.python-tests.result }}
STORE_RESULT: ${{ needs.store-tests.result }} run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success
run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success && test "$STORE_RESULT" = success
sign: sign:
needs: [build, checks] needs: [build, checks]
+4 -5
View File
@@ -47,7 +47,7 @@ Help, Preview builds and device reports are on [Discord](https://discord.gg/JRGA
## Build ## Build
Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, Go, a host C compiler, the x86_64 and i686 MinGW-w64 compilers (i686 with DWARF-2 exceptions, as Debian and Ubuntu ship it; SJLJ builds such as Homebrew's cannot link Rust's `i686-pc-windows-gnu`), GitHub CLI, Python 3 and `zstd`. On x86_64 Linux, Docker also needs an arm64 binfmt handler (`docker run --privileged --rm tonistiigi/binfmt --install arm64`). Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, GitHub CLI, Python 3 and `zstd`.
```bash ```bash
tools/build_local.sh tools/build_local.sh
@@ -70,13 +70,13 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05. - 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. - [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT). FEX's code disk cache was checked in its source.
- 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.
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim. - Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libddsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`. - Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libblsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`.
- libddsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc/<pid>/status`. - libblsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc/<pid>/status`.
- droiddeck-ntsync follows the [Linux](https://github.com/torvalds/linux) ntsync semantics in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). - droiddeck-ntsync follows the [Linux](https://github.com/torvalds/linux) ntsync semantics in `Documentation/userspace-api/ntsync.rst` (GPL-2.0).
- The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later). - The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later).
- DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling. - DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling.
@@ -97,7 +97,6 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. - Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
- The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own. - The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own.
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader. - Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code.
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used. - World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key. - The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). - The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
-2
View File
@@ -388,8 +388,6 @@ dependencies {
implementation 'androidx.compose.material3:material3' implementation 'androidx.compose.material3:material3'
implementation 'androidx.compose.ui:ui-tooling-preview' implementation 'androidx.compose.ui:ui-tooling-preview'
debugImplementation 'androidx.compose.ui:ui-tooling' debugImplementation 'androidx.compose.ui:ui-tooling'
// Declares the ComponentActivity that createComposeRule launches, for PreviewRenderTest.
debugImplementation 'androidx.compose.ui:ui-test-manifest'
implementation 'androidx.activity:activity-compose:1.8.2' implementation 'androidx.activity:activity-compose:1.8.2'
implementation 'androidx.compose.material:material-icons-extended' implementation 'androidx.compose.material:material-icons-extended'
implementation 'io.coil-kt:coil-compose:2.6.0' implementation 'io.coil-kt:coil-compose:2.6.0'
@@ -1,79 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.SecondScreenMode
/** The launcher as a whole: rail and page, opened on each tab through FrontEndState.navigate. */
@Composable
private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Library.SteamGame> = sampleGames, ready: Boolean = true) =
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
@DroidDeckPreviews @Composable private fun DownloadsPreview() = Launcher("downloads")
@DroidDeckPreviews @Composable private fun SettingsPreview() = Launcher("setup")
@DroidDeckPreviews @Composable private fun RuntimeMissingPreview() = Launcher("setup", ready = false)
/** The in-game menu on one page, as a session shows it. */
@Composable
private fun SessionMenu(page: SessionDrawerPage, steam: Boolean = true, desktop: Boolean = false) = PreviewHost {
SessionDrawer(true, page, controllerActive = true, onPageChange = {}, a = sampleDrawerActions(steam, desktop))
}
@DroidDeckPreviews @Composable private fun SessionMenuControllerPreview() = SessionMenu(SessionDrawerPage.CONTROLLER)
@DroidDeckPreviews @Composable private fun SessionMenuDisplayPreview() = SessionMenu(SessionDrawerPage.DISPLAY)
@DroidDeckPreviews @Composable private fun SessionMenuHudPreview() = SessionMenu(SessionDrawerPage.HUD)
@DroidDeckPreviews @Composable private fun SessionMenuSessionPreview() = SessionMenu(SessionDrawerPage.SESSION)
@DroidDeckPreviews @Composable private fun SessionMenuDesktopPreview() = SessionMenu(SessionDrawerPage.CONTROLLER, steam = false, desktop = true)
/** The in-game menu docked on the bottom screen, with the screen picker in its header. */
@Composable
private fun DockedMenu(page: SessionDrawerPage) = PreviewHost {
SessionDrawer(true, page, controllerActive = false, onPageChange = {},
a = sampleDrawerActions(secondScreen = SecondScreenMode.KEYBOARD_TRACKPAD), docked = true)
}
/** The bottom screen's bar on a panel: the panel's name is the screen picker. */
@Composable
private fun BottomPanelBar() = PreviewHost {
val modes = secondScreenModes(false, deckPad = false, dashboard = true, desktop = false)
Column(Modifier.fillMaxSize().background(Color.Black)) {
BottomScreenBar(BottomBarModel("Keyboard + trackpad", {}, {}, {}, {},
listOf(BarExtra("Keyboard", icon = R.drawable.ic_bottom_keyboard) {}),
picker = ScreenPicker(modes, SecondScreenMode.KEYBOARD_TRACKPAD, {}, onMenu = {})))
}
}
@DroidDeckPreviews @Composable private fun SessionMenuDockedPreview() = DockedMenu(SessionDrawerPage.CONTROLLER)
@DroidDeckPreviews @Composable private fun SessionMenuDockedDisplayPreview() = DockedMenu(SessionDrawerPage.DISPLAY)
@DroidDeckPreviews @Composable private fun BottomPanelBarPreview() = BottomPanelBar()
/** The Library and Stores tabs read store accounts, which load on a background thread. */
private val storesLoaded = { com.droiddeck.launcher.stores.StoresState.accountsLoaded }
/** Every preview above, for the render test. Add a case when adding a preview. */
internal val previewCases: List<PreviewCase> = listOf(
PreviewCase("steam-tab") { Launcher("steam") },
PreviewCase("library", storesLoaded) { Launcher("games") },
PreviewCase("library-empty", storesLoaded) { Launcher("games", games = emptyList()) },
PreviewCase("stores", storesLoaded) { Launcher("stores") },
PreviewCase("downloads") { Launcher("downloads") },
PreviewCase("settings") { Launcher("setup") },
PreviewCase("runtime-missing") { Launcher("setup", ready = false) },
PreviewCase("session-menu-controller") { SessionMenu(SessionDrawerPage.CONTROLLER) },
PreviewCase("session-menu-display") { SessionMenu(SessionDrawerPage.DISPLAY) },
PreviewCase("session-menu-hud") { SessionMenu(SessionDrawerPage.HUD) },
PreviewCase("session-menu-session") { SessionMenu(SessionDrawerPage.SESSION) },
PreviewCase("session-menu-desktop") { SessionMenu(SessionDrawerPage.CONTROLLER, steam = false, desktop = true) },
PreviewCase("session-menu-docked") { DockedMenu(SessionDrawerPage.CONTROLLER) },
PreviewCase("session-menu-docked-display") { DockedMenu(SessionDrawerPage.DISPLAY) },
PreviewCase("bottom-panel-bar") { BottomPanelBar() },
)
@@ -1,88 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.session.SessionPrefs
/**
* Debug-only support for Compose previews: the production theme around a screen, and sample state and no-op actions so
* production composables render without a device, a runtime or a network. See docs/compose-previews.md.
*/
/** The sizes the previews come in. The Duo's top screen is 1920x1080 at xhdpi, i.e. 960x540 dp. */
@Preview(name = "Handheld", widthDp = 960, heightDp = 540, device = "spec:width=960dp,height=540dp,dpi=320,orientation=landscape")
@Preview(name = "Portrait", widthDp = 540, heightDp = 960, device = "spec:width=540dp,height=960dp,dpi=320")
internal annotation class DroidDeckPreviews
@Composable
internal fun PreviewHost(content: @Composable () -> Unit) {
DroidDeckTheme {
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) { content() }
}
}
/**
* A case the render test draws: a name for its PNG and the preview's content. [ready] is what the test waits for before
* drawing, for a screen that loads something off the main thread first.
*/
internal class PreviewCase(val name: String, val ready: () -> Boolean = { true }, val content: @Composable () -> Unit) {
override fun toString() = name
}
internal val sampleGames: List<Library.SteamGame> = listOf(
"Portal 2" to 620, "Hades" to 1145360, "Celeste" to 504230, "Stardew Valley" to 413150, "Hollow Knight" to 367520,
"Balatro" to 2379780, "Dead Cells" to 588650, "Terraria" to 105600, "Vampire Survivors" to 1794680, "Slay the Spire" to 646570,
).mapIndexed { i, (name, appId) ->
Library.SteamGame(appId, name, art = null, library = "steam", lastPlayed = 1_700_000_000_000L - i * 86_400_000L)
}
internal fun sampleState(
games: List<Library.SteamGame> = sampleGames,
navigate: String? = null,
ready: Boolean = true,
): FrontEndState = FrontEndState(
installed = "ubuntu-r1", ready = ready, available = "ubuntu-r1", busy = false, stage = "", percent = 0,
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "Off", romsDir = null, logsEnabled = true,
steamGames = games, emulators = emptyList(), running = null, navigate = navigate,
)
internal val sampleActions: FrontEndActions = FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {},
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> },
)
/** The in-game menu's actions with settled sample values; its switches do nothing. */
internal fun sampleDrawerActions(
steam: Boolean = true, desktop: Boolean = false, secondScreen: SecondScreenMode? = null,
): DrawerActions = DrawerActions(
steam = steam, desktop = desktop, title = if (!steam && !desktop) "Hades" else null,
isHomeApp = false, androidApps = emptyList(),
hudOn = true, onHud = {},
frameGen = FrameGen.Mode.OFF, onFrameGenPick = {},
lossless = Lossless.State.NONE,
oscMode = SessionPrefs.OSC_AUTO, onOsc = {},
suspendPolicy = SessionPrefs.SUSPEND_MANUAL, onSuspendPolicy = {},
backActionsInverted = false, onBackActionsInverted = {},
touchMode = SessionPrefs.TOUCH_AUTO, onTouch = {}, touchAuto = "Auto (direct)",
fexPreset = "", onFexPreset = {},
secondScreenMode = secondScreen ?: SecondScreenMode.NONE, onSecondScreenMode = {}, secondScreenNone = secondScreen == null,
secondScreenDisplays = listOfNotNull(secondScreen?.let { SecondScreenDisplay(2, "Built-in · 1240×1080") }),
selectedSecondScreenDisplay = if (secondScreen != null) 2 else -1, onSecondScreenDisplay = {},
gameSwapAvailable = secondScreen != null, dashboardAvailable = secondScreen != null,
onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null,
onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {},
)
-13
View File
@@ -4,9 +4,6 @@
<queries> <queries>
<package android:name="cn.nubia.gamelauncher" /> <package android:name="cn.nubia.gamelauncher" />
<intent>
<action android:name="android.speech.RecognitionService" />
</intent>
<intent> <intent>
<action android:name="android.content.pm.action.CONFIRM_INSTALL" /> <action android:name="android.content.pm.action.CONFIRM_INSTALL" />
</intent> </intent>
@@ -153,7 +150,6 @@
<category android:name="android.intent.category.CAR_LAUNCHER" /> <category android:name="android.intent.category.CAR_LAUNCHER" />
<data android:scheme="droiddeck" android:host="game" /> <data android:scheme="droiddeck" android:host="game" />
<data android:scheme="droiddeck" android:host="soundtrack" /> <data android:scheme="droiddeck" android:host="soundtrack" />
<data android:scheme="droiddeck" android:host="settings" />
</intent-filter> </intent-filter>
<intent-filter> <intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" /> <action android:name="android.intent.action.CREATE_SHORTCUT" />
@@ -302,15 +298,6 @@
android:resizeableActivity="true" android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" /> android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".session.KeepTopActivity"
android:exported="false"
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="${applicationId}.keeptop"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity <activity
android:name=".ui.SessionTypingActivity" android:name=".ui.SessionTypingActivity"
android:exported="false" android:exported="false"
+2 -33
View File
@@ -205,11 +205,6 @@ 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;
@@ -223,10 +218,6 @@ 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")));
@@ -596,7 +587,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 || !env_ready()) if (ring_paths_loaded)
return; return;
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS"); const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
@@ -816,25 +807,12 @@ __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();
@@ -1413,7 +1391,6 @@ 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;
} }
@@ -1421,7 +1398,6 @@ 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
@@ -1494,7 +1470,6 @@ __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;
@@ -2116,7 +2091,6 @@ 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");
@@ -2338,7 +2312,7 @@ __attribute__((visibility("hidden"))) static int inject_uevent(const char *actio
const char *subsystem, const char *devname, const char *subsystem, const char *devname,
unsigned major, unsigned minor) { unsigned major, unsigned minor) {
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned); using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "dd_udevmon_inject")); static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "bl_udevmon_inject"));
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1; return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
} }
@@ -2460,7 +2434,6 @@ __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;
} }
@@ -3716,10 +3689,6 @@ 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;
-100
View File
@@ -1,100 +0,0 @@
#version 450
layout(location = 0) in vec2 fragTexCoord;
layout(location = 0) out vec4 outColor;
layout(set = 0, binding = 0) uniform sampler2D InputTexture;
layout(push_constant) uniform Constants {
vec4 ndc;
vec2 resolution;
float extra;
float pad;
} pc;
float luma(vec3 c) {
return dot(c, vec3(0.2126, 0.7152, 0.0722));
}
float edgeVertical(vec2 uv, vec2 px) {
float a = luma(texture(InputTexture, uv - vec2(px.x, 0.0)).rgb);
float b = luma(texture(InputTexture, uv + vec2(px.x, 0.0)).rgb);
return abs(a - b);
}
float edgeHorizontal(vec2 uv, vec2 px) {
float a = luma(texture(InputTexture, uv - vec2(0.0, px.y)).rgb);
float b = luma(texture(InputTexture, uv + vec2(0.0, px.y)).rgb);
return abs(a - b);
}
void main() {
vec2 px = 1.0 / max(pc.resolution, vec2(1.0));
vec2 uv = clamp(fragTexCoord, px * 0.5, vec2(1.0) - px * 0.5);
vec4 center = texture(InputTexture, uv);
float lc = luma(center.rgb);
float ll = luma(texture(InputTexture, uv - vec2(px.x, 0.0)).rgb);
float lr = luma(texture(InputTexture, uv + vec2(px.x, 0.0)).rgb);
float lu = luma(texture(InputTexture, uv - vec2(0.0, px.y)).rgb);
float ld = luma(texture(InputTexture, uv + vec2(0.0, px.y)).rgb);
float dL = abs(lc - ll);
float dR = abs(lc - lr);
float dU = abs(lc - lu);
float dD = abs(lc - ld);
float localMin = min(lc, min(min(ll, lr), min(lu, ld)));
float localMax = max(lc, max(max(ll, lr), max(lu, ld)));
float localContrast = localMax - localMin;
float threshold = max(0.045, localContrast * 0.08);
float vertical = max(dL, dR);
float horizontal = max(dU, dD);
float strongest = max(vertical, horizontal);
if (strongest <= threshold) {
outColor = center;
return;
}
bool verticalEdge = vertical >= horizontal;
vec2 tangent = verticalEdge ? vec2(0.0, px.y) : vec2(px.x, 0.0);
vec2 normal = verticalEdge
? vec2(dL >= dR ? -1.0 : 1.0, 0.0)
: vec2(0.0, dU >= dD ? -1.0 : 1.0);
float negativeRun = 0.0;
float positiveRun = 0.0;
for (int i = 1; i <= 6; ++i) {
vec2 offset = tangent * float(i);
float edgeN = verticalEdge ? edgeVertical(uv - offset, px) : edgeHorizontal(uv - offset, px);
float edgeP = verticalEdge ? edgeVertical(uv + offset, px) : edgeHorizontal(uv + offset, px);
if (negativeRun == float(i - 1) && edgeN > threshold * 0.65) negativeRun = float(i);
if (positiveRun == float(i - 1) && edgeP > threshold * 0.65) positiveRun = float(i);
}
float span = negativeRun + positiveRun;
float edgeConfidence = smoothstep(threshold, threshold * 2.5, strongest);
float nw = luma(texture(InputTexture, uv + vec2(-px.x, -px.y)).rgb);
float ne = luma(texture(InputTexture, uv + vec2(px.x, -px.y)).rgb);
float sw = luma(texture(InputTexture, uv + vec2(-px.x, px.y)).rgb);
float se = luma(texture(InputTexture, uv + vec2(px.x, px.y)).rgb);
float endpointPattern = clamp(abs(negativeRun - positiveRun) / max(span, 1.0), 0.0, 1.0);
float endpointArea = endpointPattern / (1.0 + span * 0.055);
float crossingA = verticalEdge ? abs(nw - ne) : abs(nw - sw);
float crossingB = verticalEdge ? abs(sw - se) : abs(ne - se);
float crossingContrast = abs(crossingA - crossingB);
float crossingPattern = smoothstep(threshold, threshold * 2.5, crossingContrast);
float areaWeight = 0.38 * crossingPattern * clamp(span / 4.0, 0.0, 1.0);
float diagonalContrast = max(abs(nw - se), abs(ne - sw));
float cornerFactor = 1.0 - 0.35 * smoothstep(threshold, threshold * 3.0, diagonalContrast);
float baseWeight = areaWeight * endpointArea * edgeConfidence * cornerFactor;
float diagonalStrength = min(vertical, horizontal);
float diagonalPattern = smoothstep(threshold, threshold * 2.5, diagonalStrength);
float diagonalContinuity = smoothstep(1.0, 3.0, span);
float diagonalFallback = 0.16 * diagonalPattern * edgeConfidence
* cornerFactor * diagonalContinuity * crossingPattern;
float weight = clamp(max(baseWeight, diagonalFallback), 0.0, 0.42);
vec3 across = texture(InputTexture, uv + normal * px).rgb;
outColor = vec4(mix(center.rgb, across, weight), center.a);
}
-443
View File
@@ -1,443 +0,0 @@
#pragma once
#include <stdint.h>
static const uint32_t smaa_code[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000251u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000072u, 0x000000f6u, 0x00030010u,
0x00000004u, 0x00000007u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du,
0x00000000u, 0x00050005u, 0x0000000bu, 0x616d756cu, 0x33667628u, 0x0000003bu, 0x00030005u, 0x0000000au,
0x00000063u, 0x00080005u, 0x00000012u, 0x65676465u, 0x74726556u, 0x6c616369u, 0x32667628u, 0x3266763bu,
0x0000003bu, 0x00030005u, 0x00000010u, 0x00007675u, 0x00030005u, 0x00000011u, 0x00007870u, 0x00080005u,
0x00000016u, 0x65676465u, 0x69726f48u, 0x746e6f7au, 0x76286c61u, 0x763b3266u, 0x003b3266u, 0x00030005u,
0x00000014u, 0x00007675u, 0x00030005u, 0x00000015u, 0x00007870u, 0x00030005u, 0x00000021u, 0x00000061u,
0x00060005u, 0x00000025u, 0x75706e49u, 0x78655474u, 0x65727574u, 0x00000000u, 0x00040005u, 0x00000031u,
0x61726170u, 0x0000006du, 0x00030005u, 0x00000034u, 0x00000062u, 0x00040005u, 0x0000003cu, 0x61726170u,
0x0000006du, 0x00030005u, 0x00000045u, 0x00000061u, 0x00040005u, 0x0000004eu, 0x61726170u, 0x0000006du,
0x00030005u, 0x00000051u, 0x00000062u, 0x00040005u, 0x00000059u, 0x61726170u, 0x0000006du, 0x00030005u,
0x00000062u, 0x00007870u, 0x00050005u, 0x00000064u, 0x736e6f43u, 0x746e6174u, 0x00000073u, 0x00040006u,
0x00000064u, 0x00000000u, 0x0063646eu, 0x00060006u, 0x00000064u, 0x00000001u, 0x6f736572u, 0x6974756cu,
0x00006e6fu, 0x00050006u, 0x00000064u, 0x00000002u, 0x72747865u, 0x00000061u, 0x00040006u, 0x00000064u,
0x00000003u, 0x00646170u, 0x00030005u, 0x00000066u, 0x00006370u, 0x00030005u, 0x00000070u, 0x00007675u,
0x00060005u, 0x00000072u, 0x67617266u, 0x43786554u, 0x64726f6fu, 0x00000000u, 0x00040005u, 0x0000007cu,
0x746e6563u, 0x00007265u, 0x00030005u, 0x00000080u, 0x0000636cu, 0x00040005u, 0x00000081u, 0x61726170u,
0x0000006du, 0x00030005u, 0x00000085u, 0x00006c6cu, 0x00040005u, 0x0000008du, 0x61726170u, 0x0000006du,
0x00030005u, 0x00000090u, 0x0000726cu, 0x00040005u, 0x00000098u, 0x61726170u, 0x0000006du, 0x00030005u,
0x0000009bu, 0x0000756cu, 0x00040005u, 0x000000a3u, 0x61726170u, 0x0000006du, 0x00030005u, 0x000000a6u,
0x0000646cu, 0x00040005u, 0x000000aeu, 0x61726170u, 0x0000006du, 0x00030005u, 0x000000b1u, 0x00004c64u,
0x00030005u, 0x000000b6u, 0x00005264u, 0x00030005u, 0x000000bbu, 0x00005564u, 0x00030005u, 0x000000c0u,
0x00004464u, 0x00050005u, 0x000000c5u, 0x61636f6cu, 0x6e694d6cu, 0x00000000u, 0x00050005u, 0x000000cfu,
0x61636f6cu, 0x78614d6cu, 0x00000000u, 0x00060005u, 0x000000d9u, 0x61636f6cu, 0x6e6f436cu, 0x73617274u,
0x00000074u, 0x00050005u, 0x000000ddu, 0x65726874u, 0x6c6f6873u, 0x00000064u, 0x00050005u, 0x000000e3u,
0x74726576u, 0x6c616369u, 0x00000000u, 0x00050005u, 0x000000e7u, 0x69726f68u, 0x746e6f7au, 0x00006c61u,
0x00050005u, 0x000000ebu, 0x6f727473u, 0x7365676eu, 0x00000074u, 0x00050005u, 0x000000f6u, 0x4374756fu,
0x726f6c6fu, 0x00000000u, 0x00060005u, 0x000000fau, 0x74726576u, 0x6c616369u, 0x65676445u, 0x00000000u,
0x00040005u, 0x000000feu, 0x676e6174u, 0x00746e65u, 0x00040005u, 0x0000010bu, 0x6d726f6eu, 0x00006c61u,
0x00050005u, 0x0000011du, 0x6167656eu, 0x65766974u, 0x006e7552u, 0x00050005u, 0x0000011eu, 0x69736f70u,
0x65766974u, 0x006e7552u, 0x00030005u, 0x00000120u, 0x00000069u, 0x00040005u, 0x00000129u, 0x7366666fu,
0x00007465u, 0x00040005u, 0x0000012eu, 0x65676465u, 0x0000004eu, 0x00040005u, 0x00000136u, 0x61726170u,
0x0000006du, 0x00040005u, 0x00000137u, 0x61726170u, 0x0000006du, 0x00040005u, 0x0000013eu, 0x61726170u,
0x0000006du, 0x00040005u, 0x0000013fu, 0x61726170u, 0x0000006du, 0x00040005u, 0x00000143u, 0x65676465u,
0x00000050u, 0x00040005u, 0x0000014bu, 0x61726170u, 0x0000006du, 0x00040005u, 0x0000014cu, 0x61726170u,
0x0000006du, 0x00040005u, 0x00000153u, 0x61726170u, 0x0000006du, 0x00040005u, 0x00000154u, 0x61726170u,
0x0000006du, 0x00040005u, 0x0000017bu, 0x6e617073u, 0x00000000u, 0x00060005u, 0x0000017fu, 0x65676465u,
0x666e6f43u, 0x6e656469u, 0x00006563u, 0x00030005u, 0x00000186u, 0x0000776eu, 0x00040005u, 0x00000192u,
0x61726170u, 0x0000006du, 0x00030005u, 0x00000195u, 0x0000656eu, 0x00040005u, 0x000001a0u, 0x61726170u,
0x0000006du, 0x00030005u, 0x000001a3u, 0x00007773u, 0x00040005u, 0x000001aeu, 0x61726170u, 0x0000006du,
0x00030005u, 0x000001b1u, 0x00006573u, 0x00040005u, 0x000001bbu, 0x61726170u, 0x0000006du, 0x00060005u,
0x000001beu, 0x70646e65u, 0x746e696fu, 0x74746150u, 0x006e7265u, 0x00060005u, 0x000001c7u, 0x70646e65u,
0x746e696fu, 0x61657241u, 0x00000000u, 0x00050005u, 0x000001ceu, 0x736f7263u, 0x676e6973u, 0x00000041u,
0x00050005u, 0x000001ddu, 0x736f7263u, 0x676e6973u, 0x00000042u, 0x00070005u, 0x000001ecu, 0x736f7263u,
0x676e6973u, 0x746e6f43u, 0x74736172u, 0x00000000u, 0x00060005u, 0x000001f1u, 0x736f7263u, 0x676e6973u,
0x74746150u, 0x006e7265u, 0x00050005u, 0x000001f7u, 0x61657261u, 0x67696557u, 0x00007468u, 0x00070005u,
0x00000200u, 0x67616964u, 0x6c616e6fu, 0x746e6f43u, 0x74736172u, 0x00000000u, 0x00060005u, 0x0000020au,
0x6e726f63u, 0x61467265u, 0x726f7463u, 0x00000000u, 0x00050005u, 0x00000214u, 0x65736162u, 0x67696557u,
0x00007468u, 0x00070005u, 0x0000021cu, 0x67616964u, 0x6c616e6fu, 0x65727453u, 0x6874676eu, 0x00000000u,
0x00060005u, 0x00000220u, 0x67616964u, 0x6c616e6fu, 0x74746150u, 0x006e7265u, 0x00070005u, 0x00000226u,
0x67616964u, 0x6c616e6fu, 0x746e6f43u, 0x69756e69u, 0x00007974u, 0x00070005u, 0x00000229u, 0x67616964u,
0x6c616e6fu, 0x6c6c6146u, 0x6b636162u, 0x00000000u, 0x00040005u, 0x00000235u, 0x67696577u, 0x00007468u,
0x00040005u, 0x0000023bu, 0x6f726361u, 0x00007373u, 0x00040047u, 0x00000025u, 0x00000021u, 0x00000000u,
0x00040047u, 0x00000025u, 0x00000022u, 0x00000000u, 0x00030047u, 0x00000064u, 0x00000002u, 0x00050048u,
0x00000064u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000064u, 0x00000001u, 0x00000023u,
0x00000010u, 0x00050048u, 0x00000064u, 0x00000002u, 0x00000023u, 0x00000018u, 0x00050048u, 0x00000064u,
0x00000003u, 0x00000023u, 0x0000001cu, 0x00040047u, 0x00000072u, 0x0000001eu, 0x00000000u, 0x00040047u,
0x000000f6u, 0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u,
0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000003u, 0x00040020u,
0x00000008u, 0x00000007u, 0x00000007u, 0x00040021u, 0x00000009u, 0x00000006u, 0x00000008u, 0x00040017u,
0x0000000du, 0x00000006u, 0x00000002u, 0x00040020u, 0x0000000eu, 0x00000007u, 0x0000000du, 0x00050021u,
0x0000000fu, 0x00000006u, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u, 0x00000019u, 0x3e59b3d0u,
0x0004002bu, 0x00000006u, 0x0000001au, 0x3f371759u, 0x0004002bu, 0x00000006u, 0x0000001bu, 0x3d93dd98u,
0x0006002cu, 0x00000007u, 0x0000001cu, 0x00000019u, 0x0000001au, 0x0000001bu, 0x00040020u, 0x00000020u,
0x00000007u, 0x00000006u, 0x00090019u, 0x00000022u, 0x00000006u, 0x00000001u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x00000023u, 0x00000022u, 0x00040020u, 0x00000024u,
0x00000000u, 0x00000023u, 0x0004003bu, 0x00000024u, 0x00000025u, 0x00000000u, 0x00040015u, 0x00000028u,
0x00000020u, 0x00000000u, 0x0004002bu, 0x00000028u, 0x00000029u, 0x00000000u, 0x0004002bu, 0x00000006u,
0x0000002cu, 0x00000000u, 0x00040017u, 0x0000002fu, 0x00000006u, 0x00000004u, 0x0004002bu, 0x00000028u,
0x00000048u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000063u, 0x3f800000u, 0x0006001eu, 0x00000064u,
0x0000002fu, 0x0000000du, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000065u, 0x00000009u, 0x00000064u,
0x0004003bu, 0x00000065u, 0x00000066u, 0x00000009u, 0x00040015u, 0x00000067u, 0x00000020u, 0x00000001u,
0x0004002bu, 0x00000067u, 0x00000068u, 0x00000001u, 0x00040020u, 0x00000069u, 0x00000009u, 0x0000000du,
0x0005002cu, 0x0000000du, 0x0000006cu, 0x00000063u, 0x00000063u, 0x00040020u, 0x00000071u, 0x00000001u,
0x0000000du, 0x0004003bu, 0x00000071u, 0x00000072u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000075u,
0x3f000000u, 0x00040020u, 0x0000007bu, 0x00000007u, 0x0000002fu, 0x0004002bu, 0x00000006u, 0x000000deu,
0x3d3851ecu, 0x0004002bu, 0x00000006u, 0x000000e0u, 0x3da3d70au, 0x00020014u, 0x000000f1u, 0x00040020u,
0x000000f5u, 0x00000003u, 0x0000002fu, 0x0004003bu, 0x000000f5u, 0x000000f6u, 0x00000003u, 0x00040020u,
0x000000f9u, 0x00000007u, 0x000000f1u, 0x0004002bu, 0x00000006u, 0x00000113u, 0xbf800000u, 0x00040020u,
0x0000011fu, 0x00000007u, 0x00000067u, 0x0004002bu, 0x00000067u, 0x00000127u, 0x00000006u, 0x0004002bu,
0x00000006u, 0x00000161u, 0x3f266666u, 0x0004002bu, 0x00000006u, 0x00000182u, 0x40200000u, 0x0004002bu,
0x00000006u, 0x000001cau, 0x3d6147aeu, 0x0004002bu, 0x00000006u, 0x000001f8u, 0x3ec28f5cu, 0x0004002bu,
0x00000006u, 0x000001fcu, 0x40800000u, 0x0004002bu, 0x00000006u, 0x0000020bu, 0x3eb33333u, 0x0004002bu,
0x00000006u, 0x0000020eu, 0x40400000u, 0x0004002bu, 0x00000006u, 0x0000022au, 0x3e23d70au, 0x0004002bu,
0x00000006u, 0x00000239u, 0x3ed70a3du, 0x0004002bu, 0x00000028u, 0x0000024au, 0x00000003u, 0x00050036u,
0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x0000000eu,
0x00000062u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000070u, 0x00000007u, 0x0004003bu, 0x0000007bu,
0x0000007cu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000080u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000081u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000085u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x0000008du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000090u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000098u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000009bu, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000000a3u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000a6u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000000aeu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000b1u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000b6u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000bbu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000c0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000c5u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000cfu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000d9u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000ddu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000e3u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000000e7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000ebu, 0x00000007u, 0x0004003bu, 0x000000f9u,
0x000000fau, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x000000feu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000100u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000010bu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000010du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000011du, 0x00000007u, 0x0004003bu, 0x00000020u,
0x0000011eu, 0x00000007u, 0x0004003bu, 0x0000011fu, 0x00000120u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000129u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000012eu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000130u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000136u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000137u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000013eu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000013fu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000143u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000145u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000014bu, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x0000014cu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000153u, 0x00000007u, 0x0004003bu, 0x0000000eu,
0x00000154u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000017bu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x0000017fu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000186u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x00000192u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000195u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001a0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001a3u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001aeu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001b1u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x000001bbu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001beu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001c7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ceu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001d0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ddu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001dfu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ecu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x000001f1u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001f7u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000200u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000020au, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000214u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000021cu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000220u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000226u, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000229u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000235u, 0x00000007u, 0x0004003bu, 0x00000008u,
0x0000023bu, 0x00000007u, 0x00050041u, 0x00000069u, 0x0000006au, 0x00000066u, 0x00000068u, 0x0004003du,
0x0000000du, 0x0000006bu, 0x0000006au, 0x0007000cu, 0x0000000du, 0x0000006du, 0x00000001u, 0x00000028u,
0x0000006bu, 0x0000006cu, 0x00050050u, 0x0000000du, 0x0000006eu, 0x00000063u, 0x00000063u, 0x00050088u,
0x0000000du, 0x0000006fu, 0x0000006eu, 0x0000006du, 0x0003003eu, 0x00000062u, 0x0000006fu, 0x0004003du,
0x0000000du, 0x00000073u, 0x00000072u, 0x0004003du, 0x0000000du, 0x00000074u, 0x00000062u, 0x0005008eu,
0x0000000du, 0x00000076u, 0x00000074u, 0x00000075u, 0x0004003du, 0x0000000du, 0x00000077u, 0x00000062u,
0x0005008eu, 0x0000000du, 0x00000078u, 0x00000077u, 0x00000075u, 0x00050083u, 0x0000000du, 0x00000079u,
0x0000006cu, 0x00000078u, 0x0008000cu, 0x0000000du, 0x0000007au, 0x00000001u, 0x0000002bu, 0x00000073u,
0x00000076u, 0x00000079u, 0x0003003eu, 0x00000070u, 0x0000007au, 0x0004003du, 0x00000023u, 0x0000007du,
0x00000025u, 0x0004003du, 0x0000000du, 0x0000007eu, 0x00000070u, 0x00050057u, 0x0000002fu, 0x0000007fu,
0x0000007du, 0x0000007eu, 0x0003003eu, 0x0000007cu, 0x0000007fu, 0x0004003du, 0x0000002fu, 0x00000082u,
0x0000007cu, 0x0008004fu, 0x00000007u, 0x00000083u, 0x00000082u, 0x00000082u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x00000081u, 0x00000083u, 0x00050039u, 0x00000006u, 0x00000084u, 0x0000000bu,
0x00000081u, 0x0003003eu, 0x00000080u, 0x00000084u, 0x0004003du, 0x00000023u, 0x00000086u, 0x00000025u,
0x0004003du, 0x0000000du, 0x00000087u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000088u, 0x00000062u,
0x00000029u, 0x0004003du, 0x00000006u, 0x00000089u, 0x00000088u, 0x00050050u, 0x0000000du, 0x0000008au,
0x00000089u, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000008bu, 0x00000087u, 0x0000008au, 0x00050057u,
0x0000002fu, 0x0000008cu, 0x00000086u, 0x0000008bu, 0x0008004fu, 0x00000007u, 0x0000008eu, 0x0000008cu,
0x0000008cu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000008du, 0x0000008eu, 0x00050039u,
0x00000006u, 0x0000008fu, 0x0000000bu, 0x0000008du, 0x0003003eu, 0x00000085u, 0x0000008fu, 0x0004003du,
0x00000023u, 0x00000091u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000092u, 0x00000070u, 0x00050041u,
0x00000020u, 0x00000093u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000094u, 0x00000093u,
0x00050050u, 0x0000000du, 0x00000095u, 0x00000094u, 0x0000002cu, 0x00050081u, 0x0000000du, 0x00000096u,
0x00000092u, 0x00000095u, 0x00050057u, 0x0000002fu, 0x00000097u, 0x00000091u, 0x00000096u, 0x0008004fu,
0x00000007u, 0x00000099u, 0x00000097u, 0x00000097u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu,
0x00000098u, 0x00000099u, 0x00050039u, 0x00000006u, 0x0000009au, 0x0000000bu, 0x00000098u, 0x0003003eu,
0x00000090u, 0x0000009au, 0x0004003du, 0x00000023u, 0x0000009cu, 0x00000025u, 0x0004003du, 0x0000000du,
0x0000009du, 0x00000070u, 0x00050041u, 0x00000020u, 0x0000009eu, 0x00000062u, 0x00000048u, 0x0004003du,
0x00000006u, 0x0000009fu, 0x0000009eu, 0x00050050u, 0x0000000du, 0x000000a0u, 0x0000002cu, 0x0000009fu,
0x00050083u, 0x0000000du, 0x000000a1u, 0x0000009du, 0x000000a0u, 0x00050057u, 0x0000002fu, 0x000000a2u,
0x0000009cu, 0x000000a1u, 0x0008004fu, 0x00000007u, 0x000000a4u, 0x000000a2u, 0x000000a2u, 0x00000000u,
0x00000001u, 0x00000002u, 0x0003003eu, 0x000000a3u, 0x000000a4u, 0x00050039u, 0x00000006u, 0x000000a5u,
0x0000000bu, 0x000000a3u, 0x0003003eu, 0x0000009bu, 0x000000a5u, 0x0004003du, 0x00000023u, 0x000000a7u,
0x00000025u, 0x0004003du, 0x0000000du, 0x000000a8u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000000a9u,
0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000000aau, 0x000000a9u, 0x00050050u, 0x0000000du,
0x000000abu, 0x0000002cu, 0x000000aau, 0x00050081u, 0x0000000du, 0x000000acu, 0x000000a8u, 0x000000abu,
0x00050057u, 0x0000002fu, 0x000000adu, 0x000000a7u, 0x000000acu, 0x0008004fu, 0x00000007u, 0x000000afu,
0x000000adu, 0x000000adu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000aeu, 0x000000afu,
0x00050039u, 0x00000006u, 0x000000b0u, 0x0000000bu, 0x000000aeu, 0x0003003eu, 0x000000a6u, 0x000000b0u,
0x0004003du, 0x00000006u, 0x000000b2u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b3u, 0x00000085u,
0x00050083u, 0x00000006u, 0x000000b4u, 0x000000b2u, 0x000000b3u, 0x0006000cu, 0x00000006u, 0x000000b5u,
0x00000001u, 0x00000004u, 0x000000b4u, 0x0003003eu, 0x000000b1u, 0x000000b5u, 0x0004003du, 0x00000006u,
0x000000b7u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b8u, 0x00000090u, 0x00050083u, 0x00000006u,
0x000000b9u, 0x000000b7u, 0x000000b8u, 0x0006000cu, 0x00000006u, 0x000000bau, 0x00000001u, 0x00000004u,
0x000000b9u, 0x0003003eu, 0x000000b6u, 0x000000bau, 0x0004003du, 0x00000006u, 0x000000bcu, 0x00000080u,
0x0004003du, 0x00000006u, 0x000000bdu, 0x0000009bu, 0x00050083u, 0x00000006u, 0x000000beu, 0x000000bcu,
0x000000bdu, 0x0006000cu, 0x00000006u, 0x000000bfu, 0x00000001u, 0x00000004u, 0x000000beu, 0x0003003eu,
0x000000bbu, 0x000000bfu, 0x0004003du, 0x00000006u, 0x000000c1u, 0x00000080u, 0x0004003du, 0x00000006u,
0x000000c2u, 0x000000a6u, 0x00050083u, 0x00000006u, 0x000000c3u, 0x000000c1u, 0x000000c2u, 0x0006000cu,
0x00000006u, 0x000000c4u, 0x00000001u, 0x00000004u, 0x000000c3u, 0x0003003eu, 0x000000c0u, 0x000000c4u,
0x0004003du, 0x00000006u, 0x000000c6u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000c7u, 0x00000085u,
0x0004003du, 0x00000006u, 0x000000c8u, 0x00000090u, 0x0007000cu, 0x00000006u, 0x000000c9u, 0x00000001u,
0x00000025u, 0x000000c7u, 0x000000c8u, 0x0004003du, 0x00000006u, 0x000000cau, 0x0000009bu, 0x0004003du,
0x00000006u, 0x000000cbu, 0x000000a6u, 0x0007000cu, 0x00000006u, 0x000000ccu, 0x00000001u, 0x00000025u,
0x000000cau, 0x000000cbu, 0x0007000cu, 0x00000006u, 0x000000cdu, 0x00000001u, 0x00000025u, 0x000000c9u,
0x000000ccu, 0x0007000cu, 0x00000006u, 0x000000ceu, 0x00000001u, 0x00000025u, 0x000000c6u, 0x000000cdu,
0x0003003eu, 0x000000c5u, 0x000000ceu, 0x0004003du, 0x00000006u, 0x000000d0u, 0x00000080u, 0x0004003du,
0x00000006u, 0x000000d1u, 0x00000085u, 0x0004003du, 0x00000006u, 0x000000d2u, 0x00000090u, 0x0007000cu,
0x00000006u, 0x000000d3u, 0x00000001u, 0x00000028u, 0x000000d1u, 0x000000d2u, 0x0004003du, 0x00000006u,
0x000000d4u, 0x0000009bu, 0x0004003du, 0x00000006u, 0x000000d5u, 0x000000a6u, 0x0007000cu, 0x00000006u,
0x000000d6u, 0x00000001u, 0x00000028u, 0x000000d4u, 0x000000d5u, 0x0007000cu, 0x00000006u, 0x000000d7u,
0x00000001u, 0x00000028u, 0x000000d3u, 0x000000d6u, 0x0007000cu, 0x00000006u, 0x000000d8u, 0x00000001u,
0x00000028u, 0x000000d0u, 0x000000d7u, 0x0003003eu, 0x000000cfu, 0x000000d8u, 0x0004003du, 0x00000006u,
0x000000dau, 0x000000cfu, 0x0004003du, 0x00000006u, 0x000000dbu, 0x000000c5u, 0x00050083u, 0x00000006u,
0x000000dcu, 0x000000dau, 0x000000dbu, 0x0003003eu, 0x000000d9u, 0x000000dcu, 0x0004003du, 0x00000006u,
0x000000dfu, 0x000000d9u, 0x00050085u, 0x00000006u, 0x000000e1u, 0x000000dfu, 0x000000e0u, 0x0007000cu,
0x00000006u, 0x000000e2u, 0x00000001u, 0x00000028u, 0x000000deu, 0x000000e1u, 0x0003003eu, 0x000000ddu,
0x000000e2u, 0x0004003du, 0x00000006u, 0x000000e4u, 0x000000b1u, 0x0004003du, 0x00000006u, 0x000000e5u,
0x000000b6u, 0x0007000cu, 0x00000006u, 0x000000e6u, 0x00000001u, 0x00000028u, 0x000000e4u, 0x000000e5u,
0x0003003eu, 0x000000e3u, 0x000000e6u, 0x0004003du, 0x00000006u, 0x000000e8u, 0x000000bbu, 0x0004003du,
0x00000006u, 0x000000e9u, 0x000000c0u, 0x0007000cu, 0x00000006u, 0x000000eau, 0x00000001u, 0x00000028u,
0x000000e8u, 0x000000e9u, 0x0003003eu, 0x000000e7u, 0x000000eau, 0x0004003du, 0x00000006u, 0x000000ecu,
0x000000e3u, 0x0004003du, 0x00000006u, 0x000000edu, 0x000000e7u, 0x0007000cu, 0x00000006u, 0x000000eeu,
0x00000001u, 0x00000028u, 0x000000ecu, 0x000000edu, 0x0003003eu, 0x000000ebu, 0x000000eeu, 0x0004003du,
0x00000006u, 0x000000efu, 0x000000ebu, 0x0004003du, 0x00000006u, 0x000000f0u, 0x000000ddu, 0x000500bcu,
0x000000f1u, 0x000000f2u, 0x000000efu, 0x000000f0u, 0x000300f7u, 0x000000f4u, 0x00000000u, 0x000400fau,
0x000000f2u, 0x000000f3u, 0x000000f4u, 0x000200f8u, 0x000000f3u, 0x0004003du, 0x0000002fu, 0x000000f7u,
0x0000007cu, 0x0003003eu, 0x000000f6u, 0x000000f7u, 0x000100fdu, 0x000200f8u, 0x000000f4u, 0x0004003du,
0x00000006u, 0x000000fbu, 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000fcu, 0x000000e7u, 0x000500beu,
0x000000f1u, 0x000000fdu, 0x000000fbu, 0x000000fcu, 0x0003003eu, 0x000000fau, 0x000000fdu, 0x0004003du,
0x000000f1u, 0x000000ffu, 0x000000fau, 0x000300f7u, 0x00000102u, 0x00000000u, 0x000400fau, 0x000000ffu,
0x00000101u, 0x00000106u, 0x000200f8u, 0x00000101u, 0x00050041u, 0x00000020u, 0x00000103u, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x00000104u, 0x00000103u, 0x00050050u, 0x0000000du, 0x00000105u,
0x0000002cu, 0x00000104u, 0x0003003eu, 0x00000100u, 0x00000105u, 0x000200f9u, 0x00000102u, 0x000200f8u,
0x00000106u, 0x00050041u, 0x00000020u, 0x00000107u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u,
0x00000108u, 0x00000107u, 0x00050050u, 0x0000000du, 0x00000109u, 0x00000108u, 0x0000002cu, 0x0003003eu,
0x00000100u, 0x00000109u, 0x000200f9u, 0x00000102u, 0x000200f8u, 0x00000102u, 0x0004003du, 0x0000000du,
0x0000010au, 0x00000100u, 0x0003003eu, 0x000000feu, 0x0000010au, 0x0004003du, 0x000000f1u, 0x0000010cu,
0x000000fau, 0x000300f7u, 0x0000010fu, 0x00000000u, 0x000400fau, 0x0000010cu, 0x0000010eu, 0x00000116u,
0x000200f8u, 0x0000010eu, 0x0004003du, 0x00000006u, 0x00000110u, 0x000000b1u, 0x0004003du, 0x00000006u,
0x00000111u, 0x000000b6u, 0x000500beu, 0x000000f1u, 0x00000112u, 0x00000110u, 0x00000111u, 0x000600a9u,
0x00000006u, 0x00000114u, 0x00000112u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x00000115u,
0x00000114u, 0x0000002cu, 0x0003003eu, 0x0000010du, 0x00000115u, 0x000200f9u, 0x0000010fu, 0x000200f8u,
0x00000116u, 0x0004003du, 0x00000006u, 0x00000117u, 0x000000bbu, 0x0004003du, 0x00000006u, 0x00000118u,
0x000000c0u, 0x000500beu, 0x000000f1u, 0x00000119u, 0x00000117u, 0x00000118u, 0x000600a9u, 0x00000006u,
0x0000011au, 0x00000119u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x0000011bu, 0x0000002cu,
0x0000011au, 0x0003003eu, 0x0000010du, 0x0000011bu, 0x000200f9u, 0x0000010fu, 0x000200f8u, 0x0000010fu,
0x0004003du, 0x0000000du, 0x0000011cu, 0x0000010du, 0x0003003eu, 0x0000010bu, 0x0000011cu, 0x0003003eu,
0x0000011du, 0x0000002cu, 0x0003003eu, 0x0000011eu, 0x0000002cu, 0x0003003eu, 0x00000120u, 0x00000068u,
0x000200f9u, 0x00000121u, 0x000200f8u, 0x00000121u, 0x000400f6u, 0x00000123u, 0x00000124u, 0x00000000u,
0x000200f9u, 0x00000125u, 0x000200f8u, 0x00000125u, 0x0004003du, 0x00000067u, 0x00000126u, 0x00000120u,
0x000500b3u, 0x000000f1u, 0x00000128u, 0x00000126u, 0x00000127u, 0x000400fau, 0x00000128u, 0x00000122u,
0x00000123u, 0x000200f8u, 0x00000122u, 0x0004003du, 0x0000000du, 0x0000012au, 0x000000feu, 0x0004003du,
0x00000067u, 0x0000012bu, 0x00000120u, 0x0004006fu, 0x00000006u, 0x0000012cu, 0x0000012bu, 0x0005008eu,
0x0000000du, 0x0000012du, 0x0000012au, 0x0000012cu, 0x0003003eu, 0x00000129u, 0x0000012du, 0x0004003du,
0x000000f1u, 0x0000012fu, 0x000000fau, 0x000300f7u, 0x00000132u, 0x00000000u, 0x000400fau, 0x0000012fu,
0x00000131u, 0x0000013au, 0x000200f8u, 0x00000131u, 0x0004003du, 0x0000000du, 0x00000133u, 0x00000070u,
0x0004003du, 0x0000000du, 0x00000134u, 0x00000129u, 0x00050083u, 0x0000000du, 0x00000135u, 0x00000133u,
0x00000134u, 0x0003003eu, 0x00000136u, 0x00000135u, 0x0004003du, 0x0000000du, 0x00000138u, 0x00000062u,
0x0003003eu, 0x00000137u, 0x00000138u, 0x00060039u, 0x00000006u, 0x00000139u, 0x00000012u, 0x00000136u,
0x00000137u, 0x0003003eu, 0x00000130u, 0x00000139u, 0x000200f9u, 0x00000132u, 0x000200f8u, 0x0000013au,
0x0004003du, 0x0000000du, 0x0000013bu, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000013cu, 0x00000129u,
0x00050083u, 0x0000000du, 0x0000013du, 0x0000013bu, 0x0000013cu, 0x0003003eu, 0x0000013eu, 0x0000013du,
0x0004003du, 0x0000000du, 0x00000140u, 0x00000062u, 0x0003003eu, 0x0000013fu, 0x00000140u, 0x00060039u,
0x00000006u, 0x00000141u, 0x00000016u, 0x0000013eu, 0x0000013fu, 0x0003003eu, 0x00000130u, 0x00000141u,
0x000200f9u, 0x00000132u, 0x000200f8u, 0x00000132u, 0x0004003du, 0x00000006u, 0x00000142u, 0x00000130u,
0x0003003eu, 0x0000012eu, 0x00000142u, 0x0004003du, 0x000000f1u, 0x00000144u, 0x000000fau, 0x000300f7u,
0x00000147u, 0x00000000u, 0x000400fau, 0x00000144u, 0x00000146u, 0x0000014fu, 0x000200f8u, 0x00000146u,
0x0004003du, 0x0000000du, 0x00000148u, 0x00000070u, 0x0004003du, 0x0000000du, 0x00000149u, 0x00000129u,
0x00050081u, 0x0000000du, 0x0000014au, 0x00000148u, 0x00000149u, 0x0003003eu, 0x0000014bu, 0x0000014au,
0x0004003du, 0x0000000du, 0x0000014du, 0x00000062u, 0x0003003eu, 0x0000014cu, 0x0000014du, 0x00060039u,
0x00000006u, 0x0000014eu, 0x00000012u, 0x0000014bu, 0x0000014cu, 0x0003003eu, 0x00000145u, 0x0000014eu,
0x000200f9u, 0x00000147u, 0x000200f8u, 0x0000014fu, 0x0004003du, 0x0000000du, 0x00000150u, 0x00000070u,
0x0004003du, 0x0000000du, 0x00000151u, 0x00000129u, 0x00050081u, 0x0000000du, 0x00000152u, 0x00000150u,
0x00000151u, 0x0003003eu, 0x00000153u, 0x00000152u, 0x0004003du, 0x0000000du, 0x00000155u, 0x00000062u,
0x0003003eu, 0x00000154u, 0x00000155u, 0x00060039u, 0x00000006u, 0x00000156u, 0x00000016u, 0x00000153u,
0x00000154u, 0x0003003eu, 0x00000145u, 0x00000156u, 0x000200f9u, 0x00000147u, 0x000200f8u, 0x00000147u,
0x0004003du, 0x00000006u, 0x00000157u, 0x00000145u, 0x0003003eu, 0x00000143u, 0x00000157u, 0x0004003du,
0x00000006u, 0x00000158u, 0x0000011du, 0x0004003du, 0x00000067u, 0x00000159u, 0x00000120u, 0x00050082u,
0x00000067u, 0x0000015au, 0x00000159u, 0x00000068u, 0x0004006fu, 0x00000006u, 0x0000015bu, 0x0000015au,
0x000500b4u, 0x000000f1u, 0x0000015cu, 0x00000158u, 0x0000015bu, 0x000300f7u, 0x0000015eu, 0x00000000u,
0x000400fau, 0x0000015cu, 0x0000015du, 0x0000015eu, 0x000200f8u, 0x0000015du, 0x0004003du, 0x00000006u,
0x0000015fu, 0x0000012eu, 0x0004003du, 0x00000006u, 0x00000160u, 0x000000ddu, 0x00050085u, 0x00000006u,
0x00000162u, 0x00000160u, 0x00000161u, 0x000500bau, 0x000000f1u, 0x00000163u, 0x0000015fu, 0x00000162u,
0x000200f9u, 0x0000015eu, 0x000200f8u, 0x0000015eu, 0x000700f5u, 0x000000f1u, 0x00000164u, 0x0000015cu,
0x00000147u, 0x00000163u, 0x0000015du, 0x000300f7u, 0x00000166u, 0x00000000u, 0x000400fau, 0x00000164u,
0x00000165u, 0x00000166u, 0x000200f8u, 0x00000165u, 0x0004003du, 0x00000067u, 0x00000167u, 0x00000120u,
0x0004006fu, 0x00000006u, 0x00000168u, 0x00000167u, 0x0003003eu, 0x0000011du, 0x00000168u, 0x000200f9u,
0x00000166u, 0x000200f8u, 0x00000166u, 0x0004003du, 0x00000006u, 0x00000169u, 0x0000011eu, 0x0004003du,
0x00000067u, 0x0000016au, 0x00000120u, 0x00050082u, 0x00000067u, 0x0000016bu, 0x0000016au, 0x00000068u,
0x0004006fu, 0x00000006u, 0x0000016cu, 0x0000016bu, 0x000500b4u, 0x000000f1u, 0x0000016du, 0x00000169u,
0x0000016cu, 0x000300f7u, 0x0000016fu, 0x00000000u, 0x000400fau, 0x0000016du, 0x0000016eu, 0x0000016fu,
0x000200f8u, 0x0000016eu, 0x0004003du, 0x00000006u, 0x00000170u, 0x00000143u, 0x0004003du, 0x00000006u,
0x00000171u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000172u, 0x00000171u, 0x00000161u, 0x000500bau,
0x000000f1u, 0x00000173u, 0x00000170u, 0x00000172u, 0x000200f9u, 0x0000016fu, 0x000200f8u, 0x0000016fu,
0x000700f5u, 0x000000f1u, 0x00000174u, 0x0000016du, 0x00000166u, 0x00000173u, 0x0000016eu, 0x000300f7u,
0x00000176u, 0x00000000u, 0x000400fau, 0x00000174u, 0x00000175u, 0x00000176u, 0x000200f8u, 0x00000175u,
0x0004003du, 0x00000067u, 0x00000177u, 0x00000120u, 0x0004006fu, 0x00000006u, 0x00000178u, 0x00000177u,
0x0003003eu, 0x0000011eu, 0x00000178u, 0x000200f9u, 0x00000176u, 0x000200f8u, 0x00000176u, 0x000200f9u,
0x00000124u, 0x000200f8u, 0x00000124u, 0x0004003du, 0x00000067u, 0x00000179u, 0x00000120u, 0x00050080u,
0x00000067u, 0x0000017au, 0x00000179u, 0x00000068u, 0x0003003eu, 0x00000120u, 0x0000017au, 0x000200f9u,
0x00000121u, 0x000200f8u, 0x00000123u, 0x0004003du, 0x00000006u, 0x0000017cu, 0x0000011du, 0x0004003du,
0x00000006u, 0x0000017du, 0x0000011eu, 0x00050081u, 0x00000006u, 0x0000017eu, 0x0000017cu, 0x0000017du,
0x0003003eu, 0x0000017bu, 0x0000017eu, 0x0004003du, 0x00000006u, 0x00000180u, 0x000000ddu, 0x0004003du,
0x00000006u, 0x00000181u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000183u, 0x00000181u, 0x00000182u,
0x0004003du, 0x00000006u, 0x00000184u, 0x000000ebu, 0x0008000cu, 0x00000006u, 0x00000185u, 0x00000001u,
0x00000031u, 0x00000180u, 0x00000183u, 0x00000184u, 0x0003003eu, 0x0000017fu, 0x00000185u, 0x0004003du,
0x00000023u, 0x00000187u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000188u, 0x00000070u, 0x00050041u,
0x00000020u, 0x00000189u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000018au, 0x00000189u,
0x0004007fu, 0x00000006u, 0x0000018bu, 0x0000018au, 0x00050041u, 0x00000020u, 0x0000018cu, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x0000018du, 0x0000018cu, 0x0004007fu, 0x00000006u, 0x0000018eu,
0x0000018du, 0x00050050u, 0x0000000du, 0x0000018fu, 0x0000018bu, 0x0000018eu, 0x00050081u, 0x0000000du,
0x00000190u, 0x00000188u, 0x0000018fu, 0x00050057u, 0x0000002fu, 0x00000191u, 0x00000187u, 0x00000190u,
0x0008004fu, 0x00000007u, 0x00000193u, 0x00000191u, 0x00000191u, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x00000192u, 0x00000193u, 0x00050039u, 0x00000006u, 0x00000194u, 0x0000000bu, 0x00000192u,
0x0003003eu, 0x00000186u, 0x00000194u, 0x0004003du, 0x00000023u, 0x00000196u, 0x00000025u, 0x0004003du,
0x0000000du, 0x00000197u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000198u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x00000199u, 0x00000198u, 0x00050041u, 0x00000020u, 0x0000019au, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x0000019bu, 0x0000019au, 0x0004007fu, 0x00000006u, 0x0000019cu,
0x0000019bu, 0x00050050u, 0x0000000du, 0x0000019du, 0x00000199u, 0x0000019cu, 0x00050081u, 0x0000000du,
0x0000019eu, 0x00000197u, 0x0000019du, 0x00050057u, 0x0000002fu, 0x0000019fu, 0x00000196u, 0x0000019eu,
0x0008004fu, 0x00000007u, 0x000001a1u, 0x0000019fu, 0x0000019fu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x000001a0u, 0x000001a1u, 0x00050039u, 0x00000006u, 0x000001a2u, 0x0000000bu, 0x000001a0u,
0x0003003eu, 0x00000195u, 0x000001a2u, 0x0004003du, 0x00000023u, 0x000001a4u, 0x00000025u, 0x0004003du,
0x0000000du, 0x000001a5u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001a6u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x000001a7u, 0x000001a6u, 0x0004007fu, 0x00000006u, 0x000001a8u, 0x000001a7u,
0x00050041u, 0x00000020u, 0x000001a9u, 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000001aau,
0x000001a9u, 0x00050050u, 0x0000000du, 0x000001abu, 0x000001a8u, 0x000001aau, 0x00050081u, 0x0000000du,
0x000001acu, 0x000001a5u, 0x000001abu, 0x00050057u, 0x0000002fu, 0x000001adu, 0x000001a4u, 0x000001acu,
0x0008004fu, 0x00000007u, 0x000001afu, 0x000001adu, 0x000001adu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x000001aeu, 0x000001afu, 0x00050039u, 0x00000006u, 0x000001b0u, 0x0000000bu, 0x000001aeu,
0x0003003eu, 0x000001a3u, 0x000001b0u, 0x0004003du, 0x00000023u, 0x000001b2u, 0x00000025u, 0x0004003du,
0x0000000du, 0x000001b3u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001b4u, 0x00000062u, 0x00000029u,
0x0004003du, 0x00000006u, 0x000001b5u, 0x000001b4u, 0x00050041u, 0x00000020u, 0x000001b6u, 0x00000062u,
0x00000048u, 0x0004003du, 0x00000006u, 0x000001b7u, 0x000001b6u, 0x00050050u, 0x0000000du, 0x000001b8u,
0x000001b5u, 0x000001b7u, 0x00050081u, 0x0000000du, 0x000001b9u, 0x000001b3u, 0x000001b8u, 0x00050057u,
0x0000002fu, 0x000001bau, 0x000001b2u, 0x000001b9u, 0x0008004fu, 0x00000007u, 0x000001bcu, 0x000001bau,
0x000001bau, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000001bbu, 0x000001bcu, 0x00050039u,
0x00000006u, 0x000001bdu, 0x0000000bu, 0x000001bbu, 0x0003003eu, 0x000001b1u, 0x000001bdu, 0x0004003du,
0x00000006u, 0x000001bfu, 0x0000011du, 0x0004003du, 0x00000006u, 0x000001c0u, 0x0000011eu, 0x00050083u,
0x00000006u, 0x000001c1u, 0x000001bfu, 0x000001c0u, 0x0006000cu, 0x00000006u, 0x000001c2u, 0x00000001u,
0x00000004u, 0x000001c1u, 0x0004003du, 0x00000006u, 0x000001c3u, 0x0000017bu, 0x0007000cu, 0x00000006u,
0x000001c4u, 0x00000001u, 0x00000028u, 0x000001c3u, 0x00000063u, 0x00050088u, 0x00000006u, 0x000001c5u,
0x000001c2u, 0x000001c4u, 0x0008000cu, 0x00000006u, 0x000001c6u, 0x00000001u, 0x0000002bu, 0x000001c5u,
0x0000002cu, 0x00000063u, 0x0003003eu, 0x000001beu, 0x000001c6u, 0x0004003du, 0x00000006u, 0x000001c8u,
0x000001beu, 0x0004003du, 0x00000006u, 0x000001c9u, 0x0000017bu, 0x00050085u, 0x00000006u, 0x000001cbu,
0x000001c9u, 0x000001cau, 0x00050081u, 0x00000006u, 0x000001ccu, 0x00000063u, 0x000001cbu, 0x00050088u,
0x00000006u, 0x000001cdu, 0x000001c8u, 0x000001ccu, 0x0003003eu, 0x000001c7u, 0x000001cdu, 0x0004003du,
0x000000f1u, 0x000001cfu, 0x000000fau, 0x000300f7u, 0x000001d2u, 0x00000000u, 0x000400fau, 0x000001cfu,
0x000001d1u, 0x000001d7u, 0x000200f8u, 0x000001d1u, 0x0004003du, 0x00000006u, 0x000001d3u, 0x00000186u,
0x0004003du, 0x00000006u, 0x000001d4u, 0x00000195u, 0x00050083u, 0x00000006u, 0x000001d5u, 0x000001d3u,
0x000001d4u, 0x0006000cu, 0x00000006u, 0x000001d6u, 0x00000001u, 0x00000004u, 0x000001d5u, 0x0003003eu,
0x000001d0u, 0x000001d6u, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d7u, 0x0004003du, 0x00000006u,
0x000001d8u, 0x00000186u, 0x0004003du, 0x00000006u, 0x000001d9u, 0x000001a3u, 0x00050083u, 0x00000006u,
0x000001dau, 0x000001d8u, 0x000001d9u, 0x0006000cu, 0x00000006u, 0x000001dbu, 0x00000001u, 0x00000004u,
0x000001dau, 0x0003003eu, 0x000001d0u, 0x000001dbu, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d2u,
0x0004003du, 0x00000006u, 0x000001dcu, 0x000001d0u, 0x0003003eu, 0x000001ceu, 0x000001dcu, 0x0004003du,
0x000000f1u, 0x000001deu, 0x000000fau, 0x000300f7u, 0x000001e1u, 0x00000000u, 0x000400fau, 0x000001deu,
0x000001e0u, 0x000001e6u, 0x000200f8u, 0x000001e0u, 0x0004003du, 0x00000006u, 0x000001e2u, 0x000001a3u,
0x0004003du, 0x00000006u, 0x000001e3u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x000001e4u, 0x000001e2u,
0x000001e3u, 0x0006000cu, 0x00000006u, 0x000001e5u, 0x00000001u, 0x00000004u, 0x000001e4u, 0x0003003eu,
0x000001dfu, 0x000001e5u, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e6u, 0x0004003du, 0x00000006u,
0x000001e7u, 0x00000195u, 0x0004003du, 0x00000006u, 0x000001e8u, 0x000001b1u, 0x00050083u, 0x00000006u,
0x000001e9u, 0x000001e7u, 0x000001e8u, 0x0006000cu, 0x00000006u, 0x000001eau, 0x00000001u, 0x00000004u,
0x000001e9u, 0x0003003eu, 0x000001dfu, 0x000001eau, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e1u,
0x0004003du, 0x00000006u, 0x000001ebu, 0x000001dfu, 0x0003003eu, 0x000001ddu, 0x000001ebu, 0x0004003du,
0x00000006u, 0x000001edu, 0x000001ceu, 0x0004003du, 0x00000006u, 0x000001eeu, 0x000001ddu, 0x00050083u,
0x00000006u, 0x000001efu, 0x000001edu, 0x000001eeu, 0x0006000cu, 0x00000006u, 0x000001f0u, 0x00000001u,
0x00000004u, 0x000001efu, 0x0003003eu, 0x000001ecu, 0x000001f0u, 0x0004003du, 0x00000006u, 0x000001f2u,
0x000000ddu, 0x0004003du, 0x00000006u, 0x000001f3u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x000001f4u,
0x000001f3u, 0x00000182u, 0x0004003du, 0x00000006u, 0x000001f5u, 0x000001ecu, 0x0008000cu, 0x00000006u,
0x000001f6u, 0x00000001u, 0x00000031u, 0x000001f2u, 0x000001f4u, 0x000001f5u, 0x0003003eu, 0x000001f1u,
0x000001f6u, 0x0004003du, 0x00000006u, 0x000001f9u, 0x000001f1u, 0x00050085u, 0x00000006u, 0x000001fau,
0x000001f8u, 0x000001f9u, 0x0004003du, 0x00000006u, 0x000001fbu, 0x0000017bu, 0x00050088u, 0x00000006u,
0x000001fdu, 0x000001fbu, 0x000001fcu, 0x0008000cu, 0x00000006u, 0x000001feu, 0x00000001u, 0x0000002bu,
0x000001fdu, 0x0000002cu, 0x00000063u, 0x00050085u, 0x00000006u, 0x000001ffu, 0x000001fau, 0x000001feu,
0x0003003eu, 0x000001f7u, 0x000001ffu, 0x0004003du, 0x00000006u, 0x00000201u, 0x00000186u, 0x0004003du,
0x00000006u, 0x00000202u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x00000203u, 0x00000201u, 0x00000202u,
0x0006000cu, 0x00000006u, 0x00000204u, 0x00000001u, 0x00000004u, 0x00000203u, 0x0004003du, 0x00000006u,
0x00000205u, 0x00000195u, 0x0004003du, 0x00000006u, 0x00000206u, 0x000001a3u, 0x00050083u, 0x00000006u,
0x00000207u, 0x00000205u, 0x00000206u, 0x0006000cu, 0x00000006u, 0x00000208u, 0x00000001u, 0x00000004u,
0x00000207u, 0x0007000cu, 0x00000006u, 0x00000209u, 0x00000001u, 0x00000028u, 0x00000204u, 0x00000208u,
0x0003003eu, 0x00000200u, 0x00000209u, 0x0004003du, 0x00000006u, 0x0000020cu, 0x000000ddu, 0x0004003du,
0x00000006u, 0x0000020du, 0x000000ddu, 0x00050085u, 0x00000006u, 0x0000020fu, 0x0000020du, 0x0000020eu,
0x0004003du, 0x00000006u, 0x00000210u, 0x00000200u, 0x0008000cu, 0x00000006u, 0x00000211u, 0x00000001u,
0x00000031u, 0x0000020cu, 0x0000020fu, 0x00000210u, 0x00050085u, 0x00000006u, 0x00000212u, 0x0000020bu,
0x00000211u, 0x00050083u, 0x00000006u, 0x00000213u, 0x00000063u, 0x00000212u, 0x0003003eu, 0x0000020au,
0x00000213u, 0x0004003du, 0x00000006u, 0x00000215u, 0x000001f7u, 0x0004003du, 0x00000006u, 0x00000216u,
0x000001c7u, 0x00050085u, 0x00000006u, 0x00000217u, 0x00000215u, 0x00000216u, 0x0004003du, 0x00000006u,
0x00000218u, 0x0000017fu, 0x00050085u, 0x00000006u, 0x00000219u, 0x00000217u, 0x00000218u, 0x0004003du,
0x00000006u, 0x0000021au, 0x0000020au, 0x00050085u, 0x00000006u, 0x0000021bu, 0x00000219u, 0x0000021au,
0x0003003eu, 0x00000214u, 0x0000021bu, 0x0004003du, 0x00000006u, 0x0000021du, 0x000000e3u, 0x0004003du,
0x00000006u, 0x0000021eu, 0x000000e7u, 0x0007000cu, 0x00000006u, 0x0000021fu, 0x00000001u, 0x00000025u,
0x0000021du, 0x0000021eu, 0x0003003eu, 0x0000021cu, 0x0000021fu, 0x0004003du, 0x00000006u, 0x00000221u,
0x000000ddu, 0x0004003du, 0x00000006u, 0x00000222u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000223u,
0x00000222u, 0x00000182u, 0x0004003du, 0x00000006u, 0x00000224u, 0x0000021cu, 0x0008000cu, 0x00000006u,
0x00000225u, 0x00000001u, 0x00000031u, 0x00000221u, 0x00000223u, 0x00000224u, 0x0003003eu, 0x00000220u,
0x00000225u, 0x0004003du, 0x00000006u, 0x00000227u, 0x0000017bu, 0x0008000cu, 0x00000006u, 0x00000228u,
0x00000001u, 0x00000031u, 0x00000063u, 0x0000020eu, 0x00000227u, 0x0003003eu, 0x00000226u, 0x00000228u,
0x0004003du, 0x00000006u, 0x0000022bu, 0x00000220u, 0x00050085u, 0x00000006u, 0x0000022cu, 0x0000022au,
0x0000022bu, 0x0004003du, 0x00000006u, 0x0000022du, 0x0000017fu, 0x00050085u, 0x00000006u, 0x0000022eu,
0x0000022cu, 0x0000022du, 0x0004003du, 0x00000006u, 0x0000022fu, 0x0000020au, 0x00050085u, 0x00000006u,
0x00000230u, 0x0000022eu, 0x0000022fu, 0x0004003du, 0x00000006u, 0x00000231u, 0x00000226u, 0x00050085u,
0x00000006u, 0x00000232u, 0x00000230u, 0x00000231u, 0x0004003du, 0x00000006u, 0x00000233u, 0x000001f1u,
0x00050085u, 0x00000006u, 0x00000234u, 0x00000232u, 0x00000233u, 0x0003003eu, 0x00000229u, 0x00000234u,
0x0004003du, 0x00000006u, 0x00000236u, 0x00000214u, 0x0004003du, 0x00000006u, 0x00000237u, 0x00000229u,
0x0007000cu, 0x00000006u, 0x00000238u, 0x00000001u, 0x00000028u, 0x00000236u, 0x00000237u, 0x0008000cu,
0x00000006u, 0x0000023au, 0x00000001u, 0x0000002bu, 0x00000238u, 0x0000002cu, 0x00000239u, 0x0003003eu,
0x00000235u, 0x0000023au, 0x0004003du, 0x00000023u, 0x0000023cu, 0x00000025u, 0x0004003du, 0x0000000du,
0x0000023du, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000023eu, 0x0000010bu, 0x0004003du, 0x0000000du,
0x0000023fu, 0x00000062u, 0x00050085u, 0x0000000du, 0x00000240u, 0x0000023eu, 0x0000023fu, 0x00050081u,
0x0000000du, 0x00000241u, 0x0000023du, 0x00000240u, 0x00050057u, 0x0000002fu, 0x00000242u, 0x0000023cu,
0x00000241u, 0x0008004fu, 0x00000007u, 0x00000243u, 0x00000242u, 0x00000242u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x0000023bu, 0x00000243u, 0x0004003du, 0x0000002fu, 0x00000244u, 0x0000007cu,
0x0008004fu, 0x00000007u, 0x00000245u, 0x00000244u, 0x00000244u, 0x00000000u, 0x00000001u, 0x00000002u,
0x0004003du, 0x00000007u, 0x00000246u, 0x0000023bu, 0x0004003du, 0x00000006u, 0x00000247u, 0x00000235u,
0x00060050u, 0x00000007u, 0x00000248u, 0x00000247u, 0x00000247u, 0x00000247u, 0x0008000cu, 0x00000007u,
0x00000249u, 0x00000001u, 0x0000002eu, 0x00000245u, 0x00000246u, 0x00000248u, 0x00050041u, 0x00000020u,
0x0000024bu, 0x0000007cu, 0x0000024au, 0x0004003du, 0x00000006u, 0x0000024cu, 0x0000024bu, 0x00050051u,
0x00000006u, 0x0000024du, 0x00000249u, 0x00000000u, 0x00050051u, 0x00000006u, 0x0000024eu, 0x00000249u,
0x00000001u, 0x00050051u, 0x00000006u, 0x0000024fu, 0x00000249u, 0x00000002u, 0x00070050u, 0x0000002fu,
0x00000250u, 0x0000024du, 0x0000024eu, 0x0000024fu, 0x0000024cu, 0x0003003eu, 0x000000f6u, 0x00000250u,
0x000100fdu, 0x00010038u, 0x00050036u, 0x00000006u, 0x0000000bu, 0x00000000u, 0x00000009u, 0x00030037u,
0x00000008u, 0x0000000au, 0x000200f8u, 0x0000000cu, 0x0004003du, 0x00000007u, 0x00000018u, 0x0000000au,
0x00050094u, 0x00000006u, 0x0000001du, 0x00000018u, 0x0000001cu, 0x000200feu, 0x0000001du, 0x00010038u,
0x00050036u, 0x00000006u, 0x00000012u, 0x00000000u, 0x0000000fu, 0x00030037u, 0x0000000eu, 0x00000010u,
0x00030037u, 0x0000000eu, 0x00000011u, 0x000200f8u, 0x00000013u, 0x0004003bu, 0x00000020u, 0x00000021u,
0x00000007u, 0x0004003bu, 0x00000008u, 0x00000031u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000034u,
0x00000007u, 0x0004003bu, 0x00000008u, 0x0000003cu, 0x00000007u, 0x0004003du, 0x00000023u, 0x00000026u,
0x00000025u, 0x0004003du, 0x0000000du, 0x00000027u, 0x00000010u, 0x00050041u, 0x00000020u, 0x0000002au,
0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000002bu, 0x0000002au, 0x00050050u, 0x0000000du,
0x0000002du, 0x0000002bu, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000002eu, 0x00000027u, 0x0000002du,
0x00050057u, 0x0000002fu, 0x00000030u, 0x00000026u, 0x0000002eu, 0x0008004fu, 0x00000007u, 0x00000032u,
0x00000030u, 0x00000030u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x00000031u, 0x00000032u,
0x00050039u, 0x00000006u, 0x00000033u, 0x0000000bu, 0x00000031u, 0x0003003eu, 0x00000021u, 0x00000033u,
0x0004003du, 0x00000023u, 0x00000035u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000036u, 0x00000010u,
0x00050041u, 0x00000020u, 0x00000037u, 0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000038u,
0x00000037u, 0x00050050u, 0x0000000du, 0x00000039u, 0x00000038u, 0x0000002cu, 0x00050081u, 0x0000000du,
0x0000003au, 0x00000036u, 0x00000039u, 0x00050057u, 0x0000002fu, 0x0000003bu, 0x00000035u, 0x0000003au,
0x0008004fu, 0x00000007u, 0x0000003du, 0x0000003bu, 0x0000003bu, 0x00000000u, 0x00000001u, 0x00000002u,
0x0003003eu, 0x0000003cu, 0x0000003du, 0x00050039u, 0x00000006u, 0x0000003eu, 0x0000000bu, 0x0000003cu,
0x0003003eu, 0x00000034u, 0x0000003eu, 0x0004003du, 0x00000006u, 0x0000003fu, 0x00000021u, 0x0004003du,
0x00000006u, 0x00000040u, 0x00000034u, 0x00050083u, 0x00000006u, 0x00000041u, 0x0000003fu, 0x00000040u,
0x0006000cu, 0x00000006u, 0x00000042u, 0x00000001u, 0x00000004u, 0x00000041u, 0x000200feu, 0x00000042u,
0x00010038u, 0x00050036u, 0x00000006u, 0x00000016u, 0x00000000u, 0x0000000fu, 0x00030037u, 0x0000000eu,
0x00000014u, 0x00030037u, 0x0000000eu, 0x00000015u, 0x000200f8u, 0x00000017u, 0x0004003bu, 0x00000020u,
0x00000045u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000004eu, 0x00000007u, 0x0004003bu, 0x00000020u,
0x00000051u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000059u, 0x00000007u, 0x0004003du, 0x00000023u,
0x00000046u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000047u, 0x00000014u, 0x00050041u, 0x00000020u,
0x00000049u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000004au, 0x00000049u, 0x00050050u,
0x0000000du, 0x0000004bu, 0x0000002cu, 0x0000004au, 0x00050083u, 0x0000000du, 0x0000004cu, 0x00000047u,
0x0000004bu, 0x00050057u, 0x0000002fu, 0x0000004du, 0x00000046u, 0x0000004cu, 0x0008004fu, 0x00000007u,
0x0000004fu, 0x0000004du, 0x0000004du, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000004eu,
0x0000004fu, 0x00050039u, 0x00000006u, 0x00000050u, 0x0000000bu, 0x0000004eu, 0x0003003eu, 0x00000045u,
0x00000050u, 0x0004003du, 0x00000023u, 0x00000052u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000053u,
0x00000014u, 0x00050041u, 0x00000020u, 0x00000054u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u,
0x00000055u, 0x00000054u, 0x00050050u, 0x0000000du, 0x00000056u, 0x0000002cu, 0x00000055u, 0x00050081u,
0x0000000du, 0x00000057u, 0x00000053u, 0x00000056u, 0x00050057u, 0x0000002fu, 0x00000058u, 0x00000052u,
0x00000057u, 0x0008004fu, 0x00000007u, 0x0000005au, 0x00000058u, 0x00000058u, 0x00000000u, 0x00000001u,
0x00000002u, 0x0003003eu, 0x00000059u, 0x0000005au, 0x00050039u, 0x00000006u, 0x0000005bu, 0x0000000bu,
0x00000059u, 0x0003003eu, 0x00000051u, 0x0000005bu, 0x0004003du, 0x00000006u, 0x0000005cu, 0x00000045u,
0x0004003du, 0x00000006u, 0x0000005du, 0x00000051u, 0x00050083u, 0x00000006u, 0x0000005eu, 0x0000005cu,
0x0000005du, 0x0006000cu, 0x00000006u, 0x0000005fu, 0x00000001u, 0x00000004u, 0x0000005eu, 0x000200feu,
0x0000005fu, 0x00010038u,
};
+1 -1
View File
@@ -26,7 +26,7 @@ add_library(droiddeckwayland SHARED
generated/linux-dmabuf-v1-protocol.c generated/linux-dmabuf-v1-protocol.c
generated/wayland-android-protocol.c generated/wayland-android-protocol.c
generated/viewporter-protocol.c generated/viewporter-protocol.c
generated/droiddeck-desktop-v1-protocol.c generated/banner-desktop-v1-protocol.c
generated/presentation-time-protocol.c generated/presentation-time-protocol.c
generated/pointer-constraints-unstable-v1-protocol.c generated/pointer-constraints-unstable-v1-protocol.c
generated/relative-pointer-unstable-v1-protocol.c generated/relative-pointer-unstable-v1-protocol.c
@@ -38,7 +38,7 @@
extern const struct wl_interface wl_surface_interface; extern const struct wl_interface wl_surface_interface;
static const struct wl_interface *droiddeck_desktop_v1_types[] = { static const struct wl_interface *banner_desktop_v1_types[] = {
NULL, NULL,
&wl_surface_interface, &wl_surface_interface,
&wl_surface_interface, &wl_surface_interface,
@@ -47,16 +47,16 @@ static const struct wl_interface *droiddeck_desktop_v1_types[] = {
NULL, NULL,
}; };
static const struct wl_message droiddeck_desktop_v1_requests[] = { static const struct wl_message banner_desktop_v1_requests[] = {
{ "destroy", "", droiddeck_desktop_v1_types + 0 }, { "destroy", "", banner_desktop_v1_types + 0 },
{ "set_desktop", "o", droiddeck_desktop_v1_types + 1 }, { "set_desktop", "o", banner_desktop_v1_types + 1 },
{ "set_window", "ouii", droiddeck_desktop_v1_types + 2 }, { "set_window", "ouii", banner_desktop_v1_types + 2 },
{ "set_zorder", "a", droiddeck_desktop_v1_types + 0 }, { "set_zorder", "a", banner_desktop_v1_types + 0 },
}; };
WL_PRIVATE const struct wl_interface droiddeck_desktop_v1_interface = { WL_PRIVATE const struct wl_interface banner_desktop_v1_interface = {
"droiddeck_desktop_v1", 1, "banner_desktop_v1", 1,
4, droiddeck_desktop_v1_requests, 4, banner_desktop_v1_requests,
0, NULL, 0, NULL,
}; };
@@ -1,6 +1,6 @@
#ifndef DROIDDECK_DESKTOP_V1_SERVER_PROTOCOL_H #ifndef BANNER_DESKTOP_V1_SERVER_PROTOCOL_H
#define DROIDDECK_DESKTOP_V1_SERVER_PROTOCOL_H #define BANNER_DESKTOP_V1_SERVER_PROTOCOL_H
#include <stdint.h> #include <stdint.h>
#include <stddef.h> #include <stddef.h>
@@ -14,7 +14,7 @@ struct wl_client;
struct wl_resource; struct wl_resource;
/* /*
* @section page_copyright_droiddeck_desktop_v1 Copyright * @section page_copyright_banner_desktop_v1 Copyright
* *
* Copyright 2026 The412Banner * Copyright 2026 The412Banner
* *
@@ -42,15 +42,15 @@ struct wl_resource;
struct droiddeck_desktop_v1; struct banner_desktop_v1;
struct wl_surface; struct wl_surface;
#ifndef DROIDDECK_DESKTOP_V1_INTERFACE #ifndef BANNER_DESKTOP_V1_INTERFACE
#define DROIDDECK_DESKTOP_V1_INTERFACE #define BANNER_DESKTOP_V1_INTERFACE
extern const struct wl_interface droiddeck_desktop_v1_interface; extern const struct wl_interface banner_desktop_v1_interface;
#endif #endif
struct droiddeck_desktop_v1_interface { struct banner_desktop_v1_interface {
void (*destroy)(struct wl_client *client, void (*destroy)(struct wl_client *client,
struct wl_resource *resource); struct wl_resource *resource);
void (*set_desktop)(struct wl_client *client, void (*set_desktop)(struct wl_client *client,
@@ -68,10 +68,10 @@ struct droiddeck_desktop_v1_interface {
}; };
#define DROIDDECK_DESKTOP_V1_DESTROY_SINCE_VERSION 1 #define BANNER_DESKTOP_V1_DESTROY_SINCE_VERSION 1
#define DROIDDECK_DESKTOP_V1_SET_DESKTOP_SINCE_VERSION 1 #define BANNER_DESKTOP_V1_SET_DESKTOP_SINCE_VERSION 1
#define DROIDDECK_DESKTOP_V1_SET_WINDOW_SINCE_VERSION 1 #define BANNER_DESKTOP_V1_SET_WINDOW_SINCE_VERSION 1
#define DROIDDECK_DESKTOP_V1_SET_ZORDER_SINCE_VERSION 1 #define BANNER_DESKTOP_V1_SET_ZORDER_SINCE_VERSION 1
#ifdef __cplusplus #ifdef __cplusplus
} }
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<protocol name="droiddeck_desktop_v1"> <protocol name="banner_desktop_v1">
<copyright> <copyright>
Copyright 2026 The412Banner Copyright 2026 The412Banner
@@ -23,7 +23,7 @@
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
</copyright> </copyright>
<interface name="droiddeck_desktop_v1" version="1"> <interface name="banner_desktop_v1" version="1">
<description summary="Windows virtual desktop layout"> <description summary="Windows virtual desktop layout">
Each Wine process is a separate Wayland client, so a Windows virtual Each Wine process is a separate Wayland client, so a Windows virtual
desktop can't be built from subsurfaces. Instead the process that owns desktop can't be built from subsurfaces. Instead the process that owns
@@ -14,7 +14,6 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <sys/system_properties.h>
#include <time.h> #include <time.h>
#include <unistd.h> #include <unistd.h>
@@ -26,7 +25,6 @@ struct droiddeck_dma_buf_sync_file { uint32_t flags; int32_t fd; };
#define DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW('b', 3, struct droiddeck_dma_buf_sync_file) #define DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW('b', 3, struct droiddeck_dma_buf_sync_file)
extern volatile int g_zero_copy; extern volatile int g_zero_copy;
extern volatile int g_zero_copy_ahb;
struct ahb_buf { struct ahb_buf {
uint64_t id; uint64_t id;
@@ -342,7 +340,7 @@ static void bind_ahb(struct wl_client *c, void *data, uint32_t ver, uint32_t id)
if (!r) { wl_client_post_no_memory(c); return; } if (!r) { wl_client_post_no_memory(c); return; }
wl_resource_set_implementation(r, &ahb_impl, NULL, on_client_resource_destroyed); wl_resource_set_implementation(r, &ahb_impl, NULL, on_client_resource_destroyed);
wl_list_insert(&g_clients, wl_resource_get_link(r)); wl_list_insert(&g_clients, wl_resource_get_link(r));
if (ver >= BANNER_AHB_V1_MODE_SINCE_VERSION) banner_ahb_v1_send_mode(r, (g_zero_copy || g_zero_copy_ahb) ? 1u : 0u); if (ver >= BANNER_AHB_V1_MODE_SINCE_VERSION) banner_ahb_v1_send_mode(r, g_zero_copy ? 1u : 0u);
if (last_named != c) { if (last_named != c) {
last_named = c; last_named = c;
droiddeck_log("layer", "zero-copy: %s bound banner_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver, droiddeck_log("layer", "zero-copy: %s bound banner_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver,
@@ -358,14 +356,13 @@ void ahb_swapchain_set_mode(int on, int live) {
on ? "on" : "off"); on ? "on" : "off");
return; return;
} }
const int want = on || g_zero_copy_ahb; if (g_mode_sent == on) return;
if (g_mode_sent == want) return; g_mode_sent = on;
g_mode_sent = want;
int told = 0; int told = 0;
struct wl_resource *r; struct wl_resource *r;
wl_resource_for_each(r, &g_clients) { wl_resource_for_each(r, &g_clients) {
if (wl_resource_get_version(r) >= BANNER_AHB_V1_MODE_SINCE_VERSION) { if (wl_resource_get_version(r) >= BANNER_AHB_V1_MODE_SINCE_VERSION) {
banner_ahb_v1_send_mode(r, (uint32_t)want); banner_ahb_v1_send_mode(r, (uint32_t)on);
told++; told++;
} }
} }
@@ -404,13 +401,5 @@ void ahb_swapchain_init(struct wl_display *display) {
} }
g_advertised = 1; g_advertised = 1;
droiddeck_log("layer", "zero-copy: banner_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)"); droiddeck_log("layer", "zero-copy: banner_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)");
// Android buffers only: programs that hand over their own gralloc buffers (bionic games, also through gamescope)
// are asked for them and shown on the display layer; every other frame keeps the copy path.
char prop[PROP_VALUE_MAX] = {0};
__system_property_get("persist.droiddeck.zero_copy_ahb", prop);
if (prop[0] == '1') {
g_zero_copy_ahb = 1;
droiddeck_log("layer", "zero-copy: Android buffers only (persist.droiddeck.zero_copy_ahb=1): programs that send their own gralloc buffers go on the display layer, other frames keep the copy");
}
ahb_swapchain_set_mode(g_zero_copy, 0); ahb_swapchain_set_mode(g_zero_copy, 0);
} }
+24 -95
View File
@@ -24,7 +24,7 @@
#include "sc_layer.h" #include "sc_layer.h"
#include "ahb_swapchain.h" #include "ahb_swapchain.h"
#include "viewporter-server-protocol.h" #include "viewporter-server-protocol.h"
#include "droiddeck-desktop-v1-server-protocol.h" #include "banner-desktop-v1-server-protocol.h"
#include "presentation-time-server-protocol.h" #include "presentation-time-server-protocol.h"
#include "pointer-constraints-unstable-v1-server-protocol.h" #include "pointer-constraints-unstable-v1-server-protocol.h"
#include "relative-pointer-unstable-v1-server-protocol.h" #include "relative-pointer-unstable-v1-server-protocol.h"
@@ -79,7 +79,7 @@ static void open_session_log(void) {
localtime_r(&now, &tm); localtime_r(&now, &tm);
strftime(stamp, sizeof(stamp), "%Y-%m-%d_%H-%M-%S", &tm); strftime(stamp, sizeof(stamp), "%Y-%m-%d_%H-%M-%S", &tm);
const char *given = getenv("DD_WAYLAND_LOG"); const char *given = getenv("BL_WAYLAND_LOG");
if (given && *given) { if (given && *given) {
snprintf(path, sizeof(path), "%s", given); snprintf(path, sizeof(path), "%s", given);
} else { } else {
@@ -256,7 +256,6 @@ struct surface {
struct wl_list child_link; struct wl_list child_link;
int sub_x, sub_y, sub_pending_x, sub_pending_y, sub_pending; int sub_x, sub_y, sub_pending_x, sub_pending_y, sub_pending;
int below_parent; int below_parent;
int sub_desync;
int fullscreen; int fullscreen;
int toplevel_committed; int toplevel_committed;
@@ -317,7 +316,6 @@ static struct { unsigned lit, dark, failed; } g_bfi_stats;
volatile int g_hide_shell; volatile int g_hide_shell;
volatile int g_zero_copy; volatile int g_zero_copy;
volatile int g_zero_copy_ahb;
static int g_zero_copy_paused; static int g_zero_copy_paused;
static int g_zero_copy_fx_skip_said; static int g_zero_copy_fx_skip_said;
@@ -334,7 +332,6 @@ struct pending_release {
struct wl_resource *buffer; struct wl_resource *buffer;
struct wl_listener destroy; struct wl_listener destroy;
struct surface *surface; struct surface *surface;
struct surface *held_by;
int64_t at_ns; int64_t at_ns;
int64_t since_ns; int64_t since_ns;
struct wl_list link; struct wl_list link;
@@ -437,54 +434,10 @@ static void pending_release_free(struct pending_release *pr) {
free(pr); free(pr);
} }
static void release_due_buffers(void);
static void arm_release_timer(void);
static void pending_releases_forget_surface(struct surface *s) { static void pending_releases_forget_surface(struct surface *s) {
struct pending_release *pr; struct pending_release *pr;
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link) {
if (pr->surface == s) pr->surface = NULL;
if (pr->held_by == s) { pr->held_by = NULL; unheld = 1; }
}
if (unheld) { release_due_buffers(); arm_release_timer(); }
}
static void pending_releases_cancel(struct wl_resource *buffer) {
struct pending_release *pr, *tmp;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link)
if (pr->buffer == buffer) pending_release_free(pr);
}
static void pending_releases_apply(struct surface *holder) {
struct pending_release *pr;
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link) wl_list_for_each(pr, &g_pending_releases, link)
if (pr->held_by == holder) { pr->held_by = NULL; unheld = 1; } if (pr->surface == s) pr->surface = NULL;
if (unheld) { release_due_buffers(); arm_release_timer(); }
}
static struct surface *sync_holder(struct surface *s) {
struct surface *holder = NULL;
for (int depth = 0; s && s->role == ROLE_SUBSURFACE && s->parent && depth < 8; depth++) {
if (!s->sub_desync) holder = s->parent;
s = s->parent;
}
return holder;
}
static void pending_releases_rehold(struct surface *changed) {
struct pending_release *pr;
int unheld = 0;
wl_list_for_each(pr, &g_pending_releases, link) {
if (!pr->held_by || !pr->surface) continue;
struct surface *s = pr->surface;
for (int depth = 0; s && s != changed && depth < 8; depth++) s = s->parent;
if (s != changed) continue;
pr->held_by = sync_holder(pr->surface);
if (!pr->held_by) unheld = 1;
}
if (unheld) { release_due_buffers(); arm_release_timer(); }
} }
static void on_pending_release_buffer_destroyed(struct wl_listener *l, void *data) { static void on_pending_release_buffer_destroyed(struct wl_listener *l, void *data) {
@@ -497,18 +450,20 @@ static void arm_release_timer(void) {
int64_t earliest = 0; int64_t earliest = 0;
if (g_release_timer_fd < 0) return; if (g_release_timer_fd < 0) return;
wl_list_for_each(pr, &g_pending_releases, link) wl_list_for_each(pr, &g_pending_releases, link)
if (!pr->held_by && !buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest)) if (!buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
earliest = pr->at_ns; earliest = pr->at_ns;
struct itimerspec its = {0}; struct itimerspec its = {0};
if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; } if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; }
timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL); timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL);
} }
static void release_due_buffers(void) { static int on_release_timer(int fd, uint32_t mask, void *data) {
struct pending_release *pr, *tmp; struct pending_release *pr, *tmp;
uint64_t expirations;
int64_t now = now_ns() + 300000; int64_t now = now_ns() + 300000;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) { wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) {
if (!pr->held_by && pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) { if (pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
/* Attached again since (to its surface or another): that surface releases it later. */ /* Attached again since (to its surface or another): that surface releases it later. */
if (buffer_shown_elsewhere(pr->buffer, NULL)) { if (buffer_shown_elsewhere(pr->buffer, NULL)) {
pending_release_free(pr); pending_release_free(pr);
@@ -519,39 +474,28 @@ static void release_due_buffers(void) {
pending_release_free(pr); pending_release_free(pr);
} }
} }
}
static int on_release_timer(int fd, uint32_t mask, void *data) {
uint64_t expirations;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
release_due_buffers();
wl_display_flush_clients(g_display); wl_display_flush_clients(g_display);
arm_release_timer(); arm_release_timer();
return 0; return 0;
} }
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns, struct surface *holder) { static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
/* No allocation or immediate-release fallback is allowed for a quarantined /* No allocation or immediate-release fallback is allowed for a quarantined
* DMA-BUF. Existing queued releases stay held; their timer is disarmed. */ * DMA-BUF. Existing queued releases stay held; their timer is disarmed. */
if (buffer_release_blocked(buffer)) return; if (buffer_release_blocked(buffer)) return;
const int limit = g_fps_limit; const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns; const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
const int paced = !g_release_unpaced && interval > 0 && g_release_timer_fd >= 0; if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
if (!paced && !holder) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns(); int64_t now = now_ns();
int64_t at = now; int64_t at = s->next_release_ns + interval;
if (paced) { int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1); if (at < now) at = now;
at = s->next_release_ns + interval; if (at > latest) at = latest;
if (at < now) at = now; s->next_release_ns = at;
if (at > latest) at = latest;
s->next_release_ns = at;
}
struct pending_release *pr = calloc(1, sizeof(*pr)); struct pending_release *pr = calloc(1, sizeof(*pr));
if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; } if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
pr->buffer = buffer; pr->buffer = buffer;
pr->surface = s; pr->surface = s;
pr->held_by = holder;
pr->at_ns = at; pr->at_ns = at;
pr->since_ns = since_ns; pr->since_ns = since_ns;
pr->destroy.notify = on_pending_release_buffer_destroyed; pr->destroy.notify = on_pending_release_buffer_destroyed;
@@ -777,7 +721,7 @@ static void drop_dmabuf(struct surface *s, int paced) {
wl_list_remove(&s->dmabuf_destroy.link); wl_list_remove(&s->dmabuf_destroy.link);
if (buffer_shown_elsewhere(s->dmabuf, s)) { if (buffer_shown_elsewhere(s->dmabuf, s)) {
} else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) { } else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
if (paced) release_buffer(s, s->dmabuf, now_ns(), sync_holder(s)); if (paced) release_buffer(s, s->dmabuf, now_ns());
else send_buffer_release(s->dmabuf); else send_buffer_release(s->dmabuf);
} }
s->dmabuf = NULL; s->dmabuf = NULL;
@@ -943,7 +887,6 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
s->last_dmabuf = buffer; s->last_dmabuf = buffer;
pace_note_buffer(buffer); pace_note_buffer(buffer);
drop_dmabuf(s, 1); drop_dmabuf(s, 1);
pending_releases_cancel(buffer);
s->dmabuf = buffer; s->dmabuf = buffer;
s->dmabuf_buf = b; s->dmabuf_buf = b;
b->refs++; b->refs++;
@@ -1034,7 +977,7 @@ void droiddeck_dmabuf_ref(struct dmabuf_buffer *b) { b->refs++; }
void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); } void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); }
void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) { void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) {
if (buffer_release_blocked(buffer)) return; if (buffer_release_blocked(buffer)) return;
if (paced && s) release_buffer(s, buffer, since_ns, NULL); if (paced && s) release_buffer(s, buffer, since_ns);
else { send_buffer_release(buffer); perf_note_release(since_ns); } else { send_buffer_release(buffer); perf_note_release(since_ns); }
} }
void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); } void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); }
@@ -1322,7 +1265,6 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
s->pending_attach = 0; s->pending_attach = 0;
surface_drop_idle(s); surface_drop_idle(s);
buf_trace_attach(buffer);
if (s->role == ROLE_CURSOR) { if (s->role == ROLE_CURSOR) {
if (!buffer) { if (!buffer) {
cursor_publish_hidden(); cursor_publish_hidden();
@@ -1333,6 +1275,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
} else if (s->role == ROLE_NONE) { } else if (s->role == ROLE_NONE) {
if (buffer) surface_hold_idle(s, buffer); if (buffer) surface_hold_idle(s, buffer);
} else if (db) { } else if (db) {
buf_trace_attach(buffer);
take_dmabuf(s, db, buffer); take_dmabuf(s, db, buffer);
} else if (shm) { } else if (shm) {
drop_dmabuf(s, 1); drop_dmabuf(s, 1);
@@ -1346,7 +1289,6 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
if (buffer) send_buffer_release(buffer); if (buffer) send_buffer_release(buffer);
} }
} }
pending_releases_apply(s);
wl_list_for_each(child, &s->children, child_link) { wl_list_for_each(child, &s->children, child_link) {
if (child->sub_pending) { if (child->sub_pending) {
@@ -1544,14 +1486,8 @@ static void subsurface_place_below(struct wl_client *c, struct wl_resource *r,
struct wl_resource *sibling) { struct wl_resource *sibling) {
restack_child(wl_resource_get_user_data(r), wl_resource_get_user_data(sibling), 0); restack_child(wl_resource_get_user_data(r), wl_resource_get_user_data(sibling), 0);
} }
static void subsurface_set_sync(struct wl_client *c, struct wl_resource *r) { static void subsurface_set_sync(struct wl_client *c, struct wl_resource *r) {}
struct surface *s = wl_resource_get_user_data(r); static void subsurface_set_desync(struct wl_client *c, struct wl_resource *r) {}
if (s) s->sub_desync = 0;
}
static void subsurface_set_desync(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
if (s) { s->sub_desync = 1; pending_releases_rehold(s); }
}
static const struct wl_subsurface_interface subsurface_impl = { static const struct wl_subsurface_interface subsurface_impl = {
.destroy = subsurface_destroy, .destroy = subsurface_destroy,
.set_position = subsurface_set_position, .set_position = subsurface_set_position,
@@ -1585,7 +1521,6 @@ static void subcompositor_get_subsurface(struct wl_client *c, struct wl_resource
s->subsurface = sub; s->subsurface = sub;
s->parent = p; s->parent = p;
s->below_parent = 0; s->below_parent = 0;
s->sub_desync = 0;
s->sub_x = s->sub_y = 0; s->sub_x = s->sub_y = 0;
wl_list_insert(p->children.prev, &s->child_link); wl_list_insert(p->children.prev, &s->child_link);
} }
@@ -1861,14 +1796,14 @@ static void desktop_set_zorder(struct wl_client *c, struct wl_resource *r, struc
apply_zorder(); apply_zorder();
schedule_render(); schedule_render();
} }
static const struct droiddeck_desktop_v1_interface desktop_impl = { static const struct banner_desktop_v1_interface desktop_impl = {
.destroy = desktop_destroy_req, .destroy = desktop_destroy_req,
.set_desktop = desktop_set_desktop, .set_desktop = desktop_set_desktop,
.set_window = desktop_set_window, .set_window = desktop_set_window,
.set_zorder = desktop_set_zorder, .set_zorder = desktop_set_zorder,
}; };
static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
struct wl_resource *r = wl_resource_create(c, &droiddeck_desktop_v1_interface, ver, id); struct wl_resource *r = wl_resource_create(c, &banner_desktop_v1_interface, ver, id);
wl_resource_set_implementation(r, &desktop_impl, NULL, NULL); wl_resource_set_implementation(r, &desktop_impl, NULL, NULL);
} }
@@ -2405,13 +2340,7 @@ static void render_scene(void) {
rendered = vkp_render(w, h, dl.d, dl.n) == 0; rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) { } else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen; const int pass_on = fx_on || framegen;
int li = ((g_zero_copy || g_zero_copy_ahb) && !framegen && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; int li = (g_zero_copy && !framegen && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
if (li >= 0 && !g_zero_copy) {
/* Android buffers only: the fullscreen frame goes on the display layer only when it is a gralloc buffer
* its program handed over and no screen effect needs the pass; everything else keeps the copy. */
const struct surface *cs = surface_for_image(dl.d[li].img);
if (fx_on || !cs || !cs->dmabuf_buf || !ahb_swapchain_has_ahb(cs->dmabuf_buf)) li = -1;
}
int over = li >= 0 ? dl.n - 1 - li : 0; int over = li >= 0 ? dl.n - 1 - li : 0;
const int fx_blocks = (li >= 0 && fx_on && over > 0); const int fx_blocks = (li >= 0 && fx_on && over > 0);
if (fx_blocks) { li = -1; over = 0; } if (fx_blocks) { li = -1; over = 0; }
@@ -4154,7 +4083,7 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf); wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
droiddeck_android_wlegl_init(display); droiddeck_android_wlegl_init(display);
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat); wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
wl_global_create(display, &droiddeck_desktop_v1_interface, 1, NULL, bind_desktop); wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation); wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation);
wl_global_create(display, &zwp_pointer_constraints_v1_interface, 1, NULL, bind_pointer_constraints); wl_global_create(display, &zwp_pointer_constraints_v1_interface, 1, NULL, bind_pointer_constraints);
wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager); wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager);
@@ -17,7 +17,6 @@
#include "cas_frag.h" #include "cas_frag.h"
#include "color_frag.h" #include "color_frag.h"
#include "fxaa_frag.h" #include "fxaa_frag.h"
#include "smaa_frag.h"
#include "toon_frag.h" #include "toon_frag.h"
#include "hdr_frag.h" #include "hdr_frag.h"
#include "ntsc_frag.h" #include "ntsc_frag.h"
@@ -42,7 +41,7 @@ struct fx_settings {
int color_on; int color_on;
float brightness, contrast, gamma, saturation; float brightness, contrast, gamma, saturation;
float b_raw, c_raw, s_raw; float b_raw, c_raw, s_raw;
int aa_mode, toon, crt, ntsc; int fxaa, toon, crt, ntsc;
char look[48]; char look[48];
}; };
@@ -79,7 +78,7 @@ void vkp_effects_set_deband(int enabled, int pct) {
} }
static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; } static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }
void vkp_effects_set_screen(float brightness, float contrast, float gamma, float saturation, void vkp_effects_set_screen(float brightness, float contrast, float gamma, float saturation,
int aa_mode, int toon, int crt, int ntsc) { int fxaa, int toon, int crt, int ntsc) {
int on = !(brightness == 0.0f && contrast == 0.0f && gamma == 1.0f && saturation == 100.0f); int on = !(brightness == 0.0f && contrast == 0.0f && gamma == 1.0f && saturation == 100.0f);
set_begin(); set_begin();
g_set.color_on = on; g_set.color_on = on;
@@ -88,8 +87,7 @@ void vkp_effects_set_screen(float brightness, float contrast, float gamma, float
g_set.contrast = clampf(contrast / 100.0f, 0.0f, 2.0f); g_set.contrast = clampf(contrast / 100.0f, 0.0f, 2.0f);
g_set.saturation = clampf(saturation / 100.0f, 0.0f, 2.0f); g_set.saturation = clampf(saturation / 100.0f, 0.0f, 2.0f);
g_set.gamma = clampf(gamma, 0.1f, 5.0f); g_set.gamma = clampf(gamma, 0.1f, 5.0f);
g_set.aa_mode = (aa_mode >= 0 && aa_mode <= 2) ? aa_mode : 0; g_set.fxaa = fxaa ? 1 : 0; g_set.toon = toon ? 1 : 0; g_set.crt = crt ? 1 : 0; g_set.ntsc = ntsc ? 1 : 0;
g_set.toon = toon ? 1 : 0; g_set.crt = crt ? 1 : 0; g_set.ntsc = ntsc ? 1 : 0;
set_end(); set_end();
} }
void vkp_effects_set_look(const char *name) { void vkp_effects_set_look(const char *name) {
@@ -105,7 +103,7 @@ static const char *scaling_name(int m) {
static int spatial_mode(int m) { return m >= 3 && m <= 8; } static int spatial_mode(int m) { return m >= 3 && m <= 8; }
static int cas_active(const struct fx_settings *s) { return s->cas_on && s->cas_pct > 0; } static int cas_active(const struct fx_settings *s) { return s->cas_on && s->cas_pct > 0; }
static int effect_count(const struct fx_settings *s) { static int effect_count(const struct fx_settings *s) {
return (s->aa_mode != 0) + s->toon + s->color_on + cas_active(s) + s->hdr_on + s->ntsc + s->crt + s->deband_on; return s->fxaa + s->toon + s->color_on + cas_active(s) + s->hdr_on + s->ntsc + s->crt + s->deband_on;
} }
static void log_settings(const struct fx_settings *s) { static void log_settings(const struct fx_settings *s) {
@@ -123,8 +121,7 @@ static void log_settings(const struct fx_settings *s) {
if (s->color_on) if (s->color_on)
n += snprintf(line + n, sizeof(line) - n, ", colour b=%+.0f c=%+.0f g=%.2f s=%.0f%%", n += snprintf(line + n, sizeof(line) - n, ", colour b=%+.0f c=%+.0f g=%.2f s=%.0f%%",
s->b_raw, s->c_raw, s->gamma, s->s_raw); s->b_raw, s->c_raw, s->gamma, s->s_raw);
if (s->aa_mode == 1) n += snprintf(line + n, sizeof(line) - n, ", FXAA on"); if (s->fxaa) n += snprintf(line + n, sizeof(line) - n, ", FXAA on");
else if (s->aa_mode == 2) n += snprintf(line + n, sizeof(line) - n, ", SMAA on");
if (s->toon) n += snprintf(line + n, sizeof(line) - n, ", Toon on"); if (s->toon) n += snprintf(line + n, sizeof(line) - n, ", Toon on");
if (s->hdr_on) n += snprintf(line + n, sizeof(line) - n, ", HDR on"); if (s->hdr_on) n += snprintf(line + n, sizeof(line) - n, ", HDR on");
if (s->ntsc) n += snprintf(line + n, sizeof(line) - n, ", NTSC on"); if (s->ntsc) n += snprintf(line + n, sizeof(line) - n, ", NTSC on");
@@ -155,10 +152,6 @@ int vkp_effects_upscaling(void) {
return spatial_mode(g_cur.scaling) && g_cur.scaling != 6; return spatial_mode(g_cur.scaling) && g_cur.scaling != 6;
} }
int vkp_effects_sharpening(void) {
return vkp_effects_upscaling() || cas_active(&g_cur);
}
int vkp_effects_postprocessing(void) { int vkp_effects_postprocessing(void) {
vkp_effects_sync(); vkp_effects_sync();
return effect_count(&g_cur) > 0; return effect_count(&g_cur) > 0;
@@ -209,7 +202,7 @@ static VkDescriptorSetLayout g_dsl;
static VkPipelineLayout g_pl; static VkPipelineLayout g_pl;
static VkDescriptorPool g_dpool; static VkDescriptorPool g_dpool;
static VkSampler g_sampler; static VkSampler g_sampler;
enum { P_SGSR, P_SGSR_HQ, P_NIS, P_EASU, P_RCAS, P_CAS, P_COLOR, P_FXAA, P_SMAA, P_TOON, P_HDR, P_NTSC, P_CRT, P_DEBAND, P_COUNT }; enum { P_SGSR, P_SGSR_HQ, P_NIS, P_EASU, P_RCAS, P_CAS, P_COLOR, P_FXAA, P_TOON, P_HDR, P_NTSC, P_CRT, P_DEBAND, P_COUNT };
static VkPipeline g_pipe[P_COUNT]; static VkPipeline g_pipe[P_COUNT];
static struct fx_target g_t[2], g_mid; static struct fx_target g_t[2], g_mid;
@@ -445,7 +438,6 @@ static int objects_ensure(void) {
MK(P_CAS, cas_code, "cas"); MK(P_CAS, cas_code, "cas");
MK(P_COLOR, color_code, "color"); MK(P_COLOR, color_code, "color");
MK(P_FXAA, fxaa_code, "fxaa"); MK(P_FXAA, fxaa_code, "fxaa");
MK(P_SMAA, smaa_code, "smaa");
MK(P_TOON, toon_code, "toon"); MK(P_TOON, toon_code, "toon");
MK(P_HDR, hdr_code, "hdr"); MK(P_HDR, hdr_code, "hdr");
MK(P_NTSC, ntsc_code, "ntsc"); MK(P_NTSC, ntsc_code, "ntsc");
@@ -454,7 +446,7 @@ static int objects_ensure(void) {
#undef MK #undef MK
g_vk.DestroyShaderModule(g_dev, vert, NULL); g_vk.DestroyShaderModule(g_dev, vert, NULL);
g_ready = 1; g_ready = 1;
droiddeck_log("effects", "chain ready: 14 pipelines (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, SMAA, Toon, HDR, NTSC, CRT, deband) on %s", vkp_gpu_name()); droiddeck_log("effects", "chain ready: 13 passes (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, Toon, HDR, NTSC, CRT, deband) on %s", vkp_gpu_name());
return 0; return 0;
fail: fail:
objects_destroy(); objects_destroy();
@@ -575,10 +567,9 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
cur = NULL; cur_ds = g_scene.ds; cur = NULL; cur_ds = g_scene.ds;
} }
enum { FX_FXAA, FX_SMAA, FX_TOON, FX_COLOR, FX_CAS, FX_HDR, FX_NTSC, FX_CRT, FX_DEBAND }; enum { FX_FXAA, FX_TOON, FX_COLOR, FX_CAS, FX_HDR, FX_NTSC, FX_CRT, FX_DEBAND };
int order[8], n = 0; int order[8], n = 0;
if (s->aa_mode == 1) order[n++] = FX_FXAA; if (s->fxaa) order[n++] = FX_FXAA;
else if (s->aa_mode == 2) order[n++] = FX_SMAA;
if (s->toon) order[n++] = FX_TOON; if (s->toon) order[n++] = FX_TOON;
if (s->color_on) order[n++] = FX_COLOR; if (s->color_on) order[n++] = FX_COLOR;
if (cas_active(s)) order[n++] = FX_CAS; if (cas_active(s)) order[n++] = FX_CAS;
@@ -593,7 +584,6 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
pr.res[0] = (float)cw; pr.res[1] = (float)ch; pr.res[0] = (float)cw; pr.res[1] = (float)ch;
switch (order[i]) { switch (order[i]) {
case FX_FXAA: pass(cmd, g_pipe[P_FXAA], dst, cur_ds, &pr, sizeof(pr)); break; case FX_FXAA: pass(cmd, g_pipe[P_FXAA], dst, cur_ds, &pr, sizeof(pr)); break;
case FX_SMAA: pass(cmd, g_pipe[P_SMAA], dst, cur_ds, &pr, sizeof(pr)); break;
case FX_TOON: pass(cmd, g_pipe[P_TOON], dst, cur_ds, &pr, sizeof(pr)); break; case FX_TOON: pass(cmd, g_pipe[P_TOON], dst, cur_ds, &pr, sizeof(pr)); break;
case FX_COLOR: { case FX_COLOR: {
struct pc_color pc = {0}; struct pc_color pc = {0};
@@ -11,7 +11,6 @@ int vkp_effects_sync(void);
int vkp_effects_active(void); int vkp_effects_active(void);
int vkp_effects_upscaling(void); int vkp_effects_upscaling(void);
int vkp_effects_sharpening(void);
int vkp_effects_postprocessing(void); int vkp_effects_postprocessing(void);
VkFilter vkp_effects_blit_filter(void); VkFilter vkp_effects_blit_filter(void);
@@ -31,7 +30,7 @@ void vkp_effects_set_cas(int enabled, int pct);
void vkp_effects_set_hdr(int enabled); void vkp_effects_set_hdr(int enabled);
void vkp_effects_set_deband(int enabled, int pct); void vkp_effects_set_deband(int enabled, int pct);
void vkp_effects_set_screen(float brightness, float contrast, float gamma, float saturation, void vkp_effects_set_screen(float brightness, float contrast, float gamma, float saturation,
int aa_mode, int toon, int crt, int ntsc); int fxaa, int toon, int crt, int ntsc);
void vkp_effects_set_look(const char *name); void vkp_effects_set_look(const char *name);
#endif #endif
@@ -13,7 +13,6 @@
#include "quest_device.h" #include "quest_device.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h>
#include <string.h> #include <string.h>
#include <sys/system_properties.h> #include <sys/system_properties.h>
#include <unistd.h> #include <unistd.h>
@@ -417,13 +416,7 @@ static void update_map(int scene_w, int scene_h) {
if (mode == VKP_MODE_FILL) aspect = sx > sy ? sx : sy; if (mode == VKP_MODE_FILL) aspect = sx > sy ? sx : sy;
else if (mode == VKP_MODE_INTEGER) { else if (mode == VKP_MODE_INTEGER) {
float m = sx < sy ? sx : sy; float m = sx < sy ? sx : sy;
float nearest = roundf(m); aspect = m >= 1.0f ? (float)(int)m : m;
if (nearest >= 1.0f && nearest > m &&
nearest - m < 0.15f) {
aspect = nearest;
} else {
aspect = m >= 1.0f ? (float)(int)m : m;
}
} else aspect = sx < sy ? sx : sy; } else aspect = sx < sy ? sx : sy;
g_map.kx = g_map.ky = aspect; g_map.kx = g_map.ky = aspect;
g_map.off_x = (float)(g_map.rx + (int)((g_map.rw - scene_w * aspect) * 0.5f)); g_map.off_x = (float)(g_map.rx + (int)((g_map.rw - scene_w * aspect) * 0.5f));
@@ -2179,7 +2172,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
if (fx) { if (fx) {
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
if (fg && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } if (fg) { mapped_w = scene_w; mapped_h = scene_h; }
vkp_effects_set_formats(scene_fmt, scene_fmt); vkp_effects_set_formats(scene_fmt, scene_fmt);
result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh); result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh);
effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h, effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h,
@@ -497,8 +497,8 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDeband(JNIEnv *en
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetScreenEffects(JNIEnv *env, jclass clazz, jfloat brightness, Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetScreenEffects(JNIEnv *env, jclass clazz, jfloat brightness,
jfloat contrast, jfloat gamma, jfloat saturation, jint aa_mode, jboolean toon, jboolean crt, jboolean ntsc) { jfloat contrast, jfloat gamma, jfloat saturation, jboolean fxaa, jboolean toon, jboolean crt, jboolean ntsc) {
vkp_effects_set_screen(brightness, contrast, gamma, saturation, aa_mode, toon ? 1 : 0, crt ? 1 : 0, ntsc ? 1 : 0); vkp_effects_set_screen(brightness, contrast, gamma, saturation, fxaa ? 1 : 0, toon ? 1 : 0, crt ? 1 : 0, ntsc ? 1 : 0);
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
@@ -43,17 +43,15 @@ class App : Application() {
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" || if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
CrashHandler.install(this) CrashHandler.install(this)
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this) com.droiddeck.launcher.agent.AgentHost.refresh(this)
com.droiddeck.launcher.agent.AgentTab.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this) com.droiddeck.launcher.ui.NavTabs.load(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.AgentPet.install(this) com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent" if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
com.droiddeck.launcher.lab.LabNotice.started(this) com.droiddeck.launcher.lab.LabNotice.started(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this) com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this) com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this) com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.entries.map { it.id })
com.droiddeck.launcher.update.AppUpdates.init(this) com.droiddeck.launcher.update.AppUpdates.init(this)
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null)) com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
com.droiddeck.launcher.core.DownloadSource.init(this) com.droiddeck.launcher.core.DownloadSource.init(this)
@@ -31,6 +31,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
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.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.AppLanguage import com.droiddeck.launcher.core.AppLanguage
@@ -44,6 +45,10 @@ import java.lang.ref.WeakReference
/** Floats a sign-in code over the browser page that asks for it. */ /** Floats a sign-in code over the browser page that asks for it. */
class DeviceCodeActivity : ComponentActivity() { class DeviceCodeActivity : ComponentActivity() {
private var code by mutableStateOf("") private var code by mutableStateOf("")
private var label by mutableStateOf("")
private var message by mutableStateOf<String?>(null)
private var paste = false
private var agent = true
private var url = "" private var url = ""
private var display: Int? = null private var display: Int? = null
private var inPip by mutableStateOf(false) private var inPip by mutableStateOf(false)
@@ -85,6 +90,18 @@ class DeviceCodeActivity : ComponentActivity() {
} }
} }
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus && paste && !inPip) tryPaste()
}
/** Android hands the clipboard only to the app in front, which this float is once expanded. */
private fun tryPaste() {
val text = runCatching { getSystemService(ClipboardManager::class.java)?.primaryClip?.getItemAt(0)?.coerceToText(this)?.toString() }.getOrNull()
if (text.isNullOrBlank()) return
if (onPaste?.invoke(this, text) == true) returnToApp()
}
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
inPip = isInPictureInPictureMode inPip = isInPictureInPictureMode
@@ -94,12 +111,16 @@ class DeviceCodeActivity : ComponentActivity() {
private fun read(intent: Intent) { private fun read(intent: Intent) {
code = intent.getStringExtra(EXTRA_CODE).orEmpty() code = intent.getStringExtra(EXTRA_CODE).orEmpty()
url = intent.getStringExtra(EXTRA_URL).orEmpty() url = intent.getStringExtra(EXTRA_URL).orEmpty()
label = intent.getStringExtra(EXTRA_LABEL) ?: getString(R.string.agent_step_github)
agent = intent.getBooleanExtra(EXTRA_AGENT, true)
message = intent.getStringExtra(EXTRA_MESSAGE)
paste = intent.getBooleanExtra(EXTRA_PASTE, false)
display = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it > 0 } display = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it > 0 }
copy() if (agent) copy()
} }
private fun copy() { private fun copy() {
runCatching { getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("GitHub", code)) } runCatching { getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText(label, code)) }
} }
private fun enterPip() { private fun enterPip() {
@@ -116,7 +137,8 @@ class DeviceCodeActivity : ComponentActivity() {
if (at == null) startActivity(intent) if (at == null) startActivity(intent)
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(at).toBundle()) else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(at).toBundle())
}.recoverCatching { startActivity(intent) }.isSuccess }.recoverCatching { startActivity(intent) }.isSuccess
com.droiddeck.launcher.agent.AgentHost.deviceCodeOpened(applicationContext, opened) if (agent) com.droiddeck.launcher.agent.AgentHost.deviceCodeOpened(applicationContext, opened)
else if (!opened) finish()
} }
@androidx.compose.runtime.Composable @androidx.compose.runtime.Composable
@@ -130,12 +152,16 @@ class DeviceCodeActivity : ComponentActivity() {
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(if (inPip) 2.dp else 16.dp), verticalArrangement = Arrangement.spacedBy(if (inPip) 2.dp else 16.dp),
) { ) {
Text(stringResource(R.string.agent_step_github), style = MaterialTheme.typography.labelLarge, color = colors.onSurfaceVariant) Text(label, style = MaterialTheme.typography.labelLarge, color = colors.onSurfaceVariant)
FitText(code, maxSize = if (inPip) 40.sp else 56.sp, fontWeight = FontWeight.Bold, color = accent, val shown = message
if (shown != null) Text(shown, fontSize = if (inPip) 12.sp else 22.sp, fontWeight = FontWeight.Bold, color = accent,
maxLines = 4, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth())
else FitText(code, maxSize = if (inPip) 40.sp else 56.sp, fontWeight = FontWeight.Bold, color = accent,
modifier = Modifier.fillMaxWidth()) modifier = Modifier.fillMaxWidth())
Text(Uri.parse(url).let { it.host + it.path }, style = MaterialTheme.typography.labelMedium, color = colors.onSurfaceVariant, maxLines = 1) if (!paste) Text(Uri.parse(url).let { it.host + it.path }, style = MaterialTheme.typography.labelMedium, color = colors.onSurfaceVariant, maxLines = 2, textAlign = TextAlign.Center)
if (!inPip) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { if (!inPip) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
PrimaryButton(stringResource(R.string.fm_copy), onClick = ::copy) if (paste) PrimaryButton(stringResource(R.string.fm_paste), onClick = ::tryPaste)
else PrimaryButton(stringResource(R.string.fm_copy), onClick = ::copy)
SecondaryButton(stringResource(R.string.common_close), onClick = ::finish) SecondaryButton(stringResource(R.string.common_close), onClick = ::finish)
} }
} }
@@ -146,13 +172,24 @@ class DeviceCodeActivity : ComponentActivity() {
private const val EXTRA_CODE = "code" private const val EXTRA_CODE = "code"
private const val EXTRA_URL = "url" private const val EXTRA_URL = "url"
private const val EXTRA_DISPLAY = "display" private const val EXTRA_DISPLAY = "display"
private const val EXTRA_LABEL = "label"
private const val EXTRA_AGENT = "agent"
private const val EXTRA_MESSAGE = "message"
private const val EXTRA_PASTE = "paste"
/** Takes what the user copied from the page; true once it was accepted. */
@Volatile var onPaste: ((Context, String) -> Boolean)? = null
private var current: WeakReference<DeviceCodeActivity>? = null private var current: WeakReference<DeviceCodeActivity>? = null
/** False when this device cannot float a window, so the caller opens the page itself. */ /**
fun show(context: Context, code: String, url: String, display: Int): Boolean { * False when this device cannot float a window, so the caller opens the page itself. [message]
* replaces the code; [paste] shows a Paste button that hands the clipboard to [onPaste].
*/
fun show(context: Context, code: String, url: String, display: Int, label: String? = null, message: String? = null, paste: Boolean = false): Boolean {
if (!PairingGuideActivity.canFloat(context)) return false if (!PairingGuideActivity.canFloat(context)) return false
val intent = Intent(context, DeviceCodeActivity::class.java) val intent = Intent(context, DeviceCodeActivity::class.java)
.putExtra(EXTRA_CODE, code).putExtra(EXTRA_URL, url).putExtra(EXTRA_DISPLAY, display) .putExtra(EXTRA_CODE, code).putExtra(EXTRA_URL, url).putExtra(EXTRA_DISPLAY, display)
.putExtra(EXTRA_AGENT, label == null).also { if (label != null) it.putExtra(EXTRA_LABEL, label); if (message != null) it.putExtra(EXTRA_MESSAGE, message); it.putExtra(EXTRA_PASTE, paste) }
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return runCatching { return runCatching {
if (display > 0) context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle()) if (display > 0) context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
@@ -164,4 +201,12 @@ class DeviceCodeActivity : ComponentActivity() {
current?.get()?.finish() current?.get()?.finish()
} }
} }
private fun returnToApp() {
runCatching {
startActivity(Intent(this, FrontEndActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
}
finish()
}
} }
@@ -319,7 +319,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers() refreshDrivers()
return return
} }
if (gpu.family.mali && !DriverPairs.autoEligible(gpu) && if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) { com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
releaseChecking = true releaseChecking = true
autoStatus = activity.getString(R.string.drivers_checking_latest) autoStatus = activity.getString(R.string.drivers_checking_latest)
@@ -335,14 +335,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-name").start() }, "gpu-name").start()
return return
} }
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) eligible=${DriverPairs.autoEligible(gpu)}") Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair"))
if (gpu.family.mali && !DriverPairs.autoEligible(gpu)) { if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) {
// No PanVK build covers this Mali (e.g. the G1 series, arch v14): the phone's own driver. // No PanVK build covers this Mali (e.g. the G1 series, arch v14): the phone's own driver.
autoStatus = useMaliFallback(null) autoStatus = useMaliFallback(null)
refreshDrivers() refreshDrivers()
return return
} }
if (!DriverPairs.autoEligible(gpu)) { if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase()) autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return return
} }
@@ -372,11 +372,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
} }
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> { gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
// RADV is not published right now: the Xclipse falls back to the system route. // RADV is not published right now: the Xclipse falls back to the system route.
if (gpu.name.contains("Xclipse", ignoreCase = true) && DriverPairs.xclipseNeedsUpstream(gpu.name)) { SessionPrefs.ensurePowerVrAutoDrivers(activity)
if (!SessionState.running) SessionPrefs.ensurePowerVrAutoDrivers(activity, powerVr = true, autoOwnedOnly = true)
} else {
SessionPrefs.ensurePowerVrAutoDrivers(activity)
}
autoStatus = activity.getString(R.string.drivers_powervr_builtin) autoStatus = activity.getString(R.string.drivers_powervr_builtin)
refreshDrivers() refreshDrivers()
} }
@@ -99,7 +99,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
this, ui, this, ui,
idle = { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null }, idle = { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null },
onInstalled = { if (!OfflineMode.enabled(this)) components.checkComponentUpdates(force = false) }, onInstalled = { if (!OfflineMode.enabled(this)) components.checkComponentUpdates(force = false) },
onRemoved = { components.refreshComponents() },
) )
private var installed by mutableStateOf<String?>(null) private var installed by mutableStateOf<String?>(null)
@@ -181,6 +180,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var fsyncFirst by mutableStateOf(false) private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false) private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true) private var paceCores by mutableStateOf(true)
private var ramCapMb by mutableStateOf(0)
private var zramClient by mutableStateOf(true)
private var zramIdle by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false) private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true) private var prootFastPath by mutableStateOf(true)
@@ -205,6 +208,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var animationsEnabled by mutableStateOf(true) private var animationsEnabled by mutableStateOf(true)
private var lowStorageWarning by mutableStateOf(true) private var lowStorageWarning by mutableStateOf(true)
private var launcherIcon by mutableStateOf(LauncherIcon.DARK) private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true)
private var soundtracksEnabled by mutableStateOf(true)
private var soundtracksIngame by mutableStateOf(false) private var soundtracksIngame by mutableStateOf(false)
private var soundtracks by mutableStateOf<List<Library.SteamGame>>(emptyList()) private var soundtracks by mutableStateOf<List<Library.SteamGame>>(emptyList())
private var soundtracksLoaded by mutableStateOf(false) private var soundtracksLoaded by mutableStateOf(false)
@@ -276,11 +281,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) } if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) }
} }
private val pickExperimentalProton = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { zip ->
protons.installExperimental { progress -> com.droiddeck.launcher.session.ExperimentalProtons.installFromFile(this, zip, progress) }
}
}
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
} }
@@ -875,7 +875,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) } runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
}, "components-restore").start() }, "components-restore").start()
} }
private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null private var pendingGameLink: String? = null
private var gameLinkReading = false private var gameLinkReading = false
private var gameLinkTried = false private var gameLinkTried = false
private var gameSyncFolder by mutableStateOf<String?>(null) private var gameSyncFolder by mutableStateOf<String?>(null)
@@ -911,16 +911,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
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 ->
val section = uri.pathSegments.firstOrNull()
navRequest = if (section in setOf("storage", "sync", "downloads")) section
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
request.data = null
gameLinkReading = false
pendingGameLink = null
syncDualPanel()
return
}
if (navRequest == com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS) { if (navRequest == com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS) {
homeAppSelected = HomeApp.isHomeScreenEnabled(this) && HomeApp.isDefault(this) homeAppSelected = HomeApp.isHomeScreenEnabled(this) && HomeApp.isDefault(this)
if (!homeAppSelected) navRequest = null if (!homeAppSelected) navRequest = null
@@ -937,7 +927,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request) val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request)
if (soundtrackId != null) { if (soundtrackId != null) {
soundtrackLaunch = true soundtrackLaunch = true
navRequest = if ("soundtracks" !in com.droiddeck.launcher.ui.NavTabs.hidden) "sound:$soundtrackId" else "app:$soundtrackId" navRequest = if (SessionPrefs.soundtracksEnabled(this)) "sound:$soundtrackId" else "app:$soundtrackId"
request.data = null request.data = null
request.action = Intent.ACTION_MAIN request.action = Intent.ACTION_MAIN
return return
@@ -947,12 +937,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
val copy = Intent(request) val copy = Intent(request)
Thread({ Thread({
val game = GameLaunchIntent.read(this, copy) val id = GameLaunchIntent.read(this, copy)
ui.post { ui.post {
if (intent === request && !isDestroyed) { if (intent === request && !isDestroyed) {
gameLinkReading = false gameLinkReading = false
pendingGameLink = game pendingGameLink = id
if (game == null) { if (id == null) {
syncDualPanel() syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
} else { } else {
@@ -965,36 +955,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
} }
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) { private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
val request = gameLaunchRequest.incrementAndGet()
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this) if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
if (pkgStage != null) { if (pkgStage != null) {
onHandled() onHandled()
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return return false
} }
val files = game.gameFiles
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
if (startGame(game, returnHome, onHandled)) onSettled()
return
}
Thread({
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
ui.post {
when {
request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled()
refused -> {
onHandled()
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
onSettled()
}
startGame(game, returnHome, onHandled) -> onSettled()
}
}
}, "xbox-app-model").start()
}
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean {
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled) if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
onHandled() onHandled()
if (SessionState.running) { if (SessionState.running) {
@@ -1202,28 +1169,26 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) { private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val request = pendingGameLink ?: return val id = pendingGameLink ?: return
val game = request.find(games, byTitle = scanned) if (!scanned && games.none { it.gameIdString == id }) return
if (!scanned && game == null) return
gameLinkTried = true gameLinkTried = true
ui.postDelayed({ ui.postDelayed({
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel() if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
}, LINK_PANEL_MS) }, LINK_PANEL_MS)
val link = intent val game = games.firstOrNull { it.gameIdString == id }
fun consume() {
if (intent !== link || pendingGameLink !== request) return
pendingGameLink = null
link.data = null
link.action = Intent.ACTION_MAIN
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
}
if (game == null) { if (game == null) {
consume() pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
syncDualPanel() syncDualPanel()
android.widget.Toast.makeText(this, android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing, } else if (launchGame(game, returnHome = true)) {
android.widget.Toast.LENGTH_LONG).show() pendingGameLink = null
} else launchGame(game, returnHome = true, onSettled = ::consume) intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
}
} }
private fun chooseGameShortcut(game: Library.SteamGame) { private fun chooseGameShortcut(game: Library.SteamGame) {
@@ -1270,6 +1235,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
lowStorageWarning = SessionPrefs.lowStorageWarning(this) lowStorageWarning = SessionPrefs.lowStorageWarning(this)
LauncherIcon.repair(this, intent?.component) LauncherIcon.repair(this, intent?.component)
launcherIcon = LauncherIcon.current(this) launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
soundtracksEnabled = SessionPrefs.soundtracksEnabled(this)
soundtracksIngame = SessionPrefs.soundtracksIngame(this) soundtracksIngame = SessionPrefs.soundtracksIngame(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this) gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
storesShowMature = SessionPrefs.storesShowMature(this) storesShowMature = SessionPrefs.storesShowMature(this)
@@ -1282,8 +1249,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
androidx.compose.runtime.LaunchedEffect(prootPack) { androidx.compose.runtime.LaunchedEffect(prootPack) {
if (prootPack == com.droiddeck.launcher.core.AddonPack.State.Ready && installed == null) refresh() if (prootPack == com.droiddeck.launcher.core.AddonPack.State.Ready && installed == null) refresh()
} }
val appsTabShown = "android-apps" !in com.droiddeck.launcher.ui.NavTabs.hidden
androidx.compose.runtime.LaunchedEffect(appsTabShown) { if (appsTabShown && androidApps.isEmpty()) refreshAndroidApps() }
DroidDeckTheme(theme, appScale = appScale) { DroidDeckTheme(theme, appScale = appScale) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) {
if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog( if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog(
@@ -1367,7 +1332,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
animationsEnabled = animationsEnabled, animationsEnabled = animationsEnabled,
lowStorageWarning = lowStorageWarning, lowStorageWarning = lowStorageWarning,
launcherIcon = launcherIcon, launcherIcon = launcherIcon,
soundtracksEnabled = "soundtracks" !in com.droiddeck.launcher.ui.NavTabs.hidden, gameStoresEnabled = gameStoresEnabled,
soundtracksEnabled = soundtracksEnabled,
soundtracksIngame = soundtracksIngame, soundtracksIngame = soundtracksIngame,
soundtracks = soundtracks, soundtracks = soundtracks,
soundtracksLoaded = soundtracksLoaded, soundtracksLoaded = soundtracksLoaded,
@@ -1517,7 +1483,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onComponents = { focusContent -> openComponents(focusContent) }, onComponents = { focusContent -> openComponents(focusContent) },
onGameComponents = { game -> openComponents(gameKey = game.profileKey) }, onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) }, onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(this@FrontEndActivity, sg) } }, onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
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)) {
@@ -1525,9 +1491,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
getString(R.string.main_addons_deleted, name) getString(R.string.main_addons_deleted, name)
} }
}, },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(this@FrontEndActivity, sg) } }, onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true }, onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
performancePanel = { PerformanceHost(embedded = true) },
onRoms = { showRoms = true }, onRoms = { showRoms = true },
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) }, onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
onBrowseFiles = { dir -> onBrowseFiles = { dir ->
@@ -1643,6 +1608,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
offline = OfflineMode.enabled(this) offline = OfflineMode.enabled(this)
}, },
onPageBack = { showPerformance = false; showComponents = false; showMapping = false }, onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
onSoundtracksEnabled = { on -> SessionPrefs.setSoundtracksEnabled(this, on); soundtracksEnabled = on },
onSoundtracksIngame = { on -> onSoundtracksIngame = { on ->
SessionPrefs.setSoundtracksIngame(this, on) SessionPrefs.setSoundtracksIngame(this, on)
soundtracksIngame = on soundtracksIngame = on
@@ -1941,7 +1908,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onNewIntent(intent: Intent) { override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent) super.onNewIntent(intent)
setIntent(intent) setIntent(intent)
gameLaunchRequest.incrementAndGet()
if (intent.action == SteamIntegration.ACTION_SETUP) { if (intent.action == SteamIntegration.ACTION_SETUP) {
gameLinkReading = false gameLinkReading = false
pendingGameLink = null pendingGameLink = null
@@ -2008,6 +1974,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (hasFocus) { if (hasFocus) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
applyLauncherFullscreen() applyLauncherFullscreen()
com.droiddeck.launcher.stores.epic.EpicCodeLogin.resumed(this)
} }
} }
@@ -2234,13 +2201,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
private fun refreshAndroidApps() { private fun refreshAndroidApps() {
if (!homeAppSelected && "android-apps" in com.droiddeck.launcher.ui.NavTabs.hidden) { if (!homeAppSelected) {
++androidAppsListing ++androidAppsListing
androidApps = emptyList() androidApps = emptyList()
return return
} }
val seq = ++androidAppsListing val seq = ++androidAppsListing
if (homeAppSelected) HomePins.refresh(this) HomePins.refresh(this)
Thread({ Thread({
val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList()) val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList())
ui.post { if (seq == androidAppsListing) androidApps = apps } ui.post { if (seq == androidAppsListing) androidApps = apps }
@@ -2435,20 +2402,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
), ),
protons = com.droiddeck.launcher.ui.ProtonsState( protons = com.droiddeck.launcher.ui.ProtonsState(
rows = protons.protonRows, busyId = protons.protonBusyId, stage = protons.protonStage, percent = protons.protonPercent, rows = protons.protonRows, busyId = protons.protonBusyId, stage = protons.protonStage, percent = protons.protonPercent,
runtimeReady = ready && !busy, sessionRunning = SessionState.running, experimental = protons.experimentalDirs, runtimeReady = ready && !busy, sessionRunning = SessionState.running,
experimentalReleases = protons.experimentalReleases,
), ),
protonActions = com.droiddeck.launcher.ui.ProtonsActions( protonActions = com.droiddeck.launcher.ui.ProtonsActions(
onInstall = { id -> protons.installProton(id) }, onInstall = { id -> protons.installProton(id) },
onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() }, onCancel = { id -> ProtonExtras.tools.firstOrNull { it.id == id }?.let { ProtonExtras.unqueue(this, it) }; protons.refreshProtons() },
onRemove = { id, dir -> protons.removeProton(id, dir) }, onRemove = { id, dir -> protons.removeProton(id, dir) },
onRemoveOlder = { id -> protons.removeProton(id, older = true) }, onRemoveOlder = { id -> protons.removeProton(id, older = true) },
onExperimentalFile = {
pickExperimentalProton.launch(InAppFilePicker.buildIntent(this, EXPERIMENTAL_PROTON_EXT, getString(R.string.xproton_install_file),
android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path))
},
onExperimentalRelease = { release -> protons.installExperimentalRelease(release) },
onRemoveExperimental = { dir -> protons.removeExperimental(dir) },
), ),
protonOptions = { protonOptions = {
com.droiddeck.launcher.ui.ProtonOptions( com.droiddeck.launcher.ui.ProtonOptions(
@@ -2745,8 +2705,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
@Composable @Composable
private fun PerformanceHost(embedded: Boolean = false) { private fun PerformanceHost() {
if (embedded) androidx.compose.runtime.LaunchedEffect(Unit) { refreshCores() }
PerformancePage( PerformancePage(
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) }, cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, paceCores = paceCores, clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, paceCores = paceCores,
@@ -2756,6 +2715,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst, fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime, gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin, gpuClockPin = gpuClockPin,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient, zramIdle = zramIdle,
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite, prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning, guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on }, onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
@@ -2770,6 +2733,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on }, onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on }, onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on }, onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
onZramIdle = { on -> SessionPrefs.setZramIdle(this, on); zramIdle = on },
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on }, onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on }, onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on }, onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
@@ -2784,7 +2751,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.setGameCpus(this, CpuCores.format(gameCores)) SessionPrefs.setGameCpus(this, CpuCores.format(gameCores))
}, },
onDismiss = { showPerformance = false }, onDismiss = { showPerformance = false },
embedded = embedded,
) )
} }
@@ -3068,6 +3034,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = SessionPrefs.fsyncFirst(this) fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this) gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this) paceCores = SessionPrefs.paceCores(this)
ramCapMb = SessionPrefs.ramCapMb(this)
zramClient = SessionPrefs.zramClient(this)
zramIdle = SessionPrefs.zramIdle(this)
vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this) gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this) prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this) prootFastPath = SessionPrefs.prootFastPath(this)
@@ -3124,8 +3094,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
installed = LinuxRuntimeInstaller.installedVersion(this) installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this) ready = LinuxRuntime.isInstalled(this)
vkBridge = SessionPrefs.vkBridge(this) vkBridge = SessionPrefs.vkBridge(this)
venus = SessionPrefs.venus(this)
venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this) vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this) bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this) removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
@@ -3332,7 +3300,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM) com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show() if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this) com.droiddeck.launcher.agent.AgentTab.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this) com.droiddeck.launcher.ui.NavTabs.load(this)
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate() if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
} }
@@ -3417,7 +3385,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private const val KEY_SWITCH_DEADLINE = "switch_deadline" private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED) private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val ZIP_EXT = listOf("zip") private val ZIP_EXT = listOf("zip")
private val EXPERIMENTAL_PROTON_EXT = listOf("zip", "7z", "tar", "gz", "xz", "zst", "bz2", "tgz", "txz", "tbz2", "tzst")
private val WCP_EXT = listOf("wcp") private val WCP_EXT = listOf("wcp")
} }
} }
@@ -7,7 +7,6 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.ProtonExtras import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionState
@@ -20,7 +19,6 @@ internal class ProtonMenu(
private val activity: android.app.Activity, private val activity: android.app.Activity,
private val ui: Handler, private val ui: Handler,
private val onInstalled: () -> Unit = {}, private val onInstalled: () -> Unit = {},
private val onRemoved: () -> Unit = {},
private val idle: () -> Boolean = { true }, private val idle: () -> Boolean = { true },
) { ) {
private object Operation { private object Operation {
@@ -29,23 +27,13 @@ internal class ProtonMenu(
val stage = mutableStateOf<String?>(null) val stage = mutableStateOf<String?>(null)
val percent = mutableIntStateOf(-1) val percent = mutableIntStateOf(-1)
val problem = mutableStateOf<String?>(null) val problem = mutableStateOf<String?>(null)
val experimental = mutableStateOf<List<String>>(emptyList())
val experimentalReleases = mutableStateOf<List<ExperimentalProtons.Release>>(emptyList())
var fetchedReleases = emptyList<ExperimentalProtons.Release>()
val checking = java.util.concurrent.atomic.AtomicBoolean(false)
} }
var protonRows by Operation.rows var protonRows by Operation.rows
var protonBusyId by Operation.busyId var protonBusyId by Operation.busyId
var protonStage by Operation.stage var protonStage by Operation.stage
var protonPercent by Operation.percent var protonPercent by Operation.percent
var protonProblem by Operation.problem var protonProblem by Operation.problem
var experimentalDirs by Operation.experimental private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
var experimentalReleases by Operation.experimentalReleases
companion object {
const val EXPERIMENTAL = "experimental"
}
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? = @VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) } { tool, progress -> ProtonExtras.install(activity, tool, progress) }
@@ -98,80 +86,21 @@ internal class ProtonMenu(
}, "remove-proton-$id").start() }, "remove-proton-$id").start()
} }
fun installExperimental(work: ((String, Int) -> Unit) -> String?) {
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
protonBusyId = EXPERIMENTAL
protonProblem = null
protonStage = activity.getString(R.string.store_starting)
protonPercent = -1
Thread({
val problem = runCatching {
work { label, value -> ui.post { protonStage = label; protonPercent = value } }
}.getOrElse { it.message ?: it.javaClass.simpleName }
ui.post {
protonProblem = problem
protonBusyId = null
protonStage = null
protonPercent = -1
refreshProtons()
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.xproton_installed), android.widget.Toast.LENGTH_LONG).show()
if (problem == null) onInstalled()
}
}, "install-proton-experimental").start()
}
fun installExperimentalRelease(release: ExperimentalProtons.Release) {
installExperimental { progress -> ExperimentalProtons.installRelease(activity, release, progress) }
}
fun removeExperimental(dir: String) {
if (protonBusyId != null || SessionState.running) return
protonBusyId = EXPERIMENTAL
protonProblem = null
protonStage = activity.getString(R.string.main_removing_named, dir)
protonPercent = -1
Thread({
val removed = runCatching { ExperimentalProtons.remove(activity, dir) }.getOrDefault(false)
ui.post {
protonBusyId = null
protonStage = null
refreshProtons()
if (!removed) android.widget.Toast.makeText(activity, activity.getString(R.string.xproton_remove_failed, dir), android.widget.Toast.LENGTH_LONG).show()
}
}, "remove-proton-experimental").start()
}
private fun refreshExperimental() {
val installed = ExperimentalProtons.installed(activity)
experimentalDirs = installed.map { it.dir }
experimentalReleases = ExperimentalProtons.available(Operation.fetchedReleases, installed)
}
fun refreshProtons() { fun refreshProtons() {
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))
} }
} }
fun checkUpdates(force: Boolean = false) { fun checkUpdates(force: Boolean = false) {
if (!Operation.checking.compareAndSet(false, true)) return if (!checking.compareAndSet(false, true)) return
Thread({ Thread({
val asked = runCatching { latestCheck(force) }.getOrDefault(false) val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
val experimental = runCatching { experimentalRefresh() }.getOrNull() ui.post {
val published = ui.post { if (asked) refreshProtons()
try {
val before = experimentalDirs
Operation.fetchedReleases = experimental ?: emptyList()
if (asked) refreshProtons() else refreshExperimental()
if (!experimentalDirs.containsAll(before)) onRemoved()
} finally {
Operation.checking.set(false)
}
ensureAutoUpdates() ensureAutoUpdates()
} }
if (!published) Operation.checking.set(false)
}, "proton-updates").start() }, "proton-updates").start()
} }
File diff suppressed because it is too large. Load diff
@@ -76,9 +76,6 @@ class AgentBridgeProvider : ContentProvider() {
"stop" -> stop(context) "stop" -> stop(context)
"resume" -> resume(context) "resume" -> resume(context)
"launch" -> launch(context, request) "launch" -> launch(context, request)
"library" -> AgentStores.library(context, request)
"xodus" -> AgentStores.xodus(context, request)
"cloud" -> AgentStores.cloud(context, request)
"focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000) "focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000)
"quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId")) "quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId"))
.put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000)) .put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000))
@@ -1,27 +0,0 @@
package com.droiddeck.launcher.agent
import android.content.Context
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
/** The text typed in the Agent tab and not yet sent, kept across leaving the tab and restarts. */
object AgentDraft {
private const val KEY = "draft"
private var state: MutableState<String>? = null
fun state(context: Context): MutableState<String> = state ?: run {
val prefs = AgentHost.prefs(context.applicationContext)
val backing = mutableStateOf(prefs.getString(KEY, "") ?: "")
object : MutableState<String> {
override var value: String
get() = backing.value
set(text) {
if (text == backing.value) return
backing.value = text
prefs.edit().apply { if (text.isEmpty()) remove(KEY) else putString(KEY, text) }.apply()
}
override fun component1() = value
override fun component2(): (String) -> Unit = { value = it }
}.also { state = it }
}
}
@@ -58,8 +58,7 @@ object AgentEnv {
fun override(context: Context, name: String): JSONObject = synchronized(lock) { fun override(context: Context, name: String): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context) AgentAccess.requireCommands(context)
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'") if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
if (name == LEGACY_FAST_PATH) throw AgentException("INVALID_NAME", "The fast-path library is now $FAST_PATH") if (name == "libblfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
if (name == "libddfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library") throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library")
} }
val source = File(inbox(context), name) val source = File(inbox(context), name)
@@ -74,7 +73,7 @@ object AgentEnv {
staged.delete() staged.delete()
throw AgentException("OVERRIDE_FAILED", "Could not stage the override") throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
} }
if (name == "libddfastpath.so" && !arm64SharedLibrary(staged)) { if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) {
staged.delete() staged.delete()
throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library") throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library")
} }
@@ -87,7 +86,7 @@ object AgentEnv {
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name)))) state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
save(context, state) save(context, state)
state.put("installed", "$GUEST_BIN/$name") state.put("installed", "$GUEST_BIN/$name")
if (name == "libddfastpath.so") { if (name == "libblfastpath.so") {
val digest = MessageDigest.getInstance("SHA-256") val digest = MessageDigest.getInstance("SHA-256")
target.inputStream().use { input -> target.inputStream().use { input ->
val buffer = ByteArray(65536) val buffer = ByteArray(65536)
@@ -104,10 +103,10 @@ object AgentEnv {
fun fastPathLibrary(context: Context): String = synchronized(lock) { fun fastPathLibrary(context: Context): String = synchronized(lock) {
if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY
if ("libddfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY if ("libblfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY
val file = File(bin(context), "libddfastpath.so") val file = File(bin(context), "libblfastpath.so")
if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY
"$GUEST_BIN/libddfastpath.so" "$GUEST_BIN/libblfastpath.so"
} }
private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input -> private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input ->
@@ -130,18 +129,13 @@ object AgentEnv {
} }
val state = load(context) val state = load(context)
val active = strings(state.optJSONArray("pending")) val active = strings(state.optJSONArray("pending"))
val queued = strings(state.optJSONArray("pendingOverrides")) val overrides = strings(state.optJSONArray("pendingOverrides"))
val legacy = File(bin(context), LEGACY_FAST_PATH)
val stranded = FAST_PATH in queued && legacy.isFile && !File(bin(context), FAST_PATH).exists() &&
!legacy.renameTo(File(bin(context), FAST_PATH))
if (stranded) Log.w(TAG, "could not rename the queued $LEGACY_FAST_PATH; it stays queued for the next session")
val overrides = if (stranded) queued - FAST_PATH else queued
bin(context).listFiles() bin(context).listFiles()
?.filter { it.name !in overrides && !(stranded && it.name == LEGACY_FAST_PATH) }?.forEach { it.delete() } ?.filter { it.name !in overrides }?.forEach { it.delete() }
val lines = strings(state.optJSONArray("persistent")) + active val lines = strings(state.optJSONArray("persistent")) + active
val withPath = if (overrides.none { it != "libddfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}" val withPath = if (overrides.none { it != "libblfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
state.put("active", JSONArray(active)).put("pending", JSONArray()) state.put("active", JSONArray(active)).put("pending", JSONArray())
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray(if (stranded) listOf(FAST_PATH) else emptyList())) state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
save(context, state) save(context, state)
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}") if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
withPath withPath
@@ -164,9 +158,6 @@ object AgentEnv {
save(context, state) save(context, state)
} }
private const val FAST_PATH = "libddfastpath.so"
private const val LEGACY_FAST_PATH = "libblfastpath.so"
private fun pathOf(lines: List<String>) = private fun pathOf(lines: List<String>) =
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: LinuxRuntime.GUEST_PATH lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: LinuxRuntime.GUEST_PATH
@@ -195,9 +186,6 @@ object AgentEnv {
for (key in listOf("pending", "active", "persistent", "pendingOverrides", "activeOverrides")) { for (key in listOf("pending", "active", "persistent", "pendingOverrides", "activeOverrides")) {
if (!state.has(key)) state.put(key, JSONArray()) if (!state.has(key)) state.put(key, JSONArray())
} }
for (key in listOf("pendingOverrides", "activeOverrides")) {
state.put(key, JSONArray(strings(state.optJSONArray(key)).map { if (it == LEGACY_FAST_PATH) FAST_PATH else it }.distinct()))
}
return state return state
} }
@@ -1,13 +1,11 @@
package com.droiddeck.launcher.agent package com.droiddeck.launcher.agent
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.R
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
/** One coding agent CLI in the Linux userland, run as a process that takes its turns over stdin (see [AgentProtocol]). */ /** One coding agent CLI in the Linux userland, run one process per turn (or kept open, see [input]). */
interface AgentHarness { interface AgentHarness {
val id: String val id: String
val name: String val name: String
@@ -21,36 +19,22 @@ interface AgentHarness {
val signedIn: List<String> val signedIn: List<String>
/** A guest command that signs in through $BROWSER. */ /** A guest command that signs in through $BROWSER. */
val signIn: List<String> val signIn: List<String>
/**
* APIs the CLI reaches with a key pasted into DroidDeck, for a CLI whose own sign-in is a terminal
* prompt; empty when it signs in through [signIn].
*/
val providers: List<Provider> get() = emptyList()
/** Ids of the [providers] with a key saved under [rootfs]. */
fun keys(rootfs: File): Set<String> = emptySet()
/**
* Saves [key] for [provider]. A [Provider.custom] one also takes the [endpoint] it is served from, and
* [get] fetches a URL from the userland, with the key as a bearer token when it is not null.
*/
fun saveKey(rootfs: File, provider: Provider, key: String, endpoint: String? = null, get: (String, String?) -> String = { url, _ -> error("Cannot reach $url") }) {}
fun removeKey(rootfs: File, provider: Provider) {}
/** Whether the CLI has models that need no account; [useFree] then counts as signed in. */
val free: Boolean get() = false
fun useFree(rootfs: File) {}
/** Usage reports the conversation's whole cost rather than the turn's. */
val sessionCost: Boolean get() = false
/** Whether [Options.plan] means anything to this CLI. */ /** Whether [Options.plan] means anything to this CLI. */
val plans: Boolean val plans: Boolean
/** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */ /** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */
val efforts: List<String> val efforts: List<String>
/** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */ /** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */
fun models(rootfs: File): List<Model> fun models(rootfs: File): List<Model>
/** How the CLI may run its tools, the one that asks before each action first and the default. */ /** The guest command for one turn; [conversation] is null for the first one. */
val permissions: List<Permission>
/** The guest command of the process that runs the conversation's turns; [conversation] is null for a new one. */
fun turn(message: String, conversation: String?, options: Options): List<String> fun turn(message: String, conversation: String?, options: Options): List<String>
/** A new reader for one [turn] process; it keeps what that process has said so far. */ /**
fun protocol(): AgentProtocol * The line that hands [message] to a [turn] process over stdin, or null when the message is already in the
* command. A process that takes its messages this way stays open between turns, so work it started in the
* background can wake it, as it does in the CLI's own terminal.
*/
fun input(message: String): String? = null
/** One line of the CLI's output, or null when it carries nothing to show. */
fun parse(line: String): AgentEvent?
/** The folder, under the userland's root, where the CLI loads user skills (`<name>/SKILL.md`). */ /** The folder, under the userland's root, where the CLI loads user skills (`<name>/SKILL.md`). */
val skills: String val skills: String
/** The CLI's global instructions file under the userland's root, where DroidDeck keeps its rules in a marked block. */ /** The CLI's global instructions file under the userland's root, where DroidDeck keeps its rules in a marked block. */
@@ -62,45 +46,14 @@ interface AgentHarness {
data class Model(val id: String, val label: String) data class Model(val id: String, val label: String)
/** An API reached with a key; [keyPage] is where the key is made, and a [custom] one is any OpenAI-compatible server. */ data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null)
data class Provider(val id: String, val name: String, val keyPage: String? = null, val custom: Boolean = false)
/** A permission mode; [id] is DroidDeck's own name for it, which each CLI maps to its flags. */
data class Permission(val id: String, @StringRes val label: Int, @StringRes val hint: Int)
data class Options(
val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null,
val permission: String = ASK, val workdir: String = "/root",
)
companion object { companion object {
const val ASK = "ask" val all: List<AgentHarness> = listOf(ClaudeCode, Codex)
const val EDITS = "edits"
const val AUTO = "auto"
const val DONT_ASK = "dontask"
const val FULL = "full"
val all: List<AgentHarness> = listOf(ClaudeCode, Codex, OpenCode)
fun byId(id: String?): AgentHarness = all.firstOrNull { it.id == id } ?: ClaudeCode fun byId(id: String?): AgentHarness = all.firstOrNull { it.id == id } ?: ClaudeCode
} }
} }
/** What goes to one CLI process's stdin, and what its output lines mean. */
interface AgentProtocol {
/**
* The lines that start a turn of [message]; [started] is true for a process that has just been started. The
* process stays open between turns, so work it started in the background can wake it.
*/
fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List<String>
/** One line of the process's output, or null when it carries nothing to show. */
fun parse(line: String): AgentEvent?
/** The line that answers [approval]. */
fun answer(approval: AgentHost.Approval, allow: Boolean): String
}
/** The message a CLI tells its model when the user denies a tool call. */
internal const val DENIED = "The user denied this tool call."
/** What one line of output carries: whole entries, or text still being written. */ /** What one line of output carries: whole entries, or text still being written. */
data class AgentEvent( data class AgentEvent(
val conversation: String? = null, val conversation: String? = null,
@@ -117,12 +70,6 @@ data class AgentEvent(
val background: Boolean = false, val background: Boolean = false,
/** The error a background turn ended with, if it failed. */ /** The error a background turn ended with, if it failed. */
val backgroundError: String? = null, val backgroundError: String? = null,
/** Lines to write to the process's stdin right away, the next step of a request it has answered. */
val reply: List<String> = emptyList(),
/** A tool call that waits for the user to allow it. */
val approval: AgentHost.Approval? = null,
/** The id of an approval the CLI no longer waits for. */
val resolved: String? = null,
) )
/** Claude Code: `claude -p` with stream-json input and output, resumed by session id. */ /** Claude Code: `claude -p` with stream-json input and output, resumed by session id. */
@@ -164,54 +111,22 @@ object ClaudeCode : AgentHarness {
AgentHarness.Model("opus", "Opus"), AgentHarness.Model("sonnet", "Sonnet"), AgentHarness.Model("haiku", "Haiku"), AgentHarness.Model("opus", "Opus"), AgentHarness.Model("sonnet", "Sonnet"), AgentHarness.Model("haiku", "Haiku"),
) )
override val permissions = listOf( // DroidDeck runs the agent unattended on the user's own device; permission prompts have no one to answer them.
AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint),
AgentHarness.Permission(AgentHarness.EDITS, R.string.agent_permission_edits, R.string.agent_permission_edits_hint),
AgentHarness.Permission(AgentHarness.AUTO, R.string.agent_permission_auto, R.string.agent_permission_auto_hint),
AgentHarness.Permission(AgentHarness.DONT_ASK, R.string.agent_permission_dont_ask, R.string.agent_permission_dont_ask_hint),
AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint),
)
private val MODES = mapOf(
AgentHarness.ASK to "manual", AgentHarness.EDITS to "acceptEdits", AgentHarness.AUTO to "auto",
AgentHarness.DONT_ASK to "dontAsk", AgentHarness.FULL to "bypassPermissions",
)
/**
* Prompts reach DroidDeck as can_use_tool requests on stdout (the SDK's stdio prompt tool). Plan mode keeps
* answering none, so a turn that would leave plan mode ends on its plan.
*/
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList { override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
addAll(listOf(binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages")) addAll(listOf(binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
val mode = if (options.plan) "plan" else MODES[options.permission] ?: "manual" addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions"))
addAll(listOf("--permission-mode", mode))
if (mode != "plan" && mode != "bypassPermissions") add("--permission-prompt-tool=stdio")
options.model?.let { addAll(listOf("--model", it)) } options.model?.let { addAll(listOf("--model", it)) }
options.effort?.let { addAll(listOf("--effort", it)) } options.effort?.let { addAll(listOf("--effort", it)) }
options.brief?.let { addAll(listOf("--append-system-prompt", it)) } options.brief?.let { addAll(listOf("--append-system-prompt", it)) }
if (conversation != null) addAll(listOf("--resume", conversation)) if (conversation != null) addAll(listOf("--resume", conversation))
} }
fun input(message: String): String = JSONObject() override fun input(message: String): String? = JSONObject()
.put("type", "user") .put("type", "user")
.put("message", JSONObject().put("role", "user").put("content", JSONArray().put(JSONObject().put("type", "text").put("text", message)))) .put("message", JSONObject().put("role", "user").put("content", JSONArray().put(JSONObject().put("type", "text").put("text", message))))
.toString() .toString()
override fun protocol(): AgentProtocol = object : AgentProtocol { override fun parse(line: String): AgentEvent? {
override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean) = listOf(this@ClaudeCode.input(message))
override fun parse(line: String) = this@ClaudeCode.parse(line)
override fun answer(approval: AgentHost.Approval, allow: Boolean) = this@ClaudeCode.answer(approval, allow)
}
@VisibleForTesting
internal fun answer(approval: AgentHost.Approval, allow: Boolean): String {
val decision = if (allow) JSONObject().put("behavior", "allow").put("updatedInput", runCatching { JSONObject(approval.payload) }.getOrDefault(JSONObject()))
else JSONObject().put("behavior", "deny").put("message", DENIED)
return JSONObject().put("type", "control_response")
.put("response", JSONObject().put("subtype", "success").put("request_id", approval.id).put("response", decision)).toString()
}
fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() } val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
// A subagent's messages carry the call that started it; only its tool calls are shown, under that call. // A subagent's messages carry the call that started it; only its tool calls are shown, under that call.
@@ -258,13 +173,6 @@ object ClaudeCode : AgentHarness {
AgentEvent(conversation, results) AgentEvent(conversation, results)
} }
"rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info"))) "rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info")))
"control_request" -> {
val request = o.optJSONObject("request")?.takeIf { it.optString("subtype") == "can_use_tool" } ?: return null
val tool = request.optString("tool_name")
val input = request.optJSONObject("input") ?: JSONObject()
AgentEvent(approval = AgentHost.Approval(o.optString("request_id"), tool, detail(input), fullInput(tool, input), input.toString()))
}
"control_cancel_request" -> AgentEvent(resolved = o.optString("request_id"))
// The CLI starts turns of its own for background tasks (a resumed session first answers the ones the last // The CLI starts turns of its own for background tasks (a resumed session first answers the ones the last
// run left behind). Such a result is not the end of the user's turn; the host decides what it ends. // run left behind). Such a result is not the end of the user's turn; the host decides what it ends.
"result" -> { "result" -> {
@@ -347,7 +255,7 @@ object ClaudeCode : AgentHarness {
}.joinToString("\n") }.joinToString("\n")
} }
/** OpenAI Codex: `codex app-server`, its JSON-RPC protocol over stdio, resumed by thread id. */ /** OpenAI Codex: `codex exec --json`, resumed by thread id. */
object Codex : AgentHarness { object Codex : AgentHarness {
override val id = "codex" override val id = "codex"
override val name = "Codex" override val name = "Codex"
@@ -373,13 +281,6 @@ object Codex : AgentHarness {
override val plans = false override val plans = false
override val efforts = listOf("low", "medium", "high") override val efforts = listOf("low", "medium", "high")
// Codex's sandbox needs Landlock and seccomp, which proot does not provide, so commands run unsandboxed
// and "untrusted" is what makes Codex ask before each one that is not known to be safe.
override val permissions = listOf(
AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint),
AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint),
)
/** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */ /** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */
override fun models(rootfs: File): List<AgentHarness.Model> = runCatching { override fun models(rootfs: File): List<AgentHarness.Model> = runCatching {
val o = JSONObject(File(rootfs, "root/.codex/models_cache.json").readText()) val o = JSONObject(File(rootfs, "root/.codex/models_cache.json").readText())
@@ -392,652 +293,108 @@ object Codex : AgentHarness {
} }
}.getOrDefault(emptyList()) }.getOrDefault(emptyList())
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = withoutStderr("codex", listOf(binary, "app-server")) // Codex's own sandbox needs Landlock and seccomp, which proot does not provide.
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
addAll(listOf(binary, "exec"))
if (conversation != null) addAll(listOf("resume", conversation))
addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check"))
options.model?.let { addAll(listOf("-m", it)) }
options.effort?.let { addAll(listOf("-c", "model_reasoning_effort=\"$it\"")) }
// codex exec has no system prompt option, so a new conversation starts with the brief.
add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message)
}
override fun protocol(): AgentProtocol = Protocol() override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
@VisibleForTesting val item = o.optJSONObject("item")
internal class Protocol : AgentProtocol { val id = item?.optString("id").orEmpty()
private var next = 1 val entries = when (o.optString("type")) {
private var thread: String? = null "thread.started" -> return AgentEvent(o.optString("thread_id").takeIf { it.isNotEmpty() })
/** The initialize request, the thread/start or thread/resume sent once it succeeds, and the turn that waits for its thread. */ "item.started" -> when (item?.optString("type")) {
private var initializing = -1 "command_execution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) }
private var initialized = false "mcp_tool_call" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.optJSONObject("arguments")?.toString(2).orEmpty()))
private var open: String? = null "web_search" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query")))
private var opening = -1
private var waiting: JSONObject? = null
private var starting = -1
private var turnId = ""
/** Each file change's paths and diffs, from its start; an approval for it names only the item. */
private val changes = mutableMapOf<String, JSONArray>()
private var input = 0L
private var output = 0L
override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List<String> {
val turn = JSONObject()
.put("input", JSONArray().put(JSONObject().put("type", "text").put("text", message).put("text_elements", JSONArray())))
options.model?.let { turn.put("model", it) }
options.effort?.let { turn.put("effort", it) }
val known = thread
if (!started && known != null) return listOf(startTurn(turn.put("threadId", known)))
val params = JSONObject()
.put("approvalPolicy", if (options.permission == AgentHarness.FULL) "never" else "untrusted")
.put("sandbox", "danger-full-access")
options.model?.let { params.put("model", it) }
options.brief?.let { params.put("developerInstructions", it) }
if (conversation != null) params.put("threadId", conversation)
waiting = turn
opening = next++
val request = JSONObject().put("id", opening).put("method", if (conversation != null) "thread/resume" else "thread/start").put("params", params).toString()
// Codex refuses a second initialize on one connection, so a thread that failed to open is asked for again alone.
if (initialized) return listOf(request)
open = request
initializing = next++
return listOf(
JSONObject().put("id", initializing).put("method", "initialize")
.put("params", JSONObject().put("clientInfo", JSONObject().put("name", "droiddeck").put("title", "DroidDeck").put("version", "1"))
.put("capabilities", JSONObject.NULL)).toString(),
)
}
private fun startTurn(params: JSONObject): String {
starting = next++
return JSONObject().put("id", starting).put("method", "turn/start").put("params", params).toString()
}
override fun answer(approval: AgentHost.Approval, allow: Boolean): String =
JSONObject(approval.payload).put("result", JSONObject().put("decision", if (allow) "accept" else "decline")).toString()
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val method = o.optString("method")
if (method.isEmpty()) return response(o)
val params = o.optJSONObject("params") ?: JSONObject()
if (o.has("id")) return request(o.get("id"), method, params)
return notification(method, params)
}
private fun response(o: JSONObject): AgentEvent? {
val id = o.optInt("id", -1)
val error = o.optJSONObject("error")?.optString("message")?.ifEmpty { "error" }
return when (id) {
initializing -> {
if (error != null) return AgentEvent(entries = listOf(AgentHost.Entry.Finished(error)))
initialized = true
val request = open ?: return null
open = null
AgentEvent(reply = listOf(JSONObject().put("method", "initialized").toString(), request))
}
opening -> {
if (error != null) return AgentEvent(entries = listOf(AgentHost.Entry.Finished(error)))
val started = o.optJSONObject("result")?.optJSONObject("thread")?.optString("id")?.takeIf { it.isNotEmpty() } ?: return null
thread = started
val turn = waiting ?: return AgentEvent(started)
waiting = null
AgentEvent(started, reply = listOf(startTurn(turn.put("threadId", started))))
}
starting -> error?.let { AgentEvent(entries = listOf(AgentHost.Entry.Finished(it))) }
else -> null
}
}
private fun request(id: Any, method: String, params: JSONObject): AgentEvent {
val payload = JSONObject().put("id", id).toString()
return when (method) {
"item/commandExecution/requestApproval" -> {
val command = shellCommand(params.optString("command"))
val reason = params.optString("reason").takeIf { it.isNotEmpty() && it != "null" }
AgentEvent(approval = AgentHost.Approval(id.toString(), "Shell", firstLine(command), listOfNotNull(command, reason).joinToString("\n\n"), payload))
}
"item/fileChange/requestApproval" -> {
val list = changes[params.optString("itemId")] ?: JSONArray()
val files = (0 until list.length()).mapNotNull { list.optJSONObject(it) }
AgentEvent(approval = AgentHost.Approval(
id.toString(), "Edit", files.joinToString(", ") { it.optString("path") }.take(400),
files.joinToString("\n\n") { it.optString("path") + "\n" + patchLines(it.optString("diff"), it.optJSONObject("kind")?.optString("type").orEmpty()) }, payload,
))
}
// Everything else asks for something DroidDeck has no screen for; refusing keeps the turn going.
else -> AgentEvent(reply = listOf(JSONObject(payload)
.put("error", JSONObject().put("code", -32601).put("message", "DroidDeck cannot answer $method")).toString()))
}
}
private fun notification(method: String, params: JSONObject): AgentEvent? {
val item = params.optJSONObject("item")
val id = item?.optString("id").orEmpty()
val entries: List<AgentHost.Entry> = when (method) {
"thread/started" -> return params.optJSONObject("thread")?.optString("id")?.takeIf { it.isNotEmpty() }?.let { AgentEvent(it) }
"turn/started" -> {
turnId = params.optJSONObject("turn")?.optString("id").orEmpty()
input = 0
output = 0
return null
}
"item/agentMessage/delta" -> return AgentEvent(text = params.optString("delta"))
"item/reasoning/summaryTextDelta", "item/reasoning/textDelta" -> return AgentEvent(thinking = params.optString("delta"))
"item/started" -> when (item?.optString("type")) {
"commandExecution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) }
"mcpToolCall" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.opt("arguments")?.let(::pretty).orEmpty()))
"webSearch" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query")))
"fileChange" -> {
val list = item.optJSONArray("changes") ?: JSONArray()
changes[id] = list
fileEntries(id, list)
}
else -> emptyList()
}
"item/completed" -> when (item?.optString("type")) {
"agentMessage" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty()
"reasoning" -> {
val parts = (strings(item.optJSONArray("summary")) + strings(item.optJSONArray("content"))).joinToString("\n\n").trim()
if (parts.isEmpty()) emptyList() else listOf(AgentHost.Entry.Thought(parts))
}
"commandExecution" -> {
val status = item.optString("status")
val exit = if (item.isNull("exitCode")) 0 else item.optInt("exitCode")
val out = item.optString("aggregatedOutput").takeUnless { item.isNull("aggregatedOutput") }.orEmpty()
listOf(AgentHost.Entry.Result(id, if (status == "declined") out.ifEmpty { DENIED } else out, status != "completed" || exit != 0))
}
"mcpToolCall" -> listOf(AgentHost.Entry.Result(id,
item.optJSONObject("result")?.let(::pretty) ?: item.optJSONObject("error")?.optString("message").orEmpty(), item.optString("status") == "failed"))
"webSearch" -> listOf(AgentHost.Entry.Result(id, "", false))
"fileChange" -> {
val list = item.optJSONArray("changes") ?: changes[id] ?: JSONArray()
changes.remove(id)
val failed = item.optString("status") != "completed"
(0 until list.length()).map { AgentHost.Entry.Result("$id#$it", if (failed) item.optString("status") else "", failed) }
}
else -> emptyList()
}
"turn/plan/updated" -> listOf(plan(params.optJSONArray("plan")))
"thread/tokenUsage/updated" -> {
val usage = params.optJSONObject("tokenUsage") ?: return null
val last = usage.optJSONObject("last")
input += last?.optLong("inputTokens") ?: 0
output += last?.optLong("outputTokens") ?: 0
return AgentEvent(
context = last?.optLong("totalTokens")?.takeIf { it > 0 },
window = usage.optLong("modelContextWindow").takeIf { it > 0 },
)
}
"account/rateLimits/updated" -> return rateLimits(params.optJSONObject("rateLimits"))?.let { AgentEvent(limits = it) }
"serverRequest/resolved" -> return AgentEvent(resolved = params.opt("requestId")?.toString())
"turn/completed" -> {
val turn = params.optJSONObject("turn") ?: JSONObject()
val error = when (turn.optString("status")) {
"failed" -> turn.optJSONObject("error")?.optString("message")?.ifEmpty { null } ?: "turn failed"
else -> null
}
return AgentEvent(
entries = listOf(AgentHost.Entry.Finished(error)),
usage = AgentHost.Usage(if (turn.isNull("durationMs")) 0 else turn.optLong("durationMs"), 0.0, input, output),
)
}
else -> emptyList() else -> emptyList()
} }
return if (entries.isEmpty()) null else AgentEvent(entries = entries) "item.updated" -> when (item?.optString("type")) {
} "todo_list" -> listOf(todoEntry(id, item))
else -> emptyList()
private fun plan(steps: JSONArray?): AgentHost.Entry.Used {
val text = (0 until (steps?.length() ?: 0)).mapNotNull { i ->
val step = steps?.optJSONObject(i) ?: return@mapNotNull null
val mark = when (step.optString("status")) { "completed" -> "[x]"; "inProgress" -> "[~]"; else -> "[ ]" }
"$mark ${step.optString("step")}"
}.joinToString("\n")
return AgentHost.Entry.Used("$turnId-todo", "TodoWrite", "", text, output = "")
}
}
/** One Edit per changed file: its path, then the diff as lines led by ' ', '-' or '+'. */
private fun fileEntries(id: String, changes: JSONArray) = (0 until changes.length()).mapNotNull { i ->
val change = changes.optJSONObject(i) ?: return@mapNotNull null
val path = change.optString("path")
AgentHost.Entry.Used("$id#$i", "Edit", path, path + "\n" + patchLines(change.optString("diff"), change.optJSONObject("kind")?.optString("type").orEmpty()))
}
@VisibleForTesting
internal fun rateLimits(snapshot: JSONObject?): List<AgentHost.Limit>? {
snapshot ?: return null
return listOf("primary", "secondary").mapNotNull { key ->
val w = snapshot.optJSONObject(key) ?: return@mapNotNull null
AgentHost.Limit(w.optInt("windowDurationMins"), w.optDouble("usedPercent", 0.0).toInt(), w.optLong("resetsAt"))
}.takeIf { it.isNotEmpty() }
}
private fun strings(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { list?.optString(it)?.takeIf { s -> s.isNotBlank() } }
private fun pretty(value: Any): String = when (value) {
is JSONObject -> value.toString(2)
is JSONArray -> value.toString(2)
JSONObject.NULL -> ""
else -> value.toString()
}
}
/** OpenCode: `opencode acp`, the Agent Client Protocol over stdio, resumed by session id. */
object OpenCode : AgentHarness {
override val id = "opencode"
override val name = "OpenCode"
override val binary = "/root/.opencode/bin/opencode"
override val skills = "root/.config/opencode/skills"
override val instructions = "root/.config/opencode/AGENTS.md"
override val install = "curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path"
private const val AUTH = "root/.local/share/opencode/auth.json"
private const val CONFIG = "root/.config/opencode/opencode.json"
private const val FREE = "root/.config/opencode/.droiddeck-free"
private const val MODELS = "root/.cache/droiddeck/opencode-models"
/** The provider id DroidDeck gives a server the user names, in opencode's config and auth. */
private const val CUSTOM = "droiddeck"
// `opencode models` lists only what the saved keys reach, so the check that runs it keeps the model list current.
override val signedIn = listOf("sh", "-c",
"mkdir -p /${MODELS.substringBeforeLast('/')}; $binary models --verbose > /$MODELS.$$ 2>/dev/null && mv -f /$MODELS.$$ /$MODELS; rm -f /$MODELS.$$; " +
"grep -q '\"type\"' /$AUTH 2>/dev/null || [ -e /$FREE ] || grep -q '\"$CUSTOM\"' /$CONFIG 2>/dev/null")
// Ids are opencode's own (models.dev), so a saved key is what `opencode auth login` would save for that provider.
override val providers = listOf(
AgentHarness.Provider("opencode", "OpenCode Zen", "https://opencode.ai/auth"),
AgentHarness.Provider("ollama-cloud", "Ollama Cloud", "https://ollama.com/settings/keys"),
AgentHarness.Provider("openrouter", "OpenRouter", "https://openrouter.ai/settings/keys"),
AgentHarness.Provider("openai", "OpenAI", "https://platform.openai.com/api-keys"),
AgentHarness.Provider("anthropic", "Anthropic", "https://console.anthropic.com/settings/keys"),
AgentHarness.Provider("google", "Gemini", "https://aistudio.google.com/apikey"),
AgentHarness.Provider(CUSTOM, "Other server", custom = true),
)
override val signIn = listOf("/root/.local/bin/android-open", providers.first().keyPage!!)
override val free = true
override val plans = true
override val efforts = listOf("low", "medium", "high")
override fun keys(rootfs: File): Set<String> {
val auth = runCatching { JSONObject(File(rootfs, AUTH).readText()) }.getOrNull()
val custom = runCatching { JSONObject(File(rootfs, CONFIG).readText()).optJSONObject("provider")?.has(CUSTOM) }.getOrNull() == true
return providers.filter { auth?.has(it.id) == true || (it.custom && custom) }.map { it.id }.toSet()
}
/**
* Saves the key as opencode's own `auth login` would. A custom server also gets a provider in
* opencode's config with the models its `/models` lists, since opencode does not list them itself.
*/
override fun saveKey(rootfs: File, provider: AgentHarness.Provider, key: String, endpoint: String?, get: (String, String?) -> String) {
val token = key.trim().takeIf { it.isNotEmpty() }
// Both files are read before either is written, so one that cannot be read changes nothing.
val authFile = File(rootfs, AUTH)
val auth = readJson(authFile)
if (token != null) auth.put(provider.id, JSONObject().put("type", "api").put("key", token)) else auth.remove(provider.id)
if (!provider.custom) return writeJson(authFile, auth, private = true)
val base = endpoint(endpoint ?: "")
val configFile = File(rootfs, CONFIG)
val before = configFile.takeIf { it.exists() }?.readText()
val config = readJson(configFile)
val models = modelIds(get("$base/models", token))
check(models.isNotEmpty()) { "No models at $base" }
if (!config.has("\$schema")) config.put("\$schema", "https://opencode.ai/config.json")
val all = config.optJSONObject("provider") ?: JSONObject().also { config.put("provider", it) }
all.put(CUSTOM, JSONObject()
.put("npm", "@ai-sdk/openai-compatible")
.put("name", runCatching { java.net.URI(base).host }.getOrNull() ?: provider.name)
.put("options", JSONObject().put("baseURL", base))
.put("models", JSONObject().apply { models.forEach { put(it, JSONObject().put("name", it)) } }))
writeJson(configFile, config)
try {
writeJson(authFile, auth, private = true)
} catch (e: Exception) {
val undone = runCatching {
if (before != null) writeFile(configFile, before) else java.nio.file.Files.deleteIfExists(configFile.toPath())
} }
// First, since the setup row shows two lines of the message. "item.completed" -> when (item?.optString("type")) {
undone.exceptionOrNull()?.let { throw IllegalStateException("The server config could not be put back (${it.message}): ${e.message}", e) } "agent_message" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty()
throw e "reasoning" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Thought(it)) }.orEmpty()
} "command_execution" -> listOf(AgentHost.Entry.Result(id, item.optString("aggregated_output"),
} item.has("exit_code") && !item.isNull("exit_code") && item.optInt("exit_code") != 0))
"mcp_tool_call" -> listOf(AgentHost.Entry.Result(id, item.optJSONObject("result")?.toString(2) ?: item.optJSONObject("error")?.optString("message").orEmpty(),
override fun removeKey(rootfs: File, provider: AgentHarness.Provider) { item.optString("status") == "failed"))
if (File(rootfs, AUTH).exists()) editJson(File(rootfs, AUTH), private = true) { it.remove(provider.id) } "web_search" -> listOf(AgentHost.Entry.Result(id, "", false))
if (provider.custom && File(rootfs, CONFIG).exists()) editJson(File(rootfs, CONFIG)) { it.optJSONObject("provider")?.remove(CUSTOM) } "file_change" -> listOf(
} AgentHost.Entry.Used(id, "Edit", changedFiles(item), changedFiles(item).replace(", ", "\n")),
AgentHost.Entry.Result(id, item.optString("status"), item.optString("status") == "failed"),
/** A server address as typed, made into the OpenAI-compatible base URL opencode calls. */
@VisibleForTesting
internal fun endpoint(typed: String): String {
val url = typed.trim().trimEnd('/').let { if ("://" in it) it else "http://$it" }
require(url.substringAfter("://").isNotEmpty()) { "No server address" }
return if (url.substringAfter("://").contains('/')) url else "$url/v1"
}
@VisibleForTesting
internal fun modelIds(body: String): List<String> {
// The userland can print its own warnings ahead of the response.
val json = body.substring(body.indexOf('{').coerceAtLeast(0), body.lastIndexOf('}') + 1)
val data = runCatching { JSONObject(json).optJSONArray("data") }.getOrNull() ?: return emptyList()
return (0 until data.length()).mapNotNull { data.optJSONObject(it)?.optString("id")?.takeIf { id -> id.isNotEmpty() } }.distinct()
}
// A file that cannot be read holds the user's other providers too, so it is never replaced.
private fun readJson(file: File) = if (file.exists()) JSONObject(file.readText()) else JSONObject()
private fun editJson(file: File, private: Boolean = false, edit: (JSONObject) -> Unit) =
writeJson(file, readJson(file).also(edit), private)
/** Writes beside [file] and moves it into place, so a write that stops partway leaves the old file. */
private fun writeJson(file: File, json: JSONObject, private: Boolean = false) = writeFile(file, json.toString(2) + "\n", private)
private fun writeFile(file: File, text: String, private: Boolean = false) {
file.parentFile?.mkdirs()
val temp = File(file.parentFile, ".${file.name}.tmp")
try {
temp.writeText(text)
if (private) {
temp.setReadable(false, false)
temp.setReadable(true, true)
}
java.nio.file.Files.move(temp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING, java.nio.file.StandardCopyOption.ATOMIC_MOVE)
} finally {
temp.delete()
}
}
override fun useFree(rootfs: File) {
File(rootfs, FREE).apply { parentFile?.mkdirs() }.writeText("Free OpenCode Zen models, chosen in DroidDeck's agent setup.\n")
}
private class Listed(val modified: Long, val models: List<AgentHarness.Model>, val windows: Map<String, Long>)
@Volatile private var listed: Listed? = null
private fun listed(rootfs: File): Listed? {
val file = File(rootfs, MODELS)
val modified = file.lastModified().takeIf { it > 0 } ?: return null
listed?.takeIf { it.modified == modified }?.let { return it }
return runCatching { listModels(file.readText()) }.getOrNull()?.let { (models, windows) -> Listed(modified, models, windows) }?.also { listed = it }
}
override fun models(rootfs: File) = listed(rootfs)?.models.orEmpty()
/** `opencode models --verbose` prints each model's id on a line of its own, then its details as JSON. */
@VisibleForTesting
internal fun listModels(output: String): Pair<List<AgentHarness.Model>, Map<String, Long>> {
val models = mutableListOf<AgentHarness.Model>()
val windows = mutableMapOf<String, Long>()
var id: String? = null
val json = StringBuilder()
for (line in output.lineSequence()) {
val current = id
if (current == null) {
if (MODEL_ID.matches(line)) id = line.trim()
continue
}
json.appendLine(line)
if (line != "}") continue
runCatching { JSONObject(json.toString()) }.getOrNull()?.takeIf { it.optString("status") != "deprecated" }?.let { o ->
val provider = o.optString("providerID")
val label = o.optString("name").ifEmpty { current }
val source = if (provider == "opencode" || provider == CUSTOM) "" else providers.firstOrNull { it.id == provider }?.name ?: provider
models += AgentHarness.Model(current, if (source.isEmpty()) label else "$label · $source")
o.optJSONObject("limit")?.optLong("context")?.takeIf { it > 0 }?.let { windows[current] = it }
}
id = null
json.clear()
}
return models to windows
}
private val MODEL_ID = Regex("""^[\w.-]+/\S+$""")
override val permissions = listOf(
AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint),
AgentHarness.Permission(AgentHarness.EDITS, R.string.agent_permission_edits, R.string.agent_permission_edits_hint),
AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint),
)
/**
* Rules merged over the user's opencode config. OpenCode applies the last rule that matches in key order, so the
* asking modes name each permission rather than "*", which could land after a rule of the user's and override it.
*/
@VisibleForTesting
internal fun rules(permission: String): JSONObject {
val asks = listOf("bash", "webfetch", "websearch", "codesearch")
return when (permission) {
AgentHarness.FULL -> JSONObject().put("*", "allow")
AgentHarness.EDITS -> JSONObject().put("edit", "allow").apply { asks.forEach { put(it, "ask") } }
else -> JSONObject().put("edit", "ask").apply { asks.forEach { put(it, "ask") } }
}
}
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) =
withoutStderr("opencode", listOf("/usr/bin/env", "OPENCODE_PERMISSION=${rules(options.permission)}", binary, "acp"))
/** The conversation's cost so far; DroidDeck takes the turn's share from what its chat has recorded. */
override val sessionCost = true
override fun protocol(): AgentProtocol = Protocol()
/** `opencode acp`: the Agent Client Protocol, JSON-RPC over stdio. */
@VisibleForTesting
internal class Protocol : AgentProtocol {
private enum class Stage { INIT, SESSION, CONFIG, PROMPT, IDLE }
private var next = 1
private var stage = Stage.IDLE
private var pending = -1
private var session: String? = null
private var resume: String? = null
private var cwd = "/root"
/** Requests for the session still to send, each once the one before it has been answered. */
private val queue = ArrayDeque<(String) -> JSONObject>()
private val said = StringBuilder()
private val thought = StringBuilder()
/** Each tool call's name, which only its first update carries, and its latest entry. */
private val names = mutableMapOf<String, String>()
private val used = mutableMapOf<String, AgentHost.Entry.Used>()
private var cost = 0.0
private var started = 0L
override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List<String> {
val text = if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message
val prompt = { id: String ->
JSONObject().put("sessionId", id).put("prompt", JSONArray().put(JSONObject().put("type", "text").put("text", text)))
}
queue.clear()
val known = session
if (!started && known != null && configured) return listOf(send(Stage.PROMPT, "session/prompt", prompt(known)))
fun option(config: String, value: String) = { id: String -> JSONObject().put("sessionId", id).put("configId", config).put("value", value) }
options.model?.let { queue += option("model", it) }
options.effort?.let { queue += option("effort", it) }
queue += option("mode", if (options.plan) "plan" else "build")
queue += prompt
// A session whose options were refused sets them all again before its next prompt.
if (!started && known != null) return listOf(advance(known))
resume = conversation
cwd = options.workdir
return listOf(send(Stage.INIT, "initialize", JSONObject().put("protocolVersion", 1).put("clientCapabilities", JSONObject())))
}
private fun send(stage: Stage, method: String, params: JSONObject): String {
this.stage = stage
pending = next++
if (stage == Stage.PROMPT) started = System.currentTimeMillis()
return JSONObject().put("jsonrpc", "2.0").put("id", pending).put("method", method).put("params", params).toString()
}
/** The next queued request: the prompt once nothing else is left. */
private fun advance(id: String): String {
val make = queue.removeFirst()
val params = make(id)
configuring = params.optString("configId")
configured = queue.isEmpty()
return if (queue.isEmpty()) send(Stage.PROMPT, "session/prompt", params) else send(Stage.CONFIG, "session/set_config_option", params)
}
/** The config option the pending set_config_option sets. */
private var configuring = ""
/** The session's model, effort and mode were all set, so a later prompt can go straight to it. */
private var configured = false
override fun answer(approval: AgentHost.Approval, allow: Boolean): String = JSONObject(approval.payload).put("jsonrpc", "2.0")
.put("result", JSONObject().put("outcome", JSONObject().put("outcome", "selected").put("optionId", if (allow) "once" else "reject"))).toString()
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val method = o.optString("method")
val params = o.optJSONObject("params") ?: JSONObject()
return when {
method.isEmpty() -> response(o)
o.has("id") -> request(o.get("id"), method, params)
method == "session/update" -> update(params.optJSONObject("update") ?: return null)
else -> null
}
}
private fun response(o: JSONObject): AgentEvent? {
if (o.optInt("id", -1) != pending) return null
val error = o.optJSONObject("error")?.let { it.optJSONObject("data")?.optString("message")?.ifEmpty { null } ?: it.optString("message").ifEmpty { "error" } }
val result = o.optJSONObject("result") ?: JSONObject()
return when (stage) {
Stage.INIT -> error?.let(::failed) ?: AgentEvent(reply = listOf(
resume?.let { send(Stage.SESSION, "session/resume", JSONObject().put("sessionId", it).put("cwd", cwd).put("mcpServers", JSONArray())) }
?: send(Stage.SESSION, "session/new", JSONObject().put("cwd", cwd).put("mcpServers", JSONArray())),
))
Stage.SESSION -> {
if (error != null) return failed(error)
val id = result.optString("sessionId").ifEmpty { resume.orEmpty() }.takeIf { it.isNotEmpty() } ?: return failed("no session")
session = id
AgentEvent(id, reply = listOf(advance(id)))
}
// A model without effort levels refuses one and the turn goes on with its default; a refused
// mode would run a plan turn as a build one, so it ends the turn instead.
Stage.CONFIG -> if (error != null && configuring == "mode") failed(error) else AgentEvent(reply = listOf(advance(session ?: return null)))
Stage.PROMPT -> {
stage = Stage.IDLE
val usage = result.optJSONObject("usage")
val reason = result.optString("stopReason")
AgentEvent(
session,
flush() + AgentHost.Entry.Finished(error ?: if (reason == "refusal") "refused" else null),
usage = AgentHost.Usage(
System.currentTimeMillis() - started, cost,
(usage?.optLong("inputTokens") ?: 0) + (usage?.optLong("cachedReadTokens") ?: 0),
(usage?.optLong("outputTokens") ?: 0) + (usage?.optLong("thoughtTokens") ?: 0),
),
)
}
Stage.IDLE -> null
}
}
private fun failed(error: String): AgentEvent {
stage = Stage.IDLE
configured = false
return AgentEvent(session, flush() + AgentHost.Entry.Finished(error))
}
private fun request(id: Any, method: String, params: JSONObject): AgentEvent {
val payload = JSONObject().put("id", id).toString()
if (method != "session/request_permission") {
// File writes and terminals stay with OpenCode, which does them itself when the client declines.
return AgentEvent(reply = listOf(JSONObject(payload).put("jsonrpc", "2.0")
.put("error", JSONObject().put("code", -32601).put("message", "DroidDeck cannot answer $method")).toString()))
}
val call = params.optJSONObject("toolCall") ?: JSONObject()
val raw = call.optJSONObject("rawInput") ?: JSONObject()
val name = names[call.optString("toolCallId")] ?: call.optString("kind")
val kind = call.optString("kind")
val approval = when {
kind == "execute" -> AgentHost.Approval(id.toString(), "Bash", firstLine(raw.optString("command")), raw.optString("command"), payload)
// OpenCode asks for a folder outside the workspace on its own, before the tool's own ask.
raw.has("parentDir") -> AgentHost.Approval(
id.toString(), "External directory", raw.optString("parentDir"),
listOf(raw.optString("parentDir"), raw.optString("command")).filter { it.isNotEmpty() }.joinToString("\n\n"), payload,
) )
raw.has("diff") -> { "todo_list" -> listOf(todoEntry(id, item))
val path = raw.optString("filepath") "error" -> listOf(AgentHost.Entry.Said("⚠ " + item.optString("message")))
AgentHost.Approval(id.toString(), "Edit", path, path + "\n" + patchLines(raw.optString("diff"), ""), payload) else -> emptyList()
}
else -> AgentHost.Approval(id.toString(), toolName(name), call.optString("title"), raw.toString(2), payload)
} }
return AgentEvent(session, flush(), approval = approval) "turn.completed" -> return AgentEvent(
} entries = listOf(AgentHost.Entry.Finished(null)),
usage = o.optJSONObject("usage")?.let { AgentHost.Usage(0, 0.0, it.optLong("input_tokens") + it.optLong("cached_input_tokens"), it.optLong("output_tokens")) },
private fun update(u: JSONObject): AgentEvent? = when (u.optString("sessionUpdate")) { )
"agent_message_chunk" -> chunk(u)?.let { said.append(it); AgentEvent(session, text = it) } "turn.failed" -> listOf(AgentHost.Entry.Finished(o.optJSONObject("error")?.optString("message") ?: "turn failed"))
"agent_thought_chunk" -> chunk(u)?.let { thought.append(it); AgentEvent(session, thinking = it) } // codex reports a dropped stream it is retrying as an error event, and the turn goes on.
"tool_call", "tool_call_update" -> AgentEvent(session, flush() + tool(u)) "error" -> o.optString("message").let { message ->
"usage_update" -> { if (message.startsWith("Reconnecting...")) emptyList() else listOf(AgentHost.Entry.Finished(message.ifEmpty { "error" }))
u.optJSONObject("cost")?.optDouble("amount")?.takeIf { !it.isNaN() }?.let { cost = it }
AgentEvent(session, context = u.optLong("used").takeIf { it > 0 }, window = u.optLong("size").takeIf { it > 0 })
} }
else -> null else -> emptyList()
}
private fun chunk(u: JSONObject) = u.optJSONObject("content")?.takeIf { it.optString("type") == "text" }?.optString("text")?.takeIf { it.isNotEmpty() }
/** What was written since the last entry, as whole entries. */
private fun flush(): List<AgentHost.Entry> = buildList {
thought.toString().trim().takeIf { it.isNotEmpty() }?.let { add(AgentHost.Entry.Thought(it)) }
said.toString().trim().takeIf { it.isNotEmpty() }?.let { add(AgentHost.Entry.Said(it)) }
thought.clear()
said.clear()
}
private fun tool(u: JSONObject): List<AgentHost.Entry> {
val id = u.optString("toolCallId")
if (u.optString("sessionUpdate") == "tool_call") names[id] = u.optString("title")
val input = u.optJSONObject("rawInput")?.takeIf { it.length() > 0 }
val entry = if (input != null || used[id] == null) tool(id, names[id].orEmpty(), input ?: JSONObject()) else used.getValue(id)
used[id] = entry
val raw = u.optJSONObject("rawOutput")
return when (u.optString("status")) {
"completed" -> {
val exit = raw?.optJSONObject("metadata")?.opt("exit")
listOf(entry, AgentHost.Entry.Result(id, raw?.optString("output")?.ifEmpty { null } ?: content(u), exit is Number && exit.toInt() != 0))
}
"failed" -> listOf(entry, AgentHost.Entry.Result(id, raw?.optString("error")?.ifEmpty { null } ?: content(u), true))
else -> listOf(entry)
}
}
private fun content(u: JSONObject): String {
val list = u.optJSONArray("content") ?: return ""
return (0 until list.length()).mapNotNull { list.optJSONObject(it)?.optJSONObject("content")?.optString("text") }.joinToString("\n")
} }
return if (entries.isEmpty()) null else AgentEvent(entries = entries)
} }
private fun toolName(name: String) = name.replaceFirstChar { it.uppercase() }.ifEmpty { "Tool" } private const val TOKEN_COUNT = "\"payload\":{\"type\":\"token_count\""
private fun tool(id: String, name: String, input: JSONObject): AgentHost.Entry.Used { /** Codex prints no limits with --json; its session log, named after the thread, has a token_count event each step. */
val path = input.optString("filePath") override fun usage(rootfs: File, conversation: String?): AgentEvent? {
return when (name) { conversation ?: return null
"bash" -> AgentHost.Entry.Used(id, "Bash", firstLine(input.optString("command")), input.optString("command")) val log = File(rootfs, "root/.codex/sessions").walkBottomUp().filter { it.isFile && it.name.endsWith("-$conversation.jsonl") }
"edit" -> AgentHost.Entry.Used(id, "Edit", path, path + "\n" + lineDiff(input.optString("oldString"), input.optString("newString"))) .maxByOrNull { it.lastModified() } ?: return null
"write" -> AgentHost.Entry.Used(id, "Write", path, path + "\n" + lineDiff("", input.optString("content"))) val last = runCatching { log.readLines().lastOrNull { it.contains(TOKEN_COUNT) } }.getOrNull() ?: return null
"todowrite" -> AgentHost.Entry.Used(id, "TodoWrite", "", todos(input.optJSONArray("todos"))) return tokenCount(last)
else -> AgentHost.Entry.Used(id, toolName(name), detail(input), if (input.length() == 0) "" else input.toString(2))
}
} }
private fun detail(input: JSONObject): String { @VisibleForTesting
for (key in listOf("filePath", "path", "pattern", "url", "query", "description", "prompt", "command")) { internal fun tokenCount(line: String): AgentEvent? {
input.optString(key).takeIf { it.isNotEmpty() }?.let { return firstLine(it) } val payload = runCatching { JSONObject(line).optJSONObject("payload") }.getOrNull()?.takeIf { it.optString("type") == "token_count" } ?: return null
val info = payload.optJSONObject("info")
val rates = payload.optJSONObject("rate_limits")
val limits = listOf("primary", "secondary").mapNotNull { key ->
val w = rates?.optJSONObject(key) ?: return@mapNotNull null
AgentHost.Limit(w.optInt("window_minutes"), w.optDouble("used_percent", 0.0).toInt(), w.optLong("resets_at"))
} }
return "" return AgentEvent(
context = info?.optJSONObject("last_token_usage")?.optLong("total_tokens")?.takeIf { it > 0 },
window = info?.optLong("model_context_window")?.takeIf { it > 0 },
limits = limits.takeIf { it.isNotEmpty() },
)
} }
private fun todos(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { i -> private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used {
val todo = list?.optJSONObject(i) ?: return@mapNotNull null val items = item.optJSONArray("items") ?: JSONArray()
val mark = when (todo.optString("status")) { "completed" -> "[x]"; "in_progress" -> "[~]"; else -> "[ ]" } val text = (0 until items.length()).mapNotNull { i ->
"$mark ${todo.optString("content")}" val todo = items.optJSONObject(i) ?: return@mapNotNull null
}.joinToString("\n") "${if (todo.optBoolean("completed")) "[x]" else "[ ]"} ${todo.optString("text")}"
}.joinToString("\n")
return AgentHost.Entry.Used("$id-todo", "TodoWrite", "", text, output = "")
}
private fun changedFiles(item: JSONObject): String {
val changes = item.optJSONArray("changes") ?: return ""
return (0 until changes.length()).mapNotNull { changes.optJSONObject(it)?.optString("path") }.joinToString(", ").take(400)
}
} }
@VisibleForTesting @VisibleForTesting
internal fun firstLine(text: String) = text.lineSequence().first().take(160) internal fun firstLine(text: String) = text.lineSequence().first().take(160)
/**
* [command] with its stderr in a log of its own under /root/.cache/droiddeck. The agent's stdout and stderr share one
* pipe, and a log line written in the middle of a long JSON line would make that line unreadable.
*/
internal fun withoutStderr(log: String, command: List<String>) =
listOf("/bin/sh", "-c", "mkdir -p /root/.cache/droiddeck; exec \"\$@\" 2>/root/.cache/droiddeck/$log.log", "sh") + command
private const val DIFF_CONTEXT = 2 private const val DIFF_CONTEXT = 2
/** /**
@@ -1060,18 +417,6 @@ internal fun lineDiff(old: String, new: String): String {
}.joinToString("\n") }.joinToString("\n")
} }
/** A unified diff's hunks without their headers; an added or deleted file's diff is its whole content. */
@VisibleForTesting
internal fun patchLines(diff: String, kind: String): String {
val lines = diff.removeSuffix("\n").lines()
when (kind) {
"add" -> return lines.joinToString("\n") { "+$it" }
"delete" -> return lines.joinToString("\n") { "-$it" }
}
val start = lines.indexOfFirst { it.startsWith("@@") }
return (if (start < 0) lines else lines.drop(start)).filter { it.isNotEmpty() && !it.startsWith("@@") && !it.startsWith("\\") }.joinToString("\n")
}
private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL) private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL)
/** Codex runs each command as `/bin/bash -lc '<command>'`; the command is what the user wants to read. */ /** Codex runs each command as `/bin/bash -lc '<command>'`; the command is what the user wants to read. */
@@ -21,8 +21,8 @@ import java.nio.file.Files
/** /**
* The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless * The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless
* outside any game or desktop session as one process that takes its messages over stdin and stays open * outside any game or desktop session: one process per turn, or for a CLI that takes its messages over
* between turns, so background work can start a turn of its own. Conversations are kept on disk * stdin one process kept open between turns, so background work can start a turn of its own. Conversations are kept on disk
* ([AgentChats]), so a restart (a Lab build, a crash) continues the same one. * ([AgentChats]), so a restart (a Lab build, a crash) continues the same one.
*/ */
object AgentHost { object AgentHost {
@@ -56,9 +56,6 @@ object AgentHost {
/** A message typed while the agent was working, sent when the turn ends. */ /** A message typed while the agent was working, sent when the turn ends. */
data class Queued(val text: String, val files: List<String>) data class Queued(val text: String, val files: List<String>)
/** A tool call the CLI waits on the user to allow; [payload] is what its protocol needs to answer. */
data class Approval(val id: String, val tool: String, val detail: String, val input: String, val payload: String = "")
enum class State { MISSING, IDLE, WORKING } enum class State { MISSING, IDLE, WORKING }
private const val TAG = "AgentHost" private const val TAG = "AgentHost"
@@ -97,12 +94,6 @@ object AgentHost {
private set private set
var plan by mutableStateOf(false) var plan by mutableStateOf(false)
private set private set
/** The chosen [AgentHarness.Permission] of [harness]; asking first until the user picks another. */
var permission by mutableStateOf(AgentHarness.ASK)
private set
/** Tool calls of the running turn that wait for the user, oldest first. */
val approvals = mutableStateListOf<Approval>()
private var approvalNoticed = false
var chat by mutableStateOf<String?>(null) var chat by mutableStateOf<String?>(null)
private set private set
/** A reply finished since the conversation was last on screen. */ /** A reply finished since the conversation was last on screen. */
@@ -132,9 +123,7 @@ object AgentHost {
var lab by mutableStateOf<LabProgress?>(null) var lab by mutableStateOf<LabProgress?>(null)
private set private set
private class Turn(val process: Process, val pid: Int, val protocol: AgentProtocol, val stdin: java.io.OutputStream) { private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) {
fun write(lines: List<String>) = synchronized(this) { stdin.apply { lines.forEach { write((it + "\n").toByteArray()) }; flush() } }
var writingGeneration: Int? = null var writingGeneration: Int? = null
var exitStatus: Int? = null var exitStatus: Int? = null
var costs: AgentCostTracker? = null var costs: AgentCostTracker? = null
@@ -182,8 +171,6 @@ object AgentHost {
model = prefs(app).getString(modelKey(harness), null) model = prefs(app).getString(modelKey(harness), null)
effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts } effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts }
plan = prefs(app).getBoolean(PLAN_KEY, false) plan = prefs(app).getBoolean(PLAN_KEY, false)
permission = prefs(app).getString(permissionKey(harness), null)?.takeIf { id -> harness.permissions.any { it.id == id } }
?: harness.permissions.first().id
limits = decodeLimits(prefs(app).getString(limitsKey(harness), null)) limits = decodeLimits(prefs(app).getString(limitsKey(harness), null))
available = LinuxRuntime.hasRootfs(app) available = LinuxRuntime.hasRootfs(app)
installed = harness.files.all { guestFileExists(app, it) } installed = harness.files.all { guestFileExists(app, it) }
@@ -286,42 +273,6 @@ object AgentHost {
prefs(context).edit().putBoolean(PLAN_KEY, on).apply() prefs(context).edit().putBoolean(PLAN_KEY, on).apply()
} }
/** Kept per CLI, for every conversation; the CLI process restarts with it on the next message. */
fun choosePermission(context: Context, id: String) {
if (harness.permissions.none { it.id == id }) return
permission = id
prefs(context).edit().putString(permissionKey(harness), id).apply()
}
/** Lets the CLI run [approval]'s tool call, or tells it the user said no. */
fun answer(context: Context, approval: Approval, allow: Boolean) {
if (!approvals.remove(approval)) return
val running = turn ?: session ?: return
val line = running.protocol.answer(approval, allow)
val app = context.applicationContext
val current = harness
Thread({ runCatching { running.write(listOf(line)) }.onFailure { lost(app, running, current, it) } }, "agent-approval").start()
approvalsChanged(app)
}
/** The approval notice goes once nothing waits on the user any more. */
private fun approvalsChanged(app: Context) {
if (approvals.isNotEmpty() || !approvalNoticed) return
approvalNoticed = false
AgentNotice.clear(app)
}
/**
* A line the CLI waits for could not be written, so it would wait forever: its process ends, which ends
* the turn, and the chat says why. A request that may have reached it is not sent again.
*/
private fun lost(app: Context, from: Turn, current: AgentHarness, error: Throwable) {
Log.w(TAG, "could not write to ${current.name}", error)
main.post { if (turn === from || session === from) record(app, Entry.Notice("Could not write to ${current.name}: ${error.message ?: error.javaClass.simpleName}")) }
AgentProcesses.killTree(from.pid)
from.process.destroy()
}
fun models(context: Context) = harness.models(LinuxRuntime.rootDir(context.applicationContext)) fun models(context: Context) = harness.models(LinuxRuntime.rootDir(context.applicationContext))
/** Sends [text] now, or after the current turn when the agent is working. */ /** Sends [text] now, or after the current turn when the agent is working. */
@@ -352,20 +303,19 @@ object AgentHost {
val current = harness val current = harness
val prompt = AgentAttachments.prompt(message, attached) val prompt = AgentAttachments.prompt(message, attached)
turnPlanned = plan && current.plans turnPlanned = plan && current.plans
val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort, permission, workspace(app)) val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort)
val key = "${current.id}|$id|$model|$turnPlanned|$effort|$permission" val command = current.turn(prompt, conversation, options)
val resumed = conversation val line = current.input(prompt)
val key = "${current.id}|$id|$model|$turnPlanned|$effort"
background = false background = false
approvals.clear()
approvalsChanged(app)
val kept = session val kept = session
if (kept != null && sessionKey == key && kept.process.isAlive) { if (kept != null && line != null && sessionKey == key && kept.process.isAlive) {
main.removeCallbacks(reap) main.removeCallbacks(reap)
turn = kept turn = kept
kept.writingGeneration = gen kept.writingGeneration = gen
kept.clearingCosts = prompt == "/clear" kept.clearingCosts = prompt == "/clear"
Thread({ Thread({
val written = runCatching { kept.write(kept.protocol.input(prompt, resumed, options, started = false)) }.isSuccess val written = runCatching { synchronized(kept) { kept.stdin?.apply { write((line + "\n").toByteArray()); flush() } != null } }.getOrDefault(false)
// The process died between turns: the same message goes to a new one, which resumes the conversation. // The process died between turns: the same message goes to a new one, which resumes the conversation.
main.post { main.post {
if (kept.writingGeneration == gen) kept.writingGeneration = null if (kept.writingGeneration == gen) kept.writingGeneration = null
@@ -373,7 +323,7 @@ object AgentHost {
if (!written) { if (!written) {
dropSession() dropSession()
turn = null turn = null
spawn(app, gen, current, prompt, resumed, options, key) spawn(app, gen, current, current.turn(prompt, conversation, options), line, key)
} else kept.exitStatus?.let { processExited(app, kept, current, it) } } else kept.exitStatus?.let { processExited(app, kept, current, it) }
} }
} }
@@ -381,14 +331,12 @@ object AgentHost {
return return
} }
dropSession() dropSession()
spawn(app, gen, current, prompt, resumed, options, key) spawn(app, gen, current, command, line, key)
} }
private fun spawn(app: Context, gen: Int, current: AgentHarness, prompt: String, resumed: String?, options: AgentHarness.Options, key: String) { private fun spawn(app: Context, gen: Int, current: AgentHarness, command: List<String>, line: String?, key: String) {
val workdir = options.workdir val workdir = workspace(app)
val command = current.turn(prompt, resumed, options) var threadConversation = conversation
val protocol = current.protocol()
var threadConversation = resumed
Thread({ Thread({
runCatching { current.prepare(LinuxRuntime.rootDir(app)) } runCatching { current.prepare(LinuxRuntime.rootDir(app)) }
runCatching { AgentSetup.installHelpers(app) } runCatching { AgentSetup.installHelpers(app) }
@@ -401,18 +349,17 @@ object AgentHost {
main.post { if (generation == gen) finish(app, e.message ?: "could not start") } main.post { if (generation == gen) finish(app, e.message ?: "could not start") }
return@Thread return@Thread
} }
val started = Turn(child, AgentProcesses.pidOf(child), protocol, child.outputStream).apply { val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null).apply {
if (current === ClaudeCode) costs = AgentCostTracker() if (current === ClaudeCode && line != null) costs = AgentCostTracker()
} }
OrphanReaper.keep(started.pid) OrphanReaper.keep(started.pid)
main.post { main.post {
if (generation == gen && state == State.WORKING && turn == null) { if (generation == gen && state == State.WORKING && turn == null) {
turn = started turn = started
session = started if (line != null) { session = started; sessionKey = key }
sessionKey = key
} else AgentProcesses.killTree(started.pid) } else AgentProcesses.killTree(started.pid)
} }
runCatching { started.write(protocol.input(prompt, resumed, options, started = true)) }.onFailure { lost(app, started, current, it) } if (line != null) runCatching { child.outputStream.apply { write((line + "\n").toByteArray()); flush() } } else child.outputStream.close()
val raw = runCatching { val raw = runCatching {
val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() } val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() }
log.renameTo(File(app.filesDir, "$TURN_LOG.1")) log.renameTo(File(app.filesDir, "$TURN_LOG.1"))
@@ -421,8 +368,7 @@ object AgentHost {
runCatching { runCatching {
child.inputStream.bufferedReader().forEachLine { output -> child.inputStream.bufferedReader().forEachLine { output ->
runCatching { raw?.apply { write(output); newLine(); flush() } } runCatching { raw?.apply { write(output); newLine(); flush() } }
val parsed = protocol.parse(output) ?: return@forEachLine val parsed = current.parse(output) ?: return@forEachLine
if (parsed.reply.isNotEmpty()) runCatching { started.write(parsed.reply) }.onFailure { lost(app, started, current, it) }
parsed.conversation?.let { threadConversation = it } parsed.conversation?.let { threadConversation = it }
val done = parsed.entries.any { it is Entry.Finished } val done = parsed.entries.any { it is Entry.Finished }
val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull() val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull()
@@ -464,7 +410,7 @@ object AgentHost {
if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it }) if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it })
return return
} }
val content = event.text != null || event.thinking != null || event.approval != null || event.entries.any { it !is Entry.Finished } val content = event.text != null || event.thinking != null || event.entries.any { it !is Entry.Finished }
if (content && state == State.IDLE && session === from) { if (content && state == State.IDLE && session === from) {
main.removeCallbacks(reap) main.removeCallbacks(reap)
background = true background = true
@@ -482,17 +428,10 @@ object AgentHost {
from.clearingCosts = false from.clearingCosts = false
} }
val applied = if (finished != null && state == State.WORKING && event.usage != null) val applied = if (finished != null && state == State.WORKING && event.usage != null)
event.copy(usage = turnCost(from.costs?.perTurn(event.usage) ?: event.usage)) else event event.copy(usage = from.costs?.perTurn(event.usage) ?: event.usage) else event
apply(app, applied) apply(app, applied)
} }
/** A CLI that reports the conversation's whole cost spent what this chat has not recorded yet. */
private fun turnCost(usage: Usage): Usage {
if (!harness.sessionCost) return usage
val recorded = entries.sumOf { (it as? Entry.Finished)?.usage?.costUsd ?: 0.0 }
return usage.copy(costUsd = (usage.costUsd - recorded).coerceAtLeast(0.0))
}
/** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */ /** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */
private fun dropSession() { private fun dropSession() {
main.removeCallbacks(reap) main.removeCallbacks(reap)
@@ -590,15 +529,6 @@ object AgentHost {
} }
event.text?.let { live += it } event.text?.let { live += it }
event.thinking?.let { liveThinking += it } event.thinking?.let { liveThinking += it }
event.resolved?.let { id ->
approvals.removeAll { it.id == id }
approvalsChanged(app)
}
event.approval?.takeIf { a -> state == State.WORKING && approvals.none { it.id == a.id } }?.let {
approvals += it
approvalNoticed = true
AgentNotice.post(app, AgentNotice.Kind.APPROVAL, listOf(it.tool, it.detail).filter { s -> s.isNotEmpty() }.joinToString(": "))
}
event.context?.let { context = it } event.context?.let { context = it }
event.window?.let { window = it } event.window?.let { window = it }
event.limits?.let { reported -> event.limits?.let { reported ->
@@ -619,8 +549,6 @@ object AgentHost {
private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) { private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) {
if (state != State.WORKING) return if (state != State.WORKING) return
turn = null turn = null
approvals.clear()
approvalsChanged(app)
val answeredTask = background val answeredTask = background
background = false background = false
main.removeCallbacks(reap) main.removeCallbacks(reap)
@@ -834,7 +762,6 @@ object AgentHost {
private const val LINGER_MS = 20 * 60_000L private const val LINGER_MS = 20 * 60_000L
private fun modelKey(harness: AgentHarness) = "model_${harness.id}" private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
private fun permissionKey(harness: AgentHarness) = "permission_${harness.id}"
private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}" private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}"
@VisibleForTesting @VisibleForTesting
@@ -16,10 +16,10 @@ internal object AgentNotice {
private const val CHANNEL_ID = "agent_done" private const val CHANNEL_ID = "agent_done"
private const val NOTIFICATION_ID = 4108 private const val NOTIFICATION_ID = 4108
enum class Kind { DONE, FAILED, QUESTION, APPROVAL } enum class Kind { DONE, FAILED, QUESTION }
fun post(context: Context, kind: Kind, text: String) { fun post(context: Context, kind: Kind, text: String) {
if (onScreen(context, kind)) return if (onScreen(context)) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return val manager = context.getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT)) manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT))
val open = PendingIntent.getActivity(context, 2, val open = PendingIntent.getActivity(context, 2,
@@ -31,7 +31,6 @@ internal object AgentNotice {
Kind.DONE -> R.string.agent_done Kind.DONE -> R.string.agent_done
Kind.FAILED -> R.string.agent_done_failed Kind.FAILED -> R.string.agent_done_failed
Kind.QUESTION -> R.string.agent_done_question Kind.QUESTION -> R.string.agent_done_question
Kind.APPROVAL -> R.string.agent_done_approval
}) })
runCatching { runCatching {
manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID) manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID)
@@ -50,9 +49,9 @@ internal object AgentNotice {
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID) context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
} }
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble but has no way to answer an approval. */ /** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */
private fun onScreen(context: Context, kind: Kind): Boolean { private fun onScreen(context: Context): Boolean {
if (AgentPet.floating && kind != Kind.APPROVAL) return true if (AgentPet.floating) return true
val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) } val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) }
return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
} }
@@ -27,55 +27,6 @@ object AgentSetup {
val detail = mutableStateMapOf<Step, String>() val detail = mutableStateMapOf<Step, String>()
var runtimeInstalled by mutableStateOf(true) var runtimeInstalled by mutableStateOf(true)
private set private set
/** Ids of the harness's [AgentHarness.providers] with a key saved; signed in without one means its free models. */
var keys by mutableStateOf(emptySet<String>())
private set
/** The provider and custom server picked in the key field, kept while a save is checked. */
var provider by mutableStateOf<String?>(null)
var server by mutableStateOf("")
/** Saves a pasted key for a harness that signs in with one, then checks the sign-in again. */
fun saveKey(context: Context, provider: AgentHarness.Provider, key: String, endpoint: String? = null) = signInLocally(context) { harness, root ->
harness.saveKey(root, provider, key, endpoint) { url, token -> fetch(context.applicationContext, url, token) }
}
fun removeKey(context: Context, provider: AgentHarness.Provider) = signInLocally(context) { harness, root -> harness.removeKey(root, provider) }
/** A GET from the userland, which reaches the LAN servers the app's own cleartext policy does not. */
private fun fetch(app: Context, url: String, token: String?): String {
// The key goes in on stdin, so it is never in a command line.
val process = AgentHost.guest(app, listOf("curl", "-fsSL", "--max-time", "20", "-H", "@-", url), connectAdb = false).start()
process.outputStream.bufferedWriter().use { if (token != null) it.write("Authorization: Bearer $token\n") }
val output = process.inputStream.bufferedReader().readText()
check(process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() == 0) { output.trim().lines().lastOrNull()?.takeIf { it.isNotEmpty() } ?: "Cannot reach $url" }
return output
}
fun useFree(context: Context) = signInLocally(context) { harness, root -> harness.useFree(root) }
private val signInLock = Any()
private fun signInLocally(context: Context, write: (AgentHarness, File) -> Unit) {
val app = context.applicationContext
val harness = AgentHost.harness
set(Step.SIGN_IN, Status.WORKING)
Thread({
// Each write reads the files the one before it left, including across a save's model request.
val result = synchronized(signInLock) { runCatching { write(harness, LinuxRuntime.rootDir(app)) } }
main.post {
// A failure stays on the row with the key field open, since the next check would clear it.
val error = result.exceptionOrNull()
if (error != null) {
status[Step.SIGN_IN] = Status.FAILED
detail[Step.SIGN_IN] = error.message ?: "failed"
} else {
status[Step.SIGN_IN] = Status.UNKNOWN
detail.remove(Step.SIGN_IN)
check(app)
}
}
}, "agent-sign-in").start()
}
val ready: Boolean get() = Step.entries.filter { it.required }.all { status[it] == Status.DONE } val ready: Boolean get() = Step.entries.filter { it.required }.all { status[it] == Status.DONE }
@@ -102,7 +53,6 @@ object AgentSetup {
if (!runtimeInstalled) return if (!runtimeInstalled) return
AgentHost.refresh(app) AgentHost.refresh(app)
val harness = AgentHost.harness val harness = AgentHost.harness
keys = harness.keys(LinuxRuntime.rootDir(app))
val probes = mutableListOf<Pair<Step, List<String>>>() val probes = mutableListOf<Pair<Step, List<String>>>()
for (step in Step.entries) if (status[step] != Status.WORKING) { for (step in Step.entries) if (status[step] != Status.WORKING) {
when (step) { when (step) {
@@ -129,23 +79,15 @@ object AgentSetup {
fun runsAsRoot(step: Step) = step == Step.INSTALL fun runsAsRoot(step: Step) = step == Step.INSTALL
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */ /** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
fun run(context: Context, step: Step) = run(context, step, null) fun run(context: Context, step: Step) {
/** Opens the page where a provider's key is made, as the sign-in of a harness that takes pasted keys. */
fun openKeyPage(context: Context, page: String) = run(context, Step.SIGN_IN, listOf("/root/.local/bin/android-open", page))
private fun run(context: Context, step: Step, override: List<String>?) {
val app = context.applicationContext val app = context.applicationContext
val harness = AgentHost.harness val harness = AgentHost.harness
val command = override ?: when (step) { val command = when (step) {
Step.CONNECTION -> return Step.CONNECTION -> return
Step.INSTALL -> { Step.INSTALL -> {
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 \"\$@\"; }; " + "dpkg --configure -a; apt-get update || echo 'Some package sources could not be refreshed; continuing'; apt-get -f install -y; " +
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " + "apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
"for i in 1 2 3; do apt update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
"apt -f install -y --fix-missing; " +
"apt install -y --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,14 +16,13 @@ import java.nio.file.attribute.BasicFileAttributes
/** /**
* What the agent adds to the Linux userland, measured and removable piece by piece. Sign-ins * What the agent adds to the Linux userland, measured and removable piece by piece. Sign-ins
* (~/.claude, ~/.codex, ~/.local/share/opencode, gh's config) are left alone, so removing a CLI * (~/.claude, ~/.codex, gh's config) are left alone, so removing a CLI and installing it again
* and installing it again does not sign out. * does not sign out.
*/ */
object AgentStorage { object AgentStorage {
enum class Item(val paths: List<String>) { enum class Item(val paths: List<String>) {
CLAUDE_CODE(listOf("/root/.local/share/claude", "/root/.local/bin/claude", "/root/cc")), CLAUDE_CODE(listOf("/root/.local/share/claude", "/root/.local/bin/claude", "/root/cc")),
CODEX(listOf("/root/.local/bin/codex", "/root/.local/bin/codex-code-mode-host")), CODEX(listOf("/root/.local/bin/codex", "/root/.local/bin/codex-code-mode-host")),
OPENCODE(listOf("/root/.opencode")),
BUILD_TOOLS(listOf("/root/android-sdk", "/root/aapt2", "/root/x86root", "/root/.gradle")), BUILD_TOOLS(listOf("/root/android-sdk", "/root/aapt2", "/root/x86root", "/root/.gradle")),
SOURCE(listOf("/root/DroidDeck")), SOURCE(listOf("/root/DroidDeck")),
CACHES(listOf("/root/.cache", "/root/.npm")), CACHES(listOf("/root/.cache", "/root/.npm")),
@@ -1,91 +0,0 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.frontend.LibraryCache
import com.droiddeck.launcher.stores.CloudSaves
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.xbox.Xodus
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.concurrent.TimeUnit
import org.json.JSONArray
import org.json.JSONObject
internal object AgentStores {
private const val OUTPUT_CAP = 160 * 1024
fun library(context: Context, request: JSONObject): JSONObject {
val query = request.optString("query").trim()
val source = request.optString("source").trim()
val games = JSONArray()
LibraryCache.load(context)
.filter { (query.isEmpty() || it.name.contains(query, ignoreCase = true)) && (source.isEmpty() || it.source.equals(source, ignoreCase = true)) }
.forEach {
games.put(JSONObject().put("id", it.gameIdString).put("name", it.name).put("source", it.source)
.put("storeId", it.storeId ?: JSONObject.NULL).put("folder", it.gameFiles?.path ?: JSONObject.NULL))
}
return JSONObject().put("ok", true).put("command", "library").put("games", games)
}
fun xodus(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val list = request.optJSONArray("args")
val args = if (list == null) emptyList() else List(list.length()) { list.optString(it) }
if (args.isEmpty() || args.any { it.isEmpty() }) throw AgentException("INVALID_REQUEST", "xodus needs its arguments")
val timeoutMs = (request.optDouble("timeout", 120.0) * 1000).toLong().coerceIn(1_000L, 900_000L)
return Xodus.start(context.applicationContext, args).use { child ->
val out = Tail(child.process.inputStream)
val err = Tail(child.process.errorStream)
val finished = child.process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)
if (!finished) child.close()
JSONObject().put("ok", true).put("command", "xodus").put("timedOut", !finished)
.put("exit", if (finished) child.process.exitValue() else JSONObject.NULL)
.put("stdout", out.text()).put("stderr", err.text())
}
}
fun cloud(context: Context, request: JSONObject): JSONObject {
AgentAccess.requireCommands(context)
val store = Store.byId(request.optString("store"))?.takeIf(CloudSaves::supports)
?: throw AgentException("INVALID_REQUEST", "store must be one with cloud saves")
val id = request.optString("id").ifEmpty { throw AgentException("INVALID_REQUEST", "cloud needs a game id") }
val force = request.optBoolean("force")
val result = when (val direction = request.optString("direction")) {
"down" -> CloudSaves.download(context.applicationContext, store, id, force)
"up" -> CloudSaves.upload(context.applicationContext, store, id, force)
else -> throw AgentException("INVALID_REQUEST", "direction '$direction' is not down or up")
}
return JSONObject().put("ok", true).put("command", "cloud").put("result", result.result).put("files", result.files)
.put("bytes", result.bytes).put("reason", result.reason).put("conflicts", result.conflicts).put("detail", result.detail)
}
private class Tail(stream: InputStream) {
private val kept = ByteArrayOutputStream()
private var dropped = false
private val reader = Thread({
val buffer = ByteArray(8192)
stream.use { input ->
while (true) {
val n = runCatching { input.read(buffer) }.getOrDefault(-1)
if (n < 0) break
synchronized(kept) {
kept.write(buffer, 0, n)
if (kept.size() > OUTPUT_CAP * 2) {
val bytes = kept.toByteArray()
kept.reset()
kept.write(bytes, bytes.size - OUTPUT_CAP, OUTPUT_CAP)
dropped = true
}
}
}
}
}, "agent-xodus-output").apply { isDaemon = true; start() }
fun text(): String {
reader.join(2_000)
val bytes = synchronized(kept) { kept.toByteArray() }
val tail = if (bytes.size > OUTPUT_CAP) bytes.copyOfRange(bytes.size - OUTPUT_CAP, bytes.size) else bytes
return (if (dropped || bytes.size > OUTPUT_CAP) "...\n" else "") + String(tail, Charsets.UTF_8)
}
}
}
@@ -1,9 +1,23 @@
package com.droiddeck.launcher.agent package com.droiddeck.launcher.agent
import com.droiddeck.launcher.ui.NavTabs import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
object AgentTab { object AgentTab {
val shown: Boolean get() = "agent" !in NavTabs.hidden var shown by mutableStateOf(true)
private set
val visible: Boolean get() = shown && AgentHost.available val visible: Boolean get() = shown && AgentHost.available
fun load(context: Context) {
shown = SessionPrefs.agentTab(context)
}
fun set(context: Context, show: Boolean) {
shown = show
SessionPrefs.setAgentTab(context, show)
}
} }
@@ -16,10 +16,8 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.IntConsumer; import java.util.function.IntConsumer;
import java.util.function.IntSupplier; import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class PulseAudioComponent extends SessionPart { public class PulseAudioComponent extends SessionPart {
private static final String TAG = "PulseAudio"; private static final String TAG = "PulseAudio";
@@ -40,7 +38,6 @@ public class PulseAudioComponent extends SessionPart {
private long generation; private long generation;
private long launches; private long launches;
private final IntConsumer terminate; private final IntConsumer terminate;
final ReentrantReadWriteLock commands = new ReentrantReadWriteLock();
HostLifecycle(IntConsumer terminate) { HostLifecycle(IntConsumer terminate) {
this.terminate = terminate; this.terminate = terminate;
@@ -57,27 +54,11 @@ public class PulseAudioComponent extends SessionPart {
pid = -1; pid = -1;
} }
boolean launch(long expected, IntSupplier launch) { synchronized boolean launch(long expected, IntSupplier launch) {
commands.writeLock().lock(); if (expected != generation) return false;
try { launches++;
synchronized (this) { pid = launch.getAsInt();
if (expected != generation) return false; return true;
launches++;
pid = launch.getAsInt();
return true;
}
} finally {
commands.writeLock().unlock();
}
}
<T> T command(long token, Supplier<T> command) {
commands.readLock().lock();
try {
return live(token) ? command.get() : null;
} finally {
commands.readLock().unlock();
}
} }
synchronized boolean current(long expected) { synchronized boolean current(long expected) {
@@ -237,13 +218,13 @@ public class PulseAudioComponent extends SessionPart {
String loadedAs = null; String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) { for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
if (pactlOk(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1", if (pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactlOk(token, "set-default-sink", "DirectAudio")) { && pactlFor(token, "set-default-sink", "DirectAudio") != null) {
loadedAs = "DirectAudio on attempt " + attempt; loadedAs = "DirectAudio on attempt " + attempt;
} else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", } else if (pactlFor(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) "performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactlOk(token, "set-default-sink", "AAudioSink")) { && pactlFor(token, "set-default-sink", "AAudioSink") != null) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt; loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
} }
} }
@@ -267,24 +248,14 @@ public class PulseAudioComponent extends SessionPart {
} }
private String pactlFor(long token, String... args) { private String pactlFor(long token, String... args) {
return host.command(token, () -> pactl(true, args)); return host.live(token) ? pactl(args) : null;
} }
private boolean pactlOk(long token, String... args) { /** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
return host.command(token, () -> pactl(false, args)) != null; private String pactl(String... args) {
}
private static void reap(java.lang.Process process) throws InterruptedException {
process.destroyForcibly();
process.waitFor(2, TimeUnit.SECONDS);
}
/** Runs pactl against this daemon; its stdout when captured (empty otherwise), or null when it failed or timed out. */
private String pactl(boolean capture, String... args) {
File pactl = new File(workingDir, "pactl"); File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || host.pid <= 1) return null; if (!pactl.isFile() || host.pid <= 1) return null;
java.lang.Process process = null; java.lang.Process process = null;
File output = null;
try { try {
File modules = new File(workingDir, "modules/arm64"); File modules = new File(workingDir, "modules/arm64");
ArrayList<String> cmd = new ArrayList<>(); ArrayList<String> cmd = new ArrayList<>();
@@ -297,33 +268,29 @@ public class PulseAudioComponent extends SessionPart {
builder.environment().put("HOME", workingDir.getAbsolutePath()); builder.environment().put("HOME", workingDir.getAbsolutePath());
builder.environment().put("TMPDIR", workingDir.getAbsolutePath()); builder.environment().put("TMPDIR", workingDir.getAbsolutePath());
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath()); builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
if (capture) {
output = File.createTempFile("pactl", ".out", workingDir);
builder.redirectOutput(output);
} else {
builder.redirectOutput(new File("/dev/null"));
}
process = builder.start(); process = builder.start();
String output;
try (InputStream in = process.getInputStream();
java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream()) {
byte[] buf = new byte[4096];
int n;
while ((n = in.read(buf)) != -1) {
outStream.write(buf, 0, n);
}
output = outStream.toString(java.nio.charset.StandardCharsets.UTF_8.name());
}
if (!process.waitFor(5, TimeUnit.SECONDS)) { if (!process.waitFor(5, TimeUnit.SECONDS)) {
reap(process); process.destroyForcibly();
return null; return null;
} }
if (process.exitValue() != 0) return null; return process.exitValue() == 0 ? output : null;
return capture ? new String(Files.readAllBytes(output.toPath()), java.nio.charset.StandardCharsets.UTF_8) : "";
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
return null; return null;
} catch (Throwable t) { } catch (Throwable t) {
return null; return null;
} finally { } finally {
if (process != null && process.isAlive()) { if (process != null && process.isAlive()) process.destroyForcibly();
try {
reap(process);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (output != null) output.delete();
} }
} }
@@ -281,6 +281,9 @@ object DeviceReport {
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up") k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context)) k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context)) k("pace cores", SessionPrefs.paceCores(context))
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context)) k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("native userland (no proot)", SessionPrefs.nativeUserland(context)) k("native userland (no proot)", SessionPrefs.nativeUserland(context))
k("proot fast path", SessionPrefs.prootFastPath(context)) k("proot fast path", SessionPrefs.prootFastPath(context))
@@ -122,12 +122,6 @@ public final class Downloader {
return null; return null;
} }
public static Boolean gone(String url) {
Fetch fetch = fetch(url);
if (fetch.body != null) return Boolean.FALSE;
return fetch.fatal ? Boolean.TRUE : null;
}
public static String downloadDirect(String url) { public static String downloadDirect(String url) {
LAST_FAILURE.remove(); LAST_FAILURE.remove();
return fetch(url).body; return fetch(url).body;
@@ -23,7 +23,6 @@ object GameEnvironment {
) )
fun validName(name: String) = namePattern.matches(name) fun validName(name: String) = namePattern.matches(name)
fun currentName(name: String) = if (name.startsWith("BL_")) "DD_" + name.removePrefix("BL_") else name
fun supported(name: String) = name !in unused && !name.startsWith("BOX64_") && !name.startsWith("BOX86_") fun supported(name: String) = name !in unused && !name.startsWith("BOX64_") && !name.startsWith("BOX86_")
fun validValue(value: String) = '\u0000' !in value && value.length <= 8192 fun validValue(value: String) = '\u0000' !in value && value.length <= 8192
fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true) fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true)
@@ -98,14 +97,14 @@ object GameEnvironment {
val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER) val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER)
val syncKeys = listOf("DD_SYNC", "DD_FSYNC_FIRST", "DD_SYNC_FALLBACK", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC") val syncKeys = listOf("BL_SYNC", "BL_FSYNC_FIRST", "BL_SYNC_FALLBACK", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
fun syncEnvironment(backend: String): Map<String, String> { fun syncEnvironment(backend: String): Map<String, String> {
require(backend in syncBackends) { "unknown sync $backend" } require(backend in syncBackends) { "unknown sync $backend" }
return buildMap { return buildMap {
put("DD_SYNC", if (backend == SessionPrefs.SYNC_NTSYNC) "1" else "0") put("BL_SYNC", if (backend == SessionPrefs.SYNC_NTSYNC) "1" else "0")
put("DD_FSYNC_FIRST", if (backend == SessionPrefs.SYNC_FSYNC) "1" else "0") put("BL_FSYNC_FIRST", if (backend == SessionPrefs.SYNC_FSYNC) "1" else "0")
put("DD_SYNC_FALLBACK", if (backend == SessionPrefs.SYNC_WINESERVER) "0" else "1") put("BL_SYNC_FALLBACK", if (backend == SessionPrefs.SYNC_WINESERVER) "0" else "1")
if (backend == SessionPrefs.SYNC_FSYNC) put("PROTON_NO_ESYNC", "1") if (backend == SessionPrefs.SYNC_FSYNC) put("PROTON_NO_ESYNC", "1")
} }
} }
@@ -20,7 +20,7 @@ object GameEnvironmentOptions {
Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")), Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")), Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_NO_FSYNC", "1", R.string.game_env_no_fsync, Type.TOGGLE, listOf("0", "1")), Option("PROTON_NO_FSYNC", "1", R.string.game_env_no_fsync, Type.TOGGLE, listOf("0", "1")),
Option("DD_FSYNC_FIRST", "1", R.string.game_env_fsync_first, Type.TOGGLE, listOf("0", "1")), Option("BL_FSYNC_FIRST", "1", R.string.game_env_fsync_first, Type.TOGGLE, listOf("0", "1")),
Option("DXVK_HUD", "fps", R.string.game_env_hud, Type.MULTIPLE, listOf("scale=0.5", "scale=0.7", "opacity=0.5", "opacity=0.7", "devinfo", "fps", "frametimes", "submissions", "drawcalls", "pipelines", "descriptors", "memory", "gpuload", "version", "api", "cs", "compiler", "samplers")), Option("DXVK_HUD", "fps", R.string.game_env_hud, Type.MULTIPLE, listOf("scale=0.5", "scale=0.7", "opacity=0.5", "opacity=0.7", "devinfo", "fps", "frametimes", "submissions", "drawcalls", "pipelines", "descriptors", "memory", "gpuload", "version", "api", "cs", "compiler", "samplers")),
Option("DXVK_CONFIG", "dxvk.maxFrameRate = 60", R.string.game_env_dxvk_config, Type.TEXT), Option("DXVK_CONFIG", "dxvk.maxFrameRate = 60", R.string.game_env_dxvk_config, Type.TEXT),
Option("VKD3D_FRAME_RATE", "60", R.string.game_env_vkd3d_limit, Type.NUMBER), Option("VKD3D_FRAME_RATE", "60", R.string.game_env_vkd3d_limit, Type.NUMBER),
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.core package com.droiddeck.launcher.core
import android.content.Context
import android.os.Process import android.os.Process
import android.util.Log import android.util.Log
import java.io.BufferedWriter import java.io.BufferedWriter
@@ -114,17 +113,7 @@ object SessionLogCapture {
} }
} }
internal const val LMKD_COMMAND = "logcat -d -b main,events -v threadtime -s lowmemorykiller:D killinfo:I" + fun dumpMemoryPressure(target: File) {
" | grep -v -E 'pgskip|zoneinfo_parse|polling check|thrashing:' | tail -n 120"
private fun lowMemoryKiller(context: Context?): String = when {
context == null -> "(not captured)\n"
!WirelessAdbFix.hasSavedPairing(context) -> "(not captured: pair DroidDeck with Wireless debugging in Settings > Diagnostics)\n"
else -> runCatching { WirelessAdbFix.shell(context, LMKD_COMMAND) }
.fold({ it.ifBlank { "(no lmkd lines in the log)\n" } }, { "(not captured: ${it.message})\n" })
}
fun dumpMemoryPressure(target: File, context: Context? = null) {
var temporary: File? = null var temporary: File? = null
try { try {
val staged = File.createTempFile(target.name, ".part", target.parentFile).also { temporary = it } val staged = File.createTempFile(target.name, ".part", target.parentFile).also { temporary = it }
@@ -161,8 +150,7 @@ object SessionLogCapture {
body.isNotEmpty() -> body body.isNotEmpty() -> body
else -> "(no readable events were returned)\n" else -> "(no readable events were returned)\n"
} + } +
"\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu" + "\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu"
"\nAndroid's low memory killer (lmkd), read over Wireless debugging:\n${lowMemoryKiller(context)}"
) )
Files.move( Files.move(
staged.toPath(), target.toPath(), staged.toPath(), target.toPath(),
@@ -37,7 +37,7 @@ object SteamIntegration {
locationOn = WifiDiscovery.locationEnabled(context), locationOn = WifiDiscovery.locationEnabled(context),
brightness = Settings.System.canWrite(context), brightness = Settings.System.canWrite(context),
home = HomeApp.isDefault(context), home = HomeApp.isDefault(context),
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context), shortcuts = shortcutsEnabled(context),
shortcutsRestricted = restrictedSettings(context), shortcutsRestricted = restrictedSettings(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false), suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
) )
@@ -61,10 +61,6 @@ object SteamIntegration {
return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent } return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent }
} }
@Suppress("DEPRECATION")
fun shortcutsCurrent(context: Context): Boolean =
runCatching { context.packageManager.getPackageInfo(Relay.PACKAGE, 0).versionCode }.getOrDefault(0) >= Relay.VERSION
fun shortcutsListed(context: Context): Boolean = fun shortcutsListed(context: Context): Boolean =
context.getSystemService(android.view.accessibility.AccessibilityManager::class.java) context.getSystemService(android.view.accessibility.AccessibilityManager::class.java)
?.installedAccessibilityServiceList.orEmpty() ?.installedAccessibilityServiceList.orEmpty()
@@ -235,17 +235,6 @@ object WirelessAdbFix {
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
fun savedPairingIsLocal(context: Context): Boolean = savedConnection(context.applicationContext)?.host
?.let { host ->
// Unlike isLocalAddress, an address that cannot be matched to this device's own counts as remote.
runCatching {
val address = InetAddress.getByName(host)
address.isLoopbackAddress || NetworkInterface.getNetworkInterfaces().toList().any { network ->
network.inetAddresses.toList().any { it.address.contentEquals(address.address) }
}
}.getOrDefault(false)
} == true
fun clearCachedApps(context: Context) { fun clearCachedApps(context: Context) {
shell(context, "am kill-all") shell(context, "am kill-all")
} }
@@ -13,7 +13,6 @@ import android.provider.DocumentsContract.Root
import android.provider.DocumentsProvider import android.provider.DocumentsProvider
import android.webkit.MimeTypeMap import android.webkit.MimeTypeMap
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File import java.io.File
import java.io.FileNotFoundException import java.io.FileNotFoundException
import java.io.IOException import java.io.IOException
@@ -27,21 +26,11 @@ import java.nio.file.attribute.BasicFileAttributes
class AppFilesProvider : DocumentsProvider() { class AppFilesProvider : DocumentsProvider() {
private lateinit var base: File private lateinit var base: File
private lateinit var baseCanonical: String private lateinit var baseCanonical: String
private lateinit var privatePaths: List<String>
override fun attachInfo(context: Context, info: ProviderInfo) { override fun attachInfo(context: Context, info: ProviderInfo) {
super.attachInfo(context, info) super.attachInfo(context, info)
base = context.dataDir base = context.dataDir
baseCanonical = base.canonicalPath baseCanonical = base.canonicalPath
// The wireless ADB pairing identity, preferences, store logins and Steam's saved login stay app-only.
privatePaths = listOf(
context.noBackupFilesDir,
File(base, "shared_prefs"),
context.getDatabasePath("x").parentFile!!,
File(context.filesDir, "stores"),
File(SessionPrefs.steamRoot(context, "arm64"), "config"),
File(SessionPrefs.steamRoot(context, "x86_64"), "config"),
).flatMap { listOf(it.absoluteFile.normalize().path, runCatching { it.canonicalPath }.getOrDefault(it.path)) }.distinct()
} }
override fun onCreate() = true override fun onCreate() = true
@@ -85,7 +74,6 @@ class AppFilesProvider : DocumentsProvider() {
var file = File(parent, name) var file = File(parent, name)
var n = 2 var n = 2
while (file.exists()) file = File(parent, "$name (${n++})") while (file.exists()) file = File(parent, "$name (${n++})")
if (isPrivate(file)) throw FileNotFoundException("could not create ${file.path}")
val made = try { val made = try {
if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile() if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile()
} catch (e: IOException) { } catch (e: IOException) {
@@ -97,7 +85,7 @@ class AppFilesProvider : DocumentsProvider() {
override fun deleteDocument(documentId: String) { override fun deleteDocument(documentId: String) {
val file = fileFor(documentId) val file = fileFor(documentId)
if (file.canonicalPath == baseCanonical || holdsPrivate(file)) throw FileNotFoundException("$documentId holds the app's private files") if (file.canonicalPath == baseCanonical) throw FileNotFoundException("the app folder itself is not deleted")
try { try {
deleteTree(file.toPath()) deleteTree(file.toPath())
} catch (e: IOException) { } catch (e: IOException) {
@@ -128,19 +116,17 @@ class AppFilesProvider : DocumentsProvider() {
override fun renameDocument(documentId: String, displayName: String): String { override fun renameDocument(documentId: String, displayName: String): String {
val file = fileFor(documentId) val file = fileFor(documentId)
if (holdsPrivate(file)) throw FileNotFoundException("$documentId holds the app's private files")
val target = File(file.parentFile, displayName.substringAfterLast('/')) val target = File(file.parentFile, displayName.substringAfterLast('/'))
if (target.exists() || isPrivate(target) || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId") if (target.exists() || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId")
return target.absolutePath return target.absolutePath
} }
override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String { override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String {
val source = fileFor(sourceDocumentId) val source = fileFor(sourceDocumentId)
if (holdsPrivate(source)) throw FileNotFoundException("$sourceDocumentId holds the app's private files")
val targetParent = fileFor(targetParentDocumentId) val targetParent = fileFor(targetParentDocumentId)
if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder") if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder")
val target = File(targetParent, source.name) val target = File(targetParent, source.name)
if (target.exists() || isPrivate(target) || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId") if (target.exists() || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId")
return target.absolutePath return target.absolutePath
} }
@@ -177,19 +163,7 @@ class AppFilesProvider : DocumentsProvider() {
val abs = f.absoluteFile.normalize().path val abs = f.absoluteFile.normalize().path
if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false
val real = runCatching { f.canonicalPath }.getOrNull() ?: return false val real = runCatching { f.canonicalPath }.getOrNull() ?: return false
if (real != baseCanonical && !real.startsWith("$baseCanonical/")) return false return real == baseCanonical || real.startsWith("$baseCanonical/")
return !isPrivate(f)
}
private fun isPrivate(f: File): Boolean {
val real = runCatching { f.canonicalPath }.getOrNull() ?: return true
val paths = listOf(f.absoluteFile.normalize().path, real)
return privatePaths.any { p -> paths.any { it == p || it.startsWith("$p/") } }
}
private fun holdsPrivate(f: File): Boolean {
val paths = listOfNotNull(f.absoluteFile.normalize().path, runCatching { f.canonicalPath }.getOrNull())
return privatePaths.any { p -> paths.any { p.startsWith("$it/") } }
} }
private fun addRow(result: MatrixCursor, file: File) { private fun addRow(result: MatrixCursor, file: File) {
@@ -199,7 +173,7 @@ class AppFilesProvider : DocumentsProvider() {
} else if (file.canWrite()) { } else if (file.canWrite()) {
flags = flags or Document.FLAG_SUPPORTS_WRITE flags = flags or Document.FLAG_SUPPORTS_WRITE
} }
if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true && !holdsPrivate(file)) { if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true) {
flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or
Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE
} }
@@ -40,10 +40,12 @@ import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material.icons.filled.CreateNewFolder import androidx.compose.material.icons.filled.CreateNewFolder
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.SdStorage import androidx.compose.material.icons.filled.SdStorage
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Sort import androidx.compose.material.icons.filled.Sort
import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.ViewList
import androidx.compose.material.icons.filled.StarBorder import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material.icons.filled.Storage import androidx.compose.material.icons.filled.Storage
import androidx.compose.material.icons.filled.Smartphone import androidx.compose.material.icons.filled.Smartphone
@@ -725,15 +727,11 @@ fun FileManagerScreen(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer) .background(MaterialTheme.colorScheme.surfaceContainer)
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier)
.padding(horizontal = 8.dp, vertical = 6.dp), .padding(horizontal = 8.dp, vertical = 6.dp),
) { ) {
val upEnabled = canGoUp && !cancellingNavigation IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = upEnabled, modifier = Modifier.focusGlide(CircleShape)) { Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
Icon(
Icons.Filled.ArrowBack,
stringResource(R.string.fm_back),
tint = if (upEnabled) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),
)
} }
val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel) val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel)
@@ -796,119 +794,113 @@ fun FileManagerScreen(
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
Row( if (showFavorites) {
verticalAlignment = Alignment.CenterVertically, Text(
modifier = Modifier text = stringResource(R.string.fm_favorites),
.weight(1f) color = MaterialTheme.colorScheme.primary,
.then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier), fontSize = 13.sp,
) { fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (!compactToolbar) Spacer(Modifier.weight(1f))
} else {
Text(
text = currentDir.name.ifBlank { currentDir.absolutePath },
color = MaterialTheme.colorScheme.onSurface,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
}
if (launchDir != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
}
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
}
if (!showFavorites) {
if (!pickMode) {
OutlinedButton(
onClick = { showNewFolderDialog = true },
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
) {
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(5.dp))
Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
}
}
IconButton(onClick = {
gridView = !gridView
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
}, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView,
if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
Box {
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size))
.forEach { (key, label) ->
DropdownMenuItem(
text = {
Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label)
},
onClick = {
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
browsePrefs.edit().putString("fmSortBy", sortBy)
.putBoolean("fmSortDesc", sortDesc).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
DropdownMenuItem(
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
onClick = {
compactRows = !compactRows
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
showSortMenu = false
},
modifier = Modifier.focusGlide(),
)
DropdownMenuItem(
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
onClick = {
showHidden = !showHidden
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
}
}
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
if (showFavorites) { if (showFavorites) {
Text( Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
text = stringResource(R.string.fm_favorites),
color = MaterialTheme.colorScheme.primary,
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
} else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (!compactToolbar) Spacer(Modifier.weight(1f))
} else { } else {
Text( Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
text = currentDir.name.ifBlank { currentDir.absolutePath },
color = MaterialTheme.colorScheme.onSurface,
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f),
)
}
if (launchDir != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary)
}
if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp))
}
if (!showFavorites) {
if (!pickMode) {
OutlinedButton(
onClick = { showNewFolderDialog = true },
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp),
modifier = Modifier.height(32.dp).focusGlide(CircleShape),
) {
Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(5.dp))
Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp)
}
}
IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
Box {
IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {
listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size))
.forEach { (key, label) ->
DropdownMenuItem(
text = {
Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label)
},
onClick = {
if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false }
browsePrefs.edit().putString("fmSortBy", sortBy)
.putBoolean("fmSortDesc", sortDesc).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
DropdownMenuItem(
text = { Text(if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view)) },
onClick = {
gridView = !gridView
browsePrefs.edit().putBoolean("fmGridView", gridView).apply()
showSortMenu = false
},
modifier = Modifier.focusGlide(),
)
DropdownMenuItem(
text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) },
onClick = {
compactRows = !compactRows
browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply()
showSortMenu = false
},
modifier = Modifier.focusGlide(),
)
DropdownMenuItem(
text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) },
onClick = {
showHidden = !showHidden
browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply()
showSortMenu = false
loadDirectory(currentDir, resetScroll = false)
},
modifier = Modifier.focusGlide(),
)
}
}
}
IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) {
if (showFavorites) {
Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary)
} else {
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
} }
} }
if (!pickMode && onExit != null) { if (!pickMode && onExit != null) {
@@ -335,10 +335,7 @@ object AddedGames {
val path = canonical(exe) val path = canonical(exe)
val owner = ownerFolder(app, exe) val owner = ownerFolder(app, exe)
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) { if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let { single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let { return AddResult.Existing(it) }
if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path))
return AddResult.Existing(it)
}
} }
if (guestPath(app, exe) == null) { if (guestPath(app, exe) == null) {
(owner ?: exe.parentFile)?.takeIf { guestPath(app, it) == null }?.let { bindFolder(app, it) } (owner ?: exe.parentFile)?.takeIf { guestPath(app, it) == null }?.let { bindFolder(app, it) }
@@ -347,7 +344,7 @@ object AddedGames {
val folder = owner ?: exe.parentFile ?: return AddResult.NotFound val folder = owner ?: exe.parentFile ?: return AddResult.NotFound
SessionPrefs.setAddedGameRemoved(app, folder.path, false) SessionPrefs.setAddedGameRemoved(app, folder.path, false)
SessionPrefs.setAddedGameExe(app, folder.path, exe.path) SessionPrefs.setAddedGameExe(app, folder.path, exe.path)
AddedExes.put(app, AddedExes.Entry(folder.path, exe.path)) if (owner == null) AddedExes.put(app, AddedExes.Entry(folder.path, exe.path))
val game = single(app, folder.path) ?: return AddResult.NotFound val game = single(app, folder.path) ?: return AddResult.NotFound
AddedGamesPublisher.later(app) { com.droiddeck.launcher.stores.SteamLiveShortcuts.sync(app, listOf(game)) { true } } AddedGamesPublisher.later(app) { com.droiddeck.launcher.stores.SteamLiveShortcuts.sync(app, listOf(game)) { true } }
Log.i(TAG, "added ${game.name} from its exe") Log.i(TAG, "added ${game.name} from its exe")
@@ -2,9 +2,6 @@ package com.droiddeck.launcher.frontend
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import android.util.AtomicFile import android.util.AtomicFile
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
import androidx.core.util.readText import androidx.core.util.readText
@@ -16,65 +13,27 @@ import java.io.InputStream
object GameFiles { object GameFiles {
const val EXTENSION = "steam" const val EXTENSION = "steam"
private const val MAX_BYTES = 4096 private const val MAX_BYTES = 128
private const val MAX_NAME_BYTES = 200 private const val MAX_NAME_BYTES = 200
private const val INVENTORY = ".droiddeck-sync.json" private const val INVENTORY = ".droiddeck-sync.json"
private const val FORMAT = "droiddeck-game-files-v1" private const val FORMAT = "droiddeck-game-files-v1"
fun readIntent(context: Context, request: Intent): GameRequest? = runCatching { fun readIntent(context: Context, request: Intent): String? = runCatching {
if (request.action != Intent.ACTION_VIEW) return null if (request.action != Intent.ACTION_VIEW) return null
val uri = request.data ?: return null val uri = request.data ?: return null
GameRequest.link(uri.toString())?.let { return GameRequest(it) } GameLaunchLink.parse(uri.toString())?.let { return it }
val name = displayName(context, uri)
val extension = name?.substringAfterLast('.', "").orEmpty()
if (extension.lowercase(java.util.Locale.ROOT) in GameRequest.PROGRAMS) {
val program = localFile(context, uri)?.takeIf { it.isFile } ?: return null
return GameRequest(title = name?.substringBeforeLast('.'), program = program.canonicalFile)
}
val stream = when (uri.scheme) { val stream = when (uri.scheme) {
"content" -> runCatching { context.contentResolver.openInputStream(uri) }.getOrNull() "content" -> context.contentResolver.openInputStream(uri)
?: localFile(context, uri)?.takeIf { it.isFile }?.inputStream() "file" -> {
"file", null -> localFile(context, uri)?.inputStream() if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) return null
File(uri.path ?: return null).inputStream()
}
null -> File(uri.toString()).takeIf { it.isAbsolute }?.inputStream()
else -> null else -> null
} ?: return null } ?: return null
val id = stream.use(::read) ?: return null stream.use(::read)
GameRequest(id, GameRequest.sourceOf(extension), name?.substringBeforeLast('.'))
}.getOrNull() }.getOrNull()
private fun displayName(context: Context, uri: Uri): String? = when (uri.scheme) {
"content" -> runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
}
}.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/')?.substringAfterLast(':')
"file" -> uri.path?.let { File(it).name }
null -> File(uri.toString()).name
else -> null
}?.takeIf { it.isNotEmpty() }
private fun localFile(context: Context, uri: Uri): File? = when (uri.scheme) {
"file" -> {
if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) null
else uri.path?.let(::File)
}
null -> File(uri.toString()).takeIf { it.isAbsolute }
"content" -> storageDocument(context, uri) ?: uri.pathSegments.let { parts ->
(0..1).asSequence().map { File("/" + parts.drop(it).joinToString("/")) }.firstOrNull { it.isFile }
}
else -> null
}
// Frontends pass SAF document URIs or FileProvider URIs whose path mirrors shared storage.
private fun storageDocument(context: Context, uri: Uri): File? {
if (uri.authority != "com.android.externalstorage.documents" || !DocumentsContract.isDocumentUri(context, uri)) return null
val id = DocumentsContract.getDocumentId(uri)
val volume = id.substringBefore(':')
val path = id.substringAfter(':', "")
val root = if (volume.equals("primary", ignoreCase = true)) android.os.Environment.getExternalStorageDirectory()
else File("/storage", volume)
return File(root, path)
}
fun read(stream: InputStream): String? { fun read(stream: InputStream): String? {
val bytes = ByteArray(MAX_BYTES + 1) val bytes = ByteArray(MAX_BYTES + 1)
var count = 0 var count = 0
@@ -85,7 +44,8 @@ object GameFiles {
count += n count += n
} }
if (count > MAX_BYTES) return null if (count > MAX_BYTES) return null
return GameRequest.parse(String(bytes, 0, count, Charsets.UTF_8)) val text = String(bytes, 0, count, Charsets.UTF_8).trim()
return text.takeIf(GameLaunchLink::validId)
} }
fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String { fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String {
@@ -101,7 +61,7 @@ object GameFiles {
} }
val title = String(points, 0, end).trimEnd { it.isWhitespace() || it == '.' }.ifBlank { "Game" } val title = String(points, 0, end).trimEnd { it.isWhitespace() || it == '.' }.ifBlank { "Game" }
val suffix = if (disambiguate) " (${game.gameIdString})" else "" val suffix = if (disambiguate) " (${game.gameIdString})" else ""
return "$title$suffix.${GameRequest.extension(game)}" return "$title$suffix.$EXTENSION"
} }
private fun contents(id: String): String { private fun contents(id: String): String {
@@ -170,7 +130,7 @@ object GameFiles {
} }
for (name in previous.keys()) { for (name in previous.keys()) {
val id = previous.getString(name) val id = previous.getString(name)
if (!next.has(name) && ours(name) && GameLaunchLink.validId(id)) { if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) {
val file = child(context, folder, name) val file = child(context, folder, name)
if (matches(file, contents(id))) { if (matches(file, contents(id))) {
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) } val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
@@ -181,9 +141,6 @@ object GameFiles {
if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString()) if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString())
} }
private fun ours(name: String) = name.substringAfterLast('.', "").lowercase(java.util.Locale.ROOT)
.let { it == EXTENSION || it in GameRequest.extensions }
private fun inventoryOwns(context: Context, folder: File, record: JSONObject, file: File, id: String): Boolean { private fun inventoryOwns(context: Context, folder: File, record: JSONObject, file: File, id: String): Boolean {
if (record.optString(file.name) == id) return true if (record.optString(file.name) == id) return true
if (!file.exists()) return false if (!file.exists()) return false
@@ -11,26 +11,22 @@ object GameLaunchIntent {
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) { fun read(context: Context, intent: Intent): String? = when (intent.action) {
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent) Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
ACTION, GAMENATIVE_ACTION -> readExtras(intent) ACTION, GAMENATIVE_ACTION -> readId(intent)
else -> null else -> null
} }
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
internal fun readExtras(intent: Intent): GameRequest? = runCatching { internal fun readId(intent: Intent): String? = runCatching {
if (intent.action != ACTION && intent.action != GAMENATIVE_ACTION) return null if (intent.action != ACTION && intent.action != GAMENATIVE_ACTION) return null
val source = when (val value = intent.extras?.get(EXTRA_GAME_SOURCE)) { val source = intent.extras?.get(EXTRA_GAME_SOURCE)
null -> Library.SOURCE_STEAM if (source != null && (source !is String || !source.equals("STEAM", ignoreCase = true))) return null
is String -> GameRequest.sourceNamed(value) ?: return null
else -> return null
}
val id = when (val value = intent.extras?.get(EXTRA_APP_ID)) { val id = when (val value = intent.extras?.get(EXTRA_APP_ID)) {
is Int -> value.takeIf { it > 0 }?.toString() is Int -> value.takeIf { it > 0 }?.toString()
is Long -> value.takeIf { it != 0L }?.let(java.lang.Long::toUnsignedString)
is String -> value.takeIf(GameLaunchLink::validId) is String -> value.takeIf(GameLaunchLink::validId)
else -> null else -> null
} ?: return null }
GameRequest(id, source) id
}.getOrNull() }.getOrNull()
} }
@@ -1,78 +0,0 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.stores.Store
import java.io.File
import java.util.Locale
class GameRequest(
val id: String? = null,
val source: String = Library.SOURCE_STEAM,
val title: String? = null,
val program: File? = null,
) {
fun find(games: List<Library.SteamGame>, byTitle: Boolean = true): Library.SteamGame? {
program?.let { return owner(games, it) }
val exact = id?.let { id -> games.firstOrNull { it.gameIdString == id } }
if (source == Library.SOURCE_STEAM) return exact ?: games.firstOrNull { it.appId > 0 && it.appId.toString() == id }
exact?.takeIf { it.source == source }?.let { return it }
id?.let { id -> games.firstOrNull { it.source == source && it.storeId == id } }?.let { return it }
if (!byTitle) return null
val key = title?.let(::titleKey)?.takeIf { it.isNotEmpty() } ?: return null
return games.firstOrNull { it.source == source && titleKey(it.name) == key }
}
private fun owner(games: List<Library.SteamGame>, program: File): Library.SteamGame? {
val path = program.path
return games.mapNotNull { game ->
val folder = game.gameFiles ?: return@mapNotNull null
val dir = folder.absolutePath.takeIf { inside(path, it) }
?: runCatching { folder.canonicalPath }.getOrNull()?.takeIf { inside(path, it) }
dir?.let { game to it.length }
}.maxByOrNull { it.second }?.first
}
companion object {
val PROGRAMS = setOf("exe", "bat")
private const val CUSTOM_GAME = "CUSTOM_GAME"
private const val CUSTOM_EXTENSION = "pcgame"
private val DAIJISHOU = setOf("# Daijishou Player Template", "# DST")
private val daijishouId = Regex("""(?i)\[steamappid]\s*([0-9]+)""")
private val steamLink = Regex("steam://rungameid/([1-9][0-9]{0,19})")
val extensions: Set<String> = Store.entries.map { it.id }.toSet() + CUSTOM_EXTENSION
fun extension(game: Library.SteamGame): String = Store.byId(game.source)?.id ?: GameFiles.EXTENSION
fun sourceNamed(value: String): String? = when {
value.equals(Library.SOURCE_STEAM, ignoreCase = true) -> Library.SOURCE_STEAM
value.equals(CUSTOM_GAME, ignoreCase = true) -> Library.ADDED
else -> Store.entries.firstOrNull { it.name.equals(value, ignoreCase = true) }?.id
}
fun sourceOf(extension: String): String = when (val ext = extension.lowercase(Locale.ROOT)) {
CUSTOM_EXTENSION -> Library.ADDED
else -> Store.byId(ext)?.id ?: Library.SOURCE_STEAM
}
fun link(text: String): String? = text.takeIf(GameLaunchLink::validId)
?: GameLaunchLink.parse(text)
?: steamLink.matchEntire(text)?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId)
fun parse(text: String): String? {
link(text.trim())?.let { return it }
val lines = text.lines().map { it.trim() }.filter { it.isNotEmpty() }
val header = lines.firstOrNull() ?: return null
return when {
DAIJISHOU.any { header.equals(it, ignoreCase = true) } -> lines.firstNotNullOfOrNull { daijishouId.matchEntire(it) }
?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId)
header.equals("[InternetShortcut]", ignoreCase = true) -> lines.firstOrNull { it.startsWith("URL=", ignoreCase = true) }
?.substring(4)?.trim()?.takeIf { !GameLaunchLink.validId(it) }?.let(::link)
else -> null
}
}
internal fun titleKey(name: String): String = name.lowercase(Locale.ROOT).filter { it.isLetterOrDigit() }
private fun inside(path: String, dir: String) = path.startsWith(dir.trimEnd(File.separatorChar) + File.separator)
}
}
@@ -222,7 +222,16 @@ object Library {
internal fun concealedSteamApps(root: File): Set<Long> { internal fun concealedSteamApps(root: File): Set<Long> {
val config = AddedGames.accountConfig(root) ?: return emptySet() val config = AddedGames.accountConfig(root) ?: return emptySet()
val hidden = SteamHidden.read(root) val hidden = runCatching {
val entries = org.json.JSONArray(File(config, "cloudstorage/cloud-storage-namespace-1.json").readText())
val entry = (0 until entries.length()).map { entries.getJSONArray(it) }
.firstOrNull { it.optString(0) == "user-collections.hidden" }?.optJSONObject(1)
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = org.json.JSONObject(entry.optString("value"))
fun ids(key: String) = collection.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optLong(it) } }.orEmpty()
ids("added").toSet() - ids("removed").toSet()
}
}.getOrDefault(emptySet())
val private = runCatching { val private = runCatching {
PRIVATE_APPS.find(File(config, "localconfig.vdf").readText())?.groupValues?.get(1) PRIVATE_APPS.find(File(config, "localconfig.vdf").readText())?.groupValues?.get(1)
?.split(',')?.mapNotNull { it.trim().toLongOrNull() }?.toSet() ?.split(',')?.mapNotNull { it.trim().toLongOrNull() }?.toSet()
@@ -293,7 +302,6 @@ object Library {
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId, g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, lastPlayed = maxOf(lastPlayed, recordedPlay(context, g.gameId)), gameFiles = g.folder, hero = art.hero ?: art.header, lastPlayed = maxOf(lastPlayed, recordedPlay(context, g.gameId)), gameFiles = g.folder,
protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory } protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory }
else if (g.source == com.droiddeck.launcher.stores.Store.UBISOFT.id) File(com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.prefix(context), "pfx").takeIf { it.isDirectory }
else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots), else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" }, icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
source = g.source, storeId = g.storeId, source = g.source, storeId = g.storeId,
@@ -177,10 +177,9 @@ object SoundtrackCollections {
source = Library.SOURCE_COLLECTION, soundtrack = true, source = Library.SOURCE_COLLECTION, soundtrack = true,
) )
fun games(context: Context, favoritesLabel: String, skipEmptyFavorites: Boolean = false): List<Library.SteamGame> { fun games(context: Context, favoritesLabel: String): List<Library.SteamGame> {
val s = snapshot val s = snapshot
val favorites = if (skipEmptyFavorites && s.favorites.isEmpty()) emptyList() else listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) return listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + s.collections.map { game(context, it.id, it.name, it.tracks) }
return favorites + s.collections.map { game(context, it.id, it.name, it.tracks) }
} }
fun album(context: Context, id: Int): Soundtrack.Album { fun album(context: Context, id: Int): Soundtrack.Album {
@@ -1,78 +0,0 @@
package com.droiddeck.launcher.frontend
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
internal object SteamHidden {
private const val KEY = "user-collections.hidden"
private fun file(root: File): File? = AddedGames.accountConfig(root)?.let { File(it, "cloudstorage/cloud-storage-namespace-1.json") }
class Saved(val hidden: Set<Long>, val queued: Boolean)
private fun id(member: Any?): Long? = when (member) {
is Int -> member.toLong()
is Long -> member
is String -> member.toLongOrNull()
else -> null
}
private fun ids(collection: JSONObject, key: String, strict: Boolean): List<Long> {
if (!collection.has(key)) return emptyList()
val array = collection.optJSONArray(key) ?: throw IllegalStateException(key)
return (0 until array.length()).mapNotNull { index ->
id(array.get(index)) ?: if (strict) throw IllegalStateException(key) else null
}
}
fun read(root: File): Set<Long> = readOrNull(root).orEmpty()
fun readOrNull(root: File): Set<Long>? = runCatching {
val entries = JSONArray(file(root)?.readText() ?: return null)
val slot = (0 until entries.length()).map { entries.getJSONArray(it) }.firstOrNull { it.optString(0) == KEY }
val entry = slot?.optJSONObject(1)
if (slot != null && entry == null) return null
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = JSONObject(entry.optString("value"))
ids(collection, "added", false).toSet() - ids(collection, "removed", false).toSet()
}
}.getOrNull()
fun write(root: File, appId: Long, hidden: Boolean, now: Long = System.currentTimeMillis() / 1000): Saved? = runCatching {
val target = file(root) ?: return null
val entries = JSONArray(target.readText())
val slot = (0 until entries.length()).firstOrNull { entries.getJSONArray(it).optString(0) == KEY }
val entry = if (slot == null) JSONObject().put("key", KEY) else entries.getJSONArray(slot).optJSONObject(1) ?: return null
val live = !entry.optBoolean("is_deleted")
val collection = if (live && entry.has("value")) JSONObject(entry.optString("value")) else JSONObject().put("id", "hidden")
val added = ids(collection, "added", true).filter { it != appId }
val removed = ids(collection, "removed", true).filter { it != appId }
collection.put("added", JSONArray(if (hidden) added + appId else added))
collection.put("removed", JSONArray(if (hidden) removed else removed + appId))
entry.put("value", collection.toString())
entry.put("timestamp", now)
entry.put("is_deleted", false)
entry.opt("version")?.toString()?.toLongOrNull()?.let { entry.put("version", (it + 1).toString()) }
if (slot == null) entries.put(JSONArray().put(KEY).put(entry))
val temp = File(target.parentFile, target.name + ".tmp")
temp.writeText(entries.toString())
if (!temp.renameTo(target)) {
temp.delete()
return null
}
Saved(ids(collection, "added", true).toSet() - ids(collection, "removed", true).toSet(), markModified(File(target.parentFile, "cloud-storage-namespace-1.modified.json")))
}.getOrNull()
private fun markModified(file: File): Boolean {
val pending = if (file.exists()) runCatching { JSONArray(file.readText()) }.getOrNull() ?: return false else JSONArray()
if ((0 until pending.length()).any { pending.optString(it) == KEY }) return true
val temp = File(file.parentFile, file.name + ".tmp")
val saved = runCatching {
temp.writeText(pending.put(KEY).toString())
temp.renameTo(file)
}.getOrDefault(false)
if (!saved) temp.delete()
return saved
}
}
@@ -37,22 +37,22 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList() ?.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 } ?: emptyList()
val gpuCandidates = gpuSources() val gpuCandidates = gpuSources()
val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null } val gpu = gpuCandidates.firstOrNull { !it.startsWith("/proc/") && firstNumber(it) != null }
val stepSources = GpuLimits.stepSources()
val maxSources = GpuLimits.maxSources()
val minSources = GpuLimits.minSources()
val steps = GpuLimits.first(stepSources)
var ceiling = ceilingSource(maxSources)
val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager val power = app().getSystemService(Context.POWER_SERVICE) as? PowerManager
val time = SimpleDateFormat("HH:mm:ss", Locale.US) val time = SimpleDateFormat("HH:mm:ss", Locale.US)
try { try {
FileWriter(logFile, true).use { w -> FileWriter(logFile, true).use { w ->
w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n") w.write("== clocks: ${Build.MANUFACTURER} ${Build.MODEL} (${Build.HARDWARE}), every ${PERIOD_MS / 1000}s\n")
w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n") w.write("cpu policies: ${policies.joinToString { p -> p.name + " " + (File(p, "related_cpus").readTextOrNull()?.trim() ?: "?") }}\n")
probeLines("gpu source", gpuCandidates).forEach { w.write(it + "\n") } for (source in gpuCandidates) {
val f = File(source)
val state = when {
!f.exists() -> continue
firstNumber(source) != null -> "readable"
else -> "refused"
}
w.write("gpu source $source: $state\n")
}
w.write("gpu clock from: ${gpu ?: "nothing readable"}\n") w.write("gpu clock from: ${gpu ?: "nothing readable"}\n")
(probeLines("gpu limit", stepSources, ::firstStep) + probeLines("gpu limit", maxSources, ::limit) +
probeLines("gpu limit", minSources, ::firstStep)).distinct().forEach { w.write(it + "\n") }
limitLines(steps, ceiling, GpuLimits.first(minSources)).forEach { w.write(it + "\n") }
w.flush() w.flush()
while (running && logFile.length() < MAX_BYTES) { while (running && logFile.length() < MAX_BYTES) {
val line = StringBuilder(time.format(Date())) val line = StringBuilder(time.format(Date()))
@@ -63,8 +63,7 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}") line.append(" ${p.name.removePrefix("policy").let { "p$it" }} ${mhz(cur)}/${mhz(max)}")
if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})") if (hw != null && max != null && max < hw) line.append("(of ${mhz(hw)})")
} }
if (ceiling == null) ceiling = ceilingSource(maxSources)?.also { w.write("gpu ceiling from: $it\n") } gpu?.let { line.append(" | gpu ${mhz(firstNumber(it))} MHz") }
line.append(gpuField(gpu, ceiling, steps?.mhz?.last()))
if (power != null && Build.VERSION.SDK_INT >= 29) { if (power != null && Build.VERSION.SDK_INT >= 29) {
line.append(" | thermal ${power.currentThermalStatus}") line.append(" | thermal ${power.currentThermalStatus}")
if (Build.VERSION.SDK_INT >= 30) { if (Build.VERSION.SDK_INT >= 30) {
@@ -110,41 +109,16 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
return list.distinct() return list.distinct()
} }
internal fun probeLines(label: String, sources: List<String>, read: (String) -> Long? = ::firstNumber): List<String> = sources.mapNotNull { source ->
when {
!File(source).exists() -> null
read(source) != null -> "$label $source: readable"
else -> "$label $source: refused"
}
}
internal fun limitLines(steps: GpuLimits.Found?, ceiling: String?, floor: GpuLimits.Found?): List<String> = listOf(
"gpu steps: " + (steps?.let { "${it.mhz.joinToString(" ")} MHz from ${it.path}" } ?: "nothing readable"),
"gpu ceiling from: " + (ceiling ?: "nothing readable"),
"gpu floor: " + (floor?.let { "${it.mhz.first()} MHz from ${it.path}" } ?: "nothing readable"),
)
internal fun gpuField(clock: String?, ceiling: String?, top: Long?): String {
if (clock == null && ceiling == null) return ""
val field = StringBuilder(" | gpu ").append(mhz(clock?.let(::firstNumber)))
ceiling?.let(::limit)?.let { max ->
field.append('/').append(mhz(max))
if (top != null && GpuLimits.mhz(max) < top) field.append("(of $top)")
}
return field.append(" MHz").toString()
}
private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull() private fun File.readTextOrNull(): String? = runCatching { readText() }.getOrNull()
private fun firstNumber(path: String): Long? = private fun firstNumber(path: String): Long? =
runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull() runCatching { Regex("\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
internal fun limit(path: String): Long? = firstNumber(path)?.takeIf { it > 0 } private fun mhz(raw: Long?): String = when {
raw == null -> "?"
internal fun firstStep(path: String): Long? = GpuLimits.read(path).firstOrNull() raw > 10_000_000 -> (raw / 1_000_000).toString()
raw > 10_000 -> (raw / 1_000).toString()
internal fun ceilingSource(sources: List<String>): String? = sources.firstOrNull { limit(it) != null } else -> raw.toString()
}
private fun mhz(raw: Long?): String = raw?.let { GpuLimits.mhz(it).toString() } ?: "?"
} }
} }
@@ -87,10 +87,20 @@ object DeviceInfo {
private fun ghz(khz: Long) = String.format(Locale.US, "%.2f GHz", khz / 1e6) private fun ghz(khz: Long) = String.format(Locale.US, "%.2f GHz", khz / 1e6)
private fun gpuRange(): String? { private fun gpuRange(): String? {
GpuLimits.first(GpuLimits.stepSources())?.mhz?.let { return "${it.first()} MHz–${it.last()} MHz (${it.size} steps)" } fun mhz(hz: Long) = "${hz / 1_000_000} MHz"
val max = GpuLimits.first(GpuLimits.maxSources())?.mhz?.last() ?: return null val kgsl = read("/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies")
val min = GpuLimits.first(GpuLimits.minSources())?.mhz?.first() ?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
return (if (min != null) "$min MHz–" else "up to ") + "$max MHz" if (kgsl.isNotEmpty()) return "${mhz(kgsl.min())}–${mhz(kgsl.max())} (${kgsl.size} steps)"
read("/sys/class/kgsl/kgsl-3d0/max_gpuclk")?.toLongOrNull()?.let { return "up to ${mhz(it)}" }
val node = File("/sys/class/devfreq").listFiles()?.firstOrNull { f ->
val n = f.name.lowercase()
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
} ?: return null
val steps = read("${node.path}/available_frequencies")?.split(Regex("\\s+"))?.mapNotNull { it.toLongOrNull() }?.filter { it > 0 }.orEmpty()
if (steps.isNotEmpty()) return "${mhz(steps.min())}–${mhz(steps.max())} (${steps.size} steps)"
val min = read("${node.path}/min_freq")?.toLongOrNull()
val max = read("${node.path}/max_freq")?.toLongOrNull() ?: return null
return (if (min != null) "${mhz(min)}–" else "up to ") + mhz(max)
} }
private fun memory(context: Context) = Section("Memory", buildList<Pair<String, String>> { private fun memory(context: Context) = Section("Memory", buildList<Pair<String, String>> {
@@ -18,7 +18,6 @@ object DriverPairs {
/** RADV-Xclipse rebased on JimVulkan's upstream: a manual choice, never Auto. */ /** RADV-Xclipse rebased on JimVulkan's upstream: a manual choice, never Auto. */
const val NAD_RADV_XCLIPSE_UPSTREAM = "nad:radv-xclipse-upstream" const val NAD_RADV_XCLIPSE_UPSTREAM = "nad:radv-xclipse-upstream"
private val XCLIPSE_MODEL = Regex("""(?i)xclipse\s*(\d{3})\b""") private val XCLIPSE_MODEL = Regex("""(?i)xclipse\s*(\d{3})\b""")
private val SUPPORTED_XCLIPSE_MODELS = setOf("530", "920", "940")
const val NAD_MALI_JM = "nad:panvk-mali-jm" const val NAD_MALI_JM = "nad:panvk-mali-jm"
const val NAD_MALI_G710 = "nad:panvk-mali-g710" const val NAD_MALI_G710 = "nad:panvk-mali-g710"
const val NAD_MALI_G615 = "nad:panvk-mali-g615" const val NAD_MALI_G615 = "nad:panvk-mali-g615"
@@ -113,12 +112,9 @@ object DriverPairs {
} }
} }
internal fun xclipseNeedsUpstream(name: String): Boolean = /** 950 and 960 panic on the older build; a name without a model number is treated the same way. */
XCLIPSE_MODEL.find(name)?.groupValues?.get(1) !in SUPPORTED_XCLIPSE_MODELS private fun xclipseNeedsUpstream(name: String): Boolean =
XCLIPSE_MODEL.find(name)?.groupValues?.get(1).let { it == null || it == "950" || it == "960" }
fun autoEligible(gpu: GpuInfo, sdk: Int = android.os.Build.VERSION.SDK_INT): Boolean =
recommendedKey(gpu, emptyList(), sdk = sdk) != null ||
(gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true))
fun recommendedKey( fun recommendedKey(
gpu: GpuInfo, pairs: List<DriverPair>, gpu: GpuInfo, pairs: List<DriverPair>,
@@ -129,7 +125,6 @@ object DriverPairs {
Family.POWERVR -> return when { Family.POWERVR -> return when {
!gpu.name.contains("Xclipse", ignoreCase = true) -> null !gpu.name.contains("Xclipse", ignoreCase = true) -> null
xclipseNeedsUpstream(gpu.name) && pairs.any { it.key == NAD_RADV_XCLIPSE_UPSTREAM } -> NAD_RADV_XCLIPSE_UPSTREAM xclipseNeedsUpstream(gpu.name) && pairs.any { it.key == NAD_RADV_XCLIPSE_UPSTREAM } -> NAD_RADV_XCLIPSE_UPSTREAM
xclipseNeedsUpstream(gpu.name) -> null
else -> NAD_RADV_XCLIPSE else -> NAD_RADV_XCLIPSE
} }
Family.MALI_OTHER, Family.NOT_ADRENO -> return null Family.MALI_OTHER, Family.NOT_ADRENO -> return null
@@ -118,7 +118,9 @@ data class GpuInfo(
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo( return GpuInfo(
name = when { name = when {
family == Family.POWERVR -> systemDriverName(SystemVulkanDriver.gpuName(), VulkanInfo.cachedOrNull()) family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
}
mali != null && mali.isNotEmpty() -> mali mali != null && mali.isNotEmpty() -> mali
!adreno -> Build.HARDWARE.ifBlank { UNNAMED } !adreno -> Build.HARDWARE.ifBlank { UNNAMED }
model > 0 -> "Adreno $model" model > 0 -> "Adreno $model"
@@ -132,9 +134,6 @@ data class GpuInfo(
) )
} }
fun systemDriverName(gpu: String, vulkan: Map<String, String>?): String =
vulkan?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
internal fun verifiedOn(model: Int, device: String): Boolean = internal fun verifiedOn(model: Int, device: String): Boolean =
model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true) model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true)
@@ -1,41 +0,0 @@
package com.droiddeck.launcher.gpu
import java.io.File
object GpuLimits {
class Found(val path: String, val mhz: List<Long>)
private const val KGSL = "/sys/class/kgsl/kgsl-3d0"
private const val QCOM_GPU = "/sys/kernel/gpu"
fun stepSources(): List<String> = listOf(
"$KGSL/gpu_available_frequencies", "$KGSL/freq_table_mhz", "$KGSL/devfreq/available_frequencies", "$QCOM_GPU/gpu_freq_table",
) + devfreq("available_frequencies")
fun maxSources(): List<String> = listOf(
"$KGSL/max_gpuclk", "$KGSL/max_clock_mhz", "$KGSL/devfreq/max_freq", "$QCOM_GPU/gpu_max_clock",
) + devfreq("max_freq")
fun minSources(): List<String> = listOf(
"$KGSL/min_clock_mhz", "$KGSL/devfreq/min_freq", "$QCOM_GPU/gpu_min_clock",
) + devfreq("min_freq")
fun first(sources: List<String>): Found? =
sources.firstNotNullOfOrNull { path -> read(path).takeIf { it.isNotEmpty() }?.let { Found(path, it) } }
fun read(path: String): List<Long> = runCatching {
Regex("\\d+").findAll(File(path).readText()).map { mhz(it.value.toLong()) }.filter { it > 0 }.distinct().sorted().toList()
}.getOrDefault(emptyList())
fun mhz(raw: Long): Long = when {
raw > 10_000_000 -> raw / 1_000_000
raw > 10_000 -> raw / 1_000
else -> raw
}
private fun devfreq(file: String): List<String> =
File("/sys/class/devfreq").listFiles()?.filter { f ->
val n = f.name.lowercase()
(n.contains("gpu") || n.contains("mali") || n.contains("kgsl-3d")) && listOf("bus", "bw", "memlat").none { n.contains(it) }
}?.sortedBy { it.name }?.map { "${it.path}/$file" }.orEmpty()
}
@@ -12,7 +12,7 @@ import java.util.function.Supplier;
public final class LinuxVulkanDriver { public final class LinuxVulkanDriver {
private static final String TAG = "LinuxVulkanDriver"; private static final String TAG = "LinuxVulkanDriver";
public static final String ENV = "DD_VK_DRIVER"; public static final String ENV = "BL_VK_DRIVER";
public static final String HELP_TEXT = public static final String HELP_TEXT =
"The driver the Steam client, the games it launches and the desktop's programs render on, " "The driver the Steam client, the games it launches and the desktop's programs render on, "
@@ -16,36 +16,30 @@ data class ScreenEffects(
val hdr: Boolean = false, val hdr: Boolean = false,
val deband: Boolean = false, val deband: Boolean = false,
val debandStrength: Int = 100, val debandStrength: Int = 100,
val aaMode: Int = AA_OFF, val fxaa: Boolean = false,
val toon: Boolean = false, val toon: Boolean = false,
val crt: Boolean = false, val crt: Boolean = false,
val ntsc: Boolean = false, val ntsc: Boolean = false,
) { ) {
val fxaa: Boolean get() = aaMode == AA_FXAA
val smaa: Boolean get() = aaMode == AA_SMAA
val effectiveCas: Int get() = if (cas) casLevel else 0 val effectiveCas: Int get() = if (cas) casLevel else 0
val any: Boolean get() = brightness != 0 || contrast != 0 || abs(gamma - 1f) > 0.005f || saturation != 100 || val any: Boolean get() = brightness != 0 || contrast != 0 || abs(gamma - 1f) > 0.005f || saturation != 100 ||
effectiveCas > 0 || hdr || deband || aaMode != AA_OFF || toon || crt || ntsc effectiveCas > 0 || hdr || deband || fxaa || toon || crt || ntsc
fun push(upscaler: Int) { fun push(upscaler: Int) {
WaylandCompositor.nativeSetCas(cas, casLevel) WaylandCompositor.nativeSetCas(cas, casLevel)
WaylandCompositor.nativeSetHdr(hdr) WaylandCompositor.nativeSetHdr(hdr)
WaylandCompositor.nativeSetDeband(deband, debandStrength) WaylandCompositor.nativeSetDeband(deband, debandStrength)
WaylandCompositor.nativeSetScreenEffects(brightness.toFloat(), contrast.toFloat(), gamma, saturation.toFloat(), aaMode, toon, crt, ntsc) WaylandCompositor.nativeSetScreenEffects(brightness.toFloat(), contrast.toFloat(), gamma, saturation.toFloat(), fxaa, toon, crt, ntsc)
WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(this, upscaler)?.name) WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(this, upscaler)?.name)
} }
fun encode(): JSONObject = JSONObject() fun encode(): JSONObject = JSONObject()
.put("brightness", brightness).put("contrast", contrast).put("gamma", gamma.toDouble()).put("saturation", saturation) .put("brightness", brightness).put("contrast", contrast).put("gamma", gamma.toDouble()).put("saturation", saturation)
.put("cas", cas).put("casLevel", casLevel).put("hdr", hdr).put("deband", deband).put("debandStrength", debandStrength) .put("cas", cas).put("casLevel", casLevel).put("hdr", hdr).put("deband", deband).put("debandStrength", debandStrength)
.put("aaMode", aaMode).put("fxaa", fxaa).put("toon", toon).put("crt", crt).put("ntsc", ntsc) .put("fxaa", fxaa).put("toon", toon).put("crt", crt).put("ntsc", ntsc)
companion object { companion object {
const val AA_OFF = 0
const val AA_FXAA = 1
const val AA_SMAA = 2
val OFF = ScreenEffects() val OFF = ScreenEffects()
fun decode(json: JSONObject): ScreenEffects = ScreenEffects( fun decode(json: JSONObject): ScreenEffects = ScreenEffects(
@@ -58,7 +52,7 @@ data class ScreenEffects(
hdr = json.optBoolean("hdr", false), hdr = json.optBoolean("hdr", false),
deband = json.optBoolean("deband", false), deband = json.optBoolean("deband", false),
debandStrength = json.optInt("debandStrength", 100).coerceIn(0, 200), debandStrength = json.optInt("debandStrength", 100).coerceIn(0, 200),
aaMode = json.optInt("aaMode", if (json.optBoolean("fxaa", false)) AA_FXAA else AA_OFF).coerceIn(AA_OFF, AA_SMAA), fxaa = json.optBoolean("fxaa", false),
toon = json.optBoolean("toon", false), toon = json.optBoolean("toon", false),
crt = json.optBoolean("crt", false), crt = json.optBoolean("crt", false),
ntsc = json.optBoolean("ntsc", false), ntsc = json.optBoolean("ntsc", false),
@@ -85,13 +79,13 @@ object ScreenEffectLooks {
desc = "Sharpening with a touch of contrast - the everyday one.", label = R.string.look_game_clarity, descRes = R.string.look_game_clarity_desc), desc = "Sharpening with a touch of contrast - the everyday one.", label = R.string.look_game_clarity, descRes = R.string.look_game_clarity_desc),
Look("Vivid", ScreenEffects(brightness = 3, contrast = 10, gamma = 0.98f, saturation = 145, cas = true, casLevel = 30, deband = true), Look("Vivid", ScreenEffects(brightness = 3, contrast = 10, gamma = 0.98f, saturation = 145, cas = true, casLevel = 30, deband = true),
desc = "Colour pushed hard. Deband on so skies don't stripe.", label = R.string.look_vivid, descRes = R.string.look_vivid_desc), desc = "Colour pushed hard. Deband on so skies don't stripe.", label = R.string.look_vivid, descRes = R.string.look_vivid_desc),
Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, aaMode = ScreenEffects.AA_FXAA, deband = true), Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, fxaa = true, deband = true),
desc = "Deeper contrast, cooler colour, edges smoothed.", label = R.string.look_cinematic, descRes = R.string.look_cinematic_desc), desc = "Deeper contrast, cooler colour, edges smoothed.", label = R.string.look_cinematic, descRes = R.string.look_cinematic_desc),
Look("Competitive", ScreenEffects(brightness = 16, contrast = 18, gamma = 0.92f, saturation = 82, cas = true, casLevel = 75), Look("Competitive", ScreenEffects(brightness = 16, contrast = 18, gamma = 0.92f, saturation = 82, cas = true, casLevel = 75),
desc = "Shadows lifted and heavy sharpening - spot people first.", label = R.string.look_competitive, descRes = R.string.look_competitive_desc), desc = "Shadows lifted and heavy sharpening - spot people first.", label = R.string.look_competitive, descRes = R.string.look_competitive_desc),
Look("Adaptive Sharpen", ScreenEffects(cas = true, casLevel = 85), Look("Adaptive Sharpen", ScreenEffects(cas = true, casLevel = 85),
desc = "Sharpening only, colour untouched.", label = R.string.look_adaptive_sharpen, descRes = R.string.look_adaptive_sharpen_desc), desc = "Sharpening only, colour untouched.", label = R.string.look_adaptive_sharpen, descRes = R.string.look_adaptive_sharpen_desc),
Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, aaMode = ScreenEffects.AA_FXAA, deband = true), Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, fxaa = true, deband = true),
desc = "Film-like curve, slightly muted.", label = R.string.look_filmic, descRes = R.string.look_filmic_desc), desc = "Film-like curve, slightly muted.", label = R.string.look_filmic, descRes = R.string.look_filmic_desc),
Look("Arcade", ScreenEffects(brightness = 6, contrast = 20, gamma = 0.95f, saturation = 170, cas = true, casLevel = 45, deband = true), Look("Arcade", ScreenEffects(brightness = 6, contrast = 20, gamma = 0.95f, saturation = 170, cas = true, casLevel = 45, deband = true),
desc = "Loud and punchy.", label = R.string.look_arcade, descRes = R.string.look_arcade_desc), desc = "Loud and punchy.", label = R.string.look_arcade, descRes = R.string.look_arcade_desc),
@@ -109,7 +103,7 @@ object ScreenEffectLooks {
val t = l.effects val t = l.effects
t.brightness == e.brightness && t.contrast == e.contrast && abs(t.gamma - e.gamma) < 0.005f && t.brightness == e.brightness && t.contrast == e.contrast && abs(t.gamma - e.gamma) < 0.005f &&
t.saturation == e.saturation && t.effectiveCas == e.effectiveCas && t.saturation == e.saturation && t.effectiveCas == e.effectiveCas &&
t.aaMode == e.aaMode && t.crt == e.crt && t.toon == e.toon && t.ntsc == e.ntsc && t.deband == e.deband && t.fxaa == e.fxaa && t.crt == e.crt && t.toon == e.toon && t.ntsc == e.ntsc && t.deband == e.deband &&
(l.scalingMode == null || l.scalingMode == upscaler) (l.scalingMode == null || l.scalingMode == upscaler)
} }
} }
@@ -256,12 +256,12 @@ public final class SystemVulkanDriver {
if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2"); if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2");
// The Android driver has a render node, but no KMS primary node. SDL presents // The Android driver has a render node, but no KMS primary node. SDL presents
// through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path. // through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path.
environment.add("DD_GAMESCOPE_BACKEND=sdl"); environment.add("BL_GAMESCOPE_BACKEND=sdl");
// The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles. // The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles.
environment.add("DD_POWERVR_DRM_HANDLES=1"); environment.add("BL_POWERVR_DRM_HANDLES=1");
environment.add("DD_POWERVR_RENDER_NODE=" + node); environment.add("BL_POWERVR_RENDER_NODE=" + node);
// Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols. // Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols.
environment.add("DD_STEAM_GL_PRESENT=1"); environment.add("BL_STEAM_GL_PRESENT=1");
// Only actual Proton game launches use the bundled DXVK and X11 WSI layer. // Only actual Proton game launches use the bundled DXVK and X11 WSI layer.
environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath()); environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath());
} }
@@ -5,7 +5,7 @@ import com.droiddeck.launcher.session.SessionPrefs
internal object DroidDeckHudConfig { internal object DroidDeckHudConfig {
val DEFAULTS: Map<String, String> = linkedMapOf( val DEFAULTS: Map<String, String> = linkedMapOf(
"hudSize" to "minimal", "hudLocked" to "1", "hudHold" to "collapse", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid", "hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
"hudOutline" to "40", "hudOutlineAccent" to "1", "hudOutline" to "40", "hudOutlineAccent" to "1",
"showGpuModel" to "1", "showGPULoad" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGpuModel" to "1", "showGPULoad" to "1", "showCPUUsage" to "1", "showCPULoad" to "1",
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0", "showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
@@ -18,8 +18,6 @@ internal object DroidDeckHudConfig {
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48", "tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
) )
const val HOLD_LOCKS = "lock"
private val NOT_READINGS = setOf("showCPULoad", "showRenderer", "fpsDecimal") private val NOT_READINGS = setOf("showCPULoad", "showRenderer", "fpsDecimal")
/** Orders saved before the GPU switch was named after the alias the HUD actually reads. */ /** Orders saved before the GPU switch was named after the alias the HUD actually reads. */
@@ -119,7 +119,6 @@ class DroidDeckHudHost(context: Context) {
} }
hud.setOnSizeCycledListener { size -> DroidDeckHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() } hud.setOnSizeCycledListener { size -> DroidDeckHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
hud.setOnDockChangedListener { token -> setDock(hud, DroidDeckHudDock.from(token)) } hud.setOnDockChangedListener { token -> setDock(hud, DroidDeckHudDock.from(token)) }
hud.setOnHoldListener { rawX, rawY -> collapseAt(hud, rawX, rawY) }
hud.setOnScaledListener { percent -> hud.setOnScaledListener { percent ->
DroidDeckHudConfig.set(context, "hudScale", percent.toString()) DroidDeckHudConfig.set(context, "hudScale", percent.toString())
onConfigChanged?.invoke() onConfigChanged?.invoke()
@@ -292,7 +291,7 @@ class DroidDeckHudHost(context: Context) {
DroidDeckHudDock.RIGHT -> (maxX - hud.x) / hud.width DroidDeckHudDock.RIGHT -> (maxX - hud.x) / hud.width
DroidDeckHudDock.TOP -> hud.y / hud.height DroidDeckHudDock.TOP -> hud.y / hud.height
DroidDeckHudDock.BOTTOM -> (maxY - hud.y) / hud.height DroidDeckHudDock.BOTTOM -> (maxY - hud.y) / hud.height
DroidDeckHudDock.NONE, DroidDeckHudDock.FLOAT -> 0f DroidDeckHudDock.NONE -> 0f
} }
if (pulled >= 1f) { setDock(hud, DroidDeckHudDock.NONE); return } if (pulled >= 1f) { setDock(hud, DroidDeckHudDock.NONE); return }
wantX = hud.x; wantY = hud.y wantX = hud.x; wantY = hud.y
@@ -376,30 +375,12 @@ class DroidDeckHudHost(context: Context) {
hud.scaleX = s; hud.scaleY = s hud.scaleX = s; hud.scaleY = s
} }
private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, center: Pair<Float, Float>? = null) { private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
if (edge == hud.dock) return if (edge == hud.dock) return
animateDock(hud, edge, center) { commitDock(hud, edge) } animateDock(hud, edge) { commitDock(hud, edge) }
} }
private fun collapseAt(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
if (hud.dock != DroidDeckHudDock.NONE) return
val p = hud.parent as? View ?: return
val at = IntArray(2).also { p.getLocationOnScreen(it) }
val x = rawX - at[0]
val y = rawY - at[1]
val edge = if (snaps) nearestEdge(x, y, p.width.toFloat(), p.height.toFloat()) else DroidDeckHudDock.FLOAT
setDock(hud, edge, Pair(x, y))
}
private fun nearestEdge(x: Float, y: Float, width: Float, height: Float): DroidDeckHudDock = mapOf(
DroidDeckHudDock.LEFT to x,
DroidDeckHudDock.RIGHT to width - x,
DroidDeckHudDock.TOP to y,
DroidDeckHudDock.BOTTOM to height - y,
).minByOrNull { it.value }!!.key
private fun commitDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) { private fun commitDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
snapping = false
val tabX = hud.x; val tabY = hud.y val tabX = hud.x; val tabY = hud.y
if (edge != DroidDeckHudDock.NONE) { if (edge != DroidDeckHudDock.NONE) {
val p = hud.parent as? View val p = hud.parent as? View
@@ -426,17 +407,12 @@ class DroidDeckHudHost(context: Context) {
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY) SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
} }
private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, center: Pair<Float, Float>?, commit: () -> Unit) { private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, commit: () -> Unit) {
stopMotion(hud) stopMotion(hud)
previewFade?.cancel(); previewFade = null previewFade?.cancel(); previewFade = null
snapping = false snapping = false
hud.alpha = 1f hud.alpha = 1f
val p = hud.parent as? View val p = hud.parent as? View
if (edge != DroidDeckHudDock.NONE && center != null) {
val (tabW, tabH) = hud.dockTabSize()
wantX = center.first - tabW / 2f
wantY = center.second - tabH / 2f
}
if (Motion.scale == 0f || p == null || !hud.isLaidOut || hud.width <= 0) { if (Motion.scale == 0f || p == null || !hud.isLaidOut || hud.width <= 0) {
hud.scaleX = 1f; hud.scaleY = 1f hud.scaleX = 1f; hud.scaleY = 1f
hud.setDockPreview(DroidDeckHudDock.NONE, 0f) hud.setDockPreview(DroidDeckHudDock.NONE, 0f)
@@ -448,14 +424,11 @@ class DroidDeckHudHost(context: Context) {
hud.pivotX = 0f; hud.pivotY = 0f hud.pivotX = 0f; hud.pivotY = 0f
hud.x = left; hud.y = top hud.x = left; hud.y = top
val (tabW, tabH) = hud.dockTabSize() val (tabW, tabH) = hud.dockTabSize()
if (center == null) { wantX = left + (shownW - tabW) / 2f
wantX = left + (shownW - tabW) / 2f wantY = top + (shownH - tabH) / 2f
wantY = top + (shownH - tabH) / 2f
}
val (tabX, tabY) = settled(p, edge, tabW, tabH) val (tabX, tabY) = settled(p, edge, tabW, tabH)
val sx = tabW / hud.width; val sy = tabH / hud.height val sx = tabW / hud.width; val sy = tabH / hud.height
val from = hud.dockPreviewBlend val from = hud.dockPreviewBlend
snapping = true
hud.animate().x(tabX).y(tabY).scaleX(sx).scaleY(sy).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE) hud.animate().x(tabX).y(tabY).scaleX(sx).scaleY(sy).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE)
.setUpdateListener { hud.setDockPreview(edge, from + (1f - from) * it.animatedFraction) } .setUpdateListener { hud.setDockPreview(edge, from + (1f - from) * it.animatedFraction) }
.withEndAction { .withEndAction {
@@ -500,7 +473,7 @@ class DroidDeckHudHost(context: Context) {
DroidDeckHudDock.RIGHT -> x = maxX DroidDeckHudDock.RIGHT -> x = maxX
DroidDeckHudDock.TOP -> y = 0f DroidDeckHudDock.TOP -> y = 0f
DroidDeckHudDock.BOTTOM -> y = maxY DroidDeckHudDock.BOTTOM -> y = maxY
DroidDeckHudDock.NONE, DroidDeckHudDock.FLOAT -> {} DroidDeckHudDock.NONE -> {}
} }
return Pair(x, y) return Pair(x, y)
} }
@@ -118,7 +118,7 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
} }
enum class DroidDeckHudDock(val token: String) { enum class DroidDeckHudDock(val token: String) {
NONE("none"), LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom"), FLOAT("float"); NONE("none"), LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom");
companion object { companion object {
fun from(token: String?): DroidDeckHudDock = values().firstOrNull { it.token == token } ?: NONE fun from(token: String?): DroidDeckHudDock = values().firstOrNull { it.token == token } ?: NONE
@@ -191,8 +191,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private var onMovedListener: BiConsumer<Float, Float>? = null private var onMovedListener: BiConsumer<Float, Float>? = null
private var onSizeCycledListener: Consumer<String>? = null private var onSizeCycledListener: Consumer<String>? = null
private var onLockChangedListener: Consumer<Boolean>? = null private var onLockChangedListener: Consumer<Boolean>? = null
private var onHoldListener: BiConsumer<Float, Float>? = null
fun setOnHoldListener(l: BiConsumer<Float, Float>?) { onHoldListener = l }
fun setOnMovedListener(l: BiConsumer<Float, Float>?) { onMovedListener = l } fun setOnMovedListener(l: BiConsumer<Float, Float>?) { onMovedListener = l }
fun setOnSizeCycledListener(l: Consumer<String>?) { onSizeCycledListener = l } fun setOnSizeCycledListener(l: Consumer<String>?) { onSizeCycledListener = l }
fun setOnLockChangedListener(l: Consumer<Boolean>?) { onLockChangedListener = l } fun setOnLockChangedListener(l: Consumer<Boolean>?) { onLockChangedListener = l }
@@ -211,7 +209,6 @@ class DroidDeckHudView(context: Context) : View(context) {
override fun onDragged(rawX: Float, rawY: Float) { onDraggedListener?.accept(rawX, rawY) } override fun onDragged(rawX: Float, rawY: Float) { onDraggedListener?.accept(rawX, rawY) }
override fun onFlung(velocityX: Float, velocityY: Float) { onFlungListener?.accept(velocityX, velocityY) } override fun onFlung(velocityX: Float, velocityY: Float) { onFlungListener?.accept(velocityX, velocityY) }
override fun onLockChanged(locked: Boolean) { onLockChangedListener?.accept(locked) } override fun onLockChanged(locked: Boolean) { onLockChangedListener?.accept(locked) }
override fun onHold(rawX: Float, rawY: Float) { onHoldListener?.accept(rawX, rawY) }
override fun onPinch(factor: Float) { override fun onPinch(factor: Float) {
val next = (scale * factor).coerceIn(MIN_SCALE, MAX_SCALE) val next = (scale * factor).coerceIn(MIN_SCALE, MAX_SCALE)
if (next == scale) return if (next == scale) return
@@ -227,7 +224,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private var tabStartX = 0f private var tabStartX = 0f
private var tabStartY = 0f private var tabStartY = 0f
private var tabDragging = false private var tabDragging = false
private var tabPressed = false
private var onTabDraggedListener: BiConsumer<Float, Float>? = null private var onTabDraggedListener: BiConsumer<Float, Float>? = null
private var onTabDroppedListener: Runnable? = null private var onTabDroppedListener: Runnable? = null
private var onTabDragCancelledListener: Runnable? = null private var onTabDragCancelledListener: Runnable? = null
@@ -241,24 +237,19 @@ class DroidDeckHudView(context: Context) : View(context) {
tabDownRawX = event.rawX; tabDownRawY = event.rawY tabDownRawX = event.rawX; tabDownRawY = event.rawY
tabStartX = x; tabStartY = y tabStartX = x; tabStartY = y
tabDragging = false tabDragging = false
tabPressed = true
} }
MotionEvent.ACTION_MOVE -> if (tabPressed) { MotionEvent.ACTION_MOVE -> {
val dx = event.rawX - tabDownRawX; val dy = event.rawY - tabDownRawY val dx = event.rawX - tabDownRawX; val dy = event.rawY - tabDownRawY
if (!tabDragging && dx * dx + dy * dy > touchSlop * touchSlop) tabDragging = true if (!tabDragging && dx * dx + dy * dy > touchSlop * touchSlop) tabDragging = true
if (tabDragging) onTabDraggedListener?.accept(tabStartX + dx, tabStartY + dy) if (tabDragging) onTabDraggedListener?.accept(tabStartX + dx, tabStartY + dy)
} }
MotionEvent.ACTION_UP -> if (tabPressed) { MotionEvent.ACTION_UP -> {
tabPressed = false
if (tabDragging) { tabDragging = false; onTabDroppedListener?.run() } if (tabDragging) { tabDragging = false; onTabDroppedListener?.run() }
else onDockChangedListener?.accept(DroidDeckHudDock.NONE.token) else onDockChangedListener?.accept(DroidDeckHudDock.NONE.token)
} }
MotionEvent.ACTION_CANCEL -> { MotionEvent.ACTION_CANCEL -> if (tabDragging) {
tabPressed = false tabDragging = false
if (tabDragging) { onTabDragCancelledListener?.run()
tabDragging = false
onTabDragCancelledListener?.run()
}
} }
} }
return true return true
@@ -350,7 +341,6 @@ class DroidDeckHudView(context: Context) : View(context) {
showSession = switchOn("showSession") showSession = switchOn("showSession")
tempDisplay = HudMetrics.TempDisplay.from(cfg) tempDisplay = HudMetrics.TempDisplay.from(cfg)
lockController.setLocked(cfg.get("hudLocked", "1") == "1") lockController.setLocked(cfg.get("hudLocked", "1") == "1")
lockController.setHoldLocks(cfg.get("hudHold", "collapse") == DroidDeckHudConfig.HOLD_LOCKS)
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none")) dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
colorIntensity = when (cfg.get("hudColor", "vivid")) { colorIntensity = when (cfg.get("hudColor", "vivid")) {
@@ -601,7 +591,7 @@ class DroidDeckHudView(context: Context) : View(context) {
DroidDeckHudDock.RIGHT -> intArrayOf(1, 2) DroidDeckHudDock.RIGHT -> intArrayOf(1, 2)
DroidDeckHudDock.TOP -> intArrayOf(0, 1) DroidDeckHudDock.TOP -> intArrayOf(0, 1)
DroidDeckHudDock.BOTTOM -> intArrayOf(2, 3) DroidDeckHudDock.BOTTOM -> intArrayOf(2, 3)
DroidDeckHudDock.NONE, DroidDeckHudDock.FLOAT -> intArrayOf() DroidDeckHudDock.NONE -> intArrayOf()
} }
for (corner in edge) { round[corner * 2] = 0f; round[corner * 2 + 1] = 0f } for (corner in edge) { round[corner * 2] = 0f; round[corner * 2 + 1] = 0f }
tabPath.rewind() tabPath.rewind()
@@ -275,7 +275,7 @@ internal class GameFrameFeed(
private const val INFO_NS = 500_000_000L private const val INFO_NS = 500_000_000L
private const val SHIFT_NS = 1_000_000_000L private const val SHIFT_NS = 1_000_000_000L
private const val SHIFT_RECHECK_NS = 100_000_000L private const val SHIFT_RECHECK_NS = 100_000_000L
private const val CLOCK_CONTROL_PATH = "tmp/.dd-clock" private const val CLOCK_CONTROL_PATH = "tmp/.bl-clock"
fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH)) fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH))
@@ -36,7 +36,6 @@ public class HudLockController {
default void onDragged(float rawX, float rawY) {} default void onDragged(float rawX, float rawY) {}
default void onFlung(float velocityX, float velocityY) {} default void onFlung(float velocityX, float velocityY) {}
void onLockChanged(boolean locked); void onLockChanged(boolean locked);
default void onHold(float rawX, float rawY) {}
default void onPinch(float factor) {} default void onPinch(float factor) {}
default void onPinchEnd() {} default void onPinchEnd() {}
} }
@@ -54,7 +53,6 @@ public class HudLockController {
private final android.view.VelocityTracker velocity = android.view.VelocityTracker.obtain(); private final android.view.VelocityTracker velocity = android.view.VelocityTracker.obtain();
private boolean locked = false; private boolean locked = false;
private boolean holdLocks = false;
private float downRawX, downRawY, startX, startY; private float downRawX, downRawY, startX, startY;
private boolean dragging = false; private boolean dragging = false;
@@ -82,8 +80,6 @@ public class HudLockController {
public void setLocked(boolean locked) { this.locked = locked; } public void setLocked(boolean locked) { this.locked = locked; }
public void setHoldLocks(boolean holdLocks) { this.holdLocks = holdLocks; }
public boolean isLocked() { return locked; } public boolean isLocked() { return locked; }
public boolean isDragging() { return dragging; } public boolean isDragging() { return dragging; }
@@ -123,10 +119,6 @@ public class HudLockController {
@Override @Override
public void onLongPress(MotionEvent e) { public void onLongPress(MotionEvent e) {
if (!holdLocks) {
cb.onHold(e.getRawX(), e.getRawY());
return;
}
locked = !locked; locked = !locked;
cb.onLockChanged(locked); cb.onLockChanged(locked);
flash(locked, HOLD_TOGGLE_MS); flash(locked, HOLD_TOGGLE_MS);
@@ -7,6 +7,21 @@ object ControllerPrefs {
const val STEAM_BLUE = 0xFF1A9FFF.toInt() const val STEAM_BLUE = 0xFF1A9FFF.toInt()
const val OFF = "off" const val OFF = "off"
val tints = listOf(
STEAM_BLUE to R.string.ctrl_tint_steam_blue,
0xFF66C0F4.toInt() to R.string.ctrl_tint_sky,
0xFFE8EEF4.toInt() to R.string.ctrl_tint_white,
0xFFC77DFF.toInt() to R.string.ctrl_tint_violet,
0xFF3DDC84.toInt() to R.string.ctrl_tint_green,
0xFFFFA726.toInt() to R.string.ctrl_tint_amber,
0xFFFF5252.toInt() to R.string.ctrl_tint_red,
0xFFFF6FB5.toInt() to R.string.ctrl_tint_pink,
)
val opacities = listOf(40, 60, 80, 100)
val sizes = listOf(80, 90, 100, 110, 125)
val deadZones = listOf(0, 5, 8, 12, 15, 20, 25) val deadZones = listOf(0, 5, 8, 12, 15, 20, 25)
const val DEFAULT_DEAD_ZONE_PERCENT = 12 const val DEFAULT_DEAD_ZONE_PERCENT = 12
@@ -24,15 +39,20 @@ object ControllerPrefs {
OFF to R.string.ctrl_target_hidden, OFF to R.string.ctrl_target_hidden,
) )
/** Settings still read: the rest only seed the one-time library and layout migrations. */
class Settings( class Settings(
val tint: Int, val tint: Int,
val opacity: Int, val opacity: Int,
val size: Int,
val stickClick: Boolean, val stickClick: Boolean,
val adaptiveSticks: Boolean,
val rumble: Boolean, val rumble: Boolean,
val steamButton: Boolean,
val qamButton: Boolean,
val keyboardButton: Boolean,
val selectSteam: Boolean, val selectSteam: Boolean,
val joyConVr: Boolean, val joyConVr: Boolean,
val snap: Boolean, val snap: Boolean,
val customLayout: Boolean,
val mapping: Map<String, String>, val mapping: Map<String, String>,
val deadZone: Int, val deadZone: Int,
) )
@@ -43,17 +63,50 @@ object ControllerPrefs {
val p = prefs(context) val p = prefs(context)
return Settings( return Settings(
tint = p.getInt("tint", STEAM_BLUE), tint = p.getInt("tint", STEAM_BLUE),
opacity = p.getInt("opacity", 100).coerceIn(1, 100), opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100,
size = p.getInt("size", 100).takeIf { it in sizes } ?: 100,
stickClick = p.getBoolean("stickClick", true), stickClick = p.getBoolean("stickClick", true),
adaptiveSticks = p.getBoolean("adaptiveSticks", true),
rumble = rumbleEnabled(context), rumble = rumbleEnabled(context),
steamButton = p.getBoolean("steamButton", true),
qamButton = p.getBoolean("qamButton", true),
keyboardButton = p.getBoolean("keyboardButton", true),
selectSteam = p.getBoolean("selectSteam", false), selectSteam = p.getBoolean("selectSteam", false),
joyConVr = joyConVr(context), joyConVr = joyConVr(context),
snap = snap(context), snap = snap(context),
mapping = mappable.associate { (id, _) -> id to (p.getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id) }, customLayout = p.all.keys.any { it.startsWith("layout.") },
mapping = mappable.associate { (id, _) -> id to target(context, id) },
deadZone = deadZone(context), deadZone = deadZone(context),
) )
} }
fun target(context: Context, id: String): String =
prefs(context).getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id
fun setTarget(context: Context, id: String, target: String) {
prefs(context).edit().putString("map.$id", target).apply()
}
fun setTint(context: Context, tint: Int) {
prefs(context).edit().putInt("tint", tint).apply()
}
fun setOpacity(context: Context, percent: Int) {
prefs(context).edit().putInt("opacity", percent).apply()
}
fun setSize(context: Context, percent: Int) {
prefs(context).edit().putInt("size", percent).apply()
}
fun setStickClick(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("stickClick", on).apply()
}
fun setAdaptiveSticks(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
}
fun rumbleEnabled(context: Context): Boolean = prefs(context).getBoolean("rumble", true) fun rumbleEnabled(context: Context): Boolean = prefs(context).getBoolean("rumble", true)
fun deadZone(context: Context): Int = fun deadZone(context: Context): Int =
@@ -67,6 +120,18 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("rumble", on).apply() prefs(context).edit().putBoolean("rumble", on).apply()
} }
fun setSteamButton(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("steamButton", on).apply()
}
fun setKeyboardButton(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("keyboardButton", on).apply()
}
fun setSelectSteam(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("selectSteam", on).apply()
}
fun joyConVr(context: Context): Boolean = prefs(context).getBoolean("joyConVr", true) fun joyConVr(context: Context): Boolean = prefs(context).getBoolean("joyConVr", true)
fun setJoyConVr(context: Context, on: Boolean) { fun setJoyConVr(context: Context, on: Boolean) {
@@ -79,6 +144,24 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("snap", on).apply() prefs(context).edit().putBoolean("snap", on).apply()
} }
fun layout(context: Context, width: Int, height: Int): Map<String, Pair<Float, Float>> {
val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap()
return raw.split(';').mapNotNull { entry ->
val (group, pos) = entry.split(':').takeIf { it.size == 2 } ?: return@mapNotNull null
val (x, y) = pos.split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 2 } ?: return@mapNotNull null
group to (x to y)
}.toMap()
}
fun setLayout(context: Context, width: Int, height: Int, positions: Map<String, Pair<Float, Float>>) {
val raw = positions.entries.joinToString(";") { (group, pos) -> "$group:${pos.first},${pos.second}" }
prefs(context).edit().putString("layout.${width}x$height", raw).apply()
}
fun resetLayout(context: Context, width: Int, height: Int) {
prefs(context).edit().remove("layout.${width}x$height").apply()
}
fun resetAll(context: Context) { fun resetAll(context: Context) {
prefs(context).edit().clear().putBoolean("rumble", true).apply() prefs(context).edit().clear().putBoolean("rumble", true).apply()
} }
@@ -1,123 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/** The on-screen layout each game draws, shared by the in-game Controller page and Settings › Controller. A null game is the default. */
object ControlsChoice {
const val NEW = "new"
const val DEFAULT = "default"
data class Game(val id: Long, val name: String, val layout: String)
private fun own(library: InputLibrary, id: String?): String? = id?.takeIf { bindings ->
library.bindings.any { it.id == bindings && !it.physical && it.layoutId?.let { l -> library.layouts.any { x -> x.id == l && x.supports(InputRole.PRIMARY) } } == true }
}
private fun own(context: Context, library: InputLibrary, game: Long?) = own(library, GameControls.bindings(context, game))
/** The input library with [game]'s main-screen layout selected, without saving it. */
fun library(context: Context, game: Long?, desktop: Boolean): InputLibrary {
val library = InputLibraries.read(context)
val chosen = own(context, library, game)
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
}
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null): List<Pair<String, String>> {
val library = InputLibraries.read(context)
val own = game != null && game in GameControls.games(context)
return (if (own) listOf(DEFAULT to context.getString(R.string.osc_default)) else emptyList()) +
listOf(InputLibraries.OVERLAY to context.getString(R.string.osc_layout_gamepad)) +
(if (steamMode) listOf(GameControls.STEAM to context.getString(R.string.osc_layout_steam)) else emptyList()) +
library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }.map { it.id to it.name } +
(if (game != null && !gameName.isNullOrBlank()) listOf(NEW to context.getString(R.string.osc_layout_new_for, gameName)) else emptyList())
}
fun current(context: Context, game: Long?, steamMode: Boolean, desktop: Boolean = false): String =
if (steamMode && GameControls.steamLayout(context, game)) GameControls.STEAM
else library(context, game, desktop).activeLayout(desktop, InputRole.PRIMARY)?.id ?: InputLibraries.OVERLAY
fun choose(context: Context, game: Long?, id: String, desktop: Boolean, gameName: String? = null) {
require(id != NEW)
if (id == DEFAULT) { if (game != null) useDefault(context, game); return }
val steam = id == GameControls.STEAM
val bindings = if (steam) null else {
val library = InputLibraries.read(context)
val layout = library.layouts.first { it.id == id }
library.bindings.firstOrNull { !it.physical && it.layoutId == layout.id && it.compatible(layout) }?.id ?: newInputId().also { newId ->
InputLibraries.update(context) { it.withPreset(SavedInputBindings(newId, layout.name, false, layout.id)) }
}
}
if (game != null) GameControls.choose(context, game, bindings, steam, gameName)
else {
if (bindings != null) InputLibraries.update(context) { it.selectPart(desktop, InputRole.PRIMARY, bindings) }
SessionPrefs.setSteamTouchLayout(context, steam)
}
}
/** Copies the layout [game] draws now, actions included, into a layout of its own and chooses it for that game only. */
fun newForGame(context: Context, game: Long, name: String, desktop: Boolean): Pair<String, String> {
val layoutId = newInputId()
val bindingsId = newInputId()
InputLibraries.update(context) { latest -> copyForGame(context, latest, game, name, desktop, layoutId, bindingsId) }
GameControls.choose(context, game, bindingsId, steam = false, name = name)
return layoutId to bindingsId
}
/** [latest] with a copy of the layout [game] draws now, actions included, under the given ids. Nothing is chosen for the game. */
fun copyForGame(context: Context, latest: InputLibrary, game: Long, name: String, desktop: Boolean, layoutId: String, bindingsId: String): InputLibrary {
run {
val chosen = own(context, latest, game)
val part = (if (chosen == null) latest else latest.selectPart(desktop, InputRole.PRIMARY, chosen)).activePart(desktop, InputRole.PRIMARY)
val source = latest.layouts.firstOrNull { it.id == part.layout && it.editable } ?: latest.layouts.first { it.id == InputLibraries.OVERLAY }
val actions = latest.bindings.firstOrNull { it.id == part.bindings && it.compatible(source) }
?: latest.bindings.firstOrNull { !it.physical && it.compatible(source) }
?: SavedInputBindings(bindingsId, source.name, false, source.id)
val title = name.trim().take(80).ifEmpty { source.name }
return latest.withLayout(source.derived(layoutId, title)).withPreset(actions.copy(id = bindingsId, name = title, layoutId = layoutId))
}
}
/** Uses [bindingsId], made by [copyForGame], for [game] only. */
fun useForGame(context: Context, game: Long, name: String, bindingsId: String) = GameControls.choose(context, game, bindingsId, steam = false, name = name)
/** The profile, layout and actions the editor opens for [game], or null when its layout can't be edited here. */
fun editTarget(context: Context, game: Long?, desktop: Boolean): Triple<String, String, String>? {
val library = library(context, game, desktop)
val layout = library.activeLayout(desktop, InputRole.PRIMARY)?.takeIf { it.editable } ?: return null
return Triple(library.activeId(desktop), layout.id, library.activePart(desktop, InputRole.PRIMARY).bindings)
}
/** Whether [game] has a layout of its own, rather than the default. */
fun hasOwn(context: Context, game: Long?): Boolean = own(context, InputLibraries.read(context), game) != null
/** Whether saving an edit of [game]'s layout would also change the default or another game. */
fun shared(context: Context, game: Long?): Boolean {
game ?: return false
val library = InputLibraries.read(context)
val bindings = own(context, library, game) ?: return true
val layout = library.preset(bindings).layoutId
fun drawsLayout(id: String) = library.bindings.firstOrNull { it.id == id }?.layoutId == layout
return library.usersOfLayout(layout ?: return true).isNotEmpty() ||
library.selections.values.any { s -> s.parts[InputRole.PRIMARY]?.let(::drawsLayout) == true } ||
GameControls.games(context).any { it != game && own(context, library, it)?.let(::drawsLayout) == true }
}
fun useDefault(context: Context, game: Long) = GameControls.clear(context, game)
/** Games with a layout of their own, by name. */
fun games(context: Context): List<Game> {
val library = InputLibraries.read(context)
return GameControls.games(context).mapNotNull { id ->
val layout = when {
GameControls.steamLayout(context, id) -> context.getString(R.string.osc_layout_steam)
else -> own(context, library, id)?.let { b -> library.layouts.firstOrNull { it.id == library.preset(b).layoutId }?.name } ?: return@mapNotNull null
}
val name = GameControls.name(context, id)
?: id.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.let { runCatching { SteamTouchConfig.gameName(context, it.toInt()) }.getOrNull() }
?: id.toString()
Game(id, name, layout)
}.sortedBy { it.name.lowercase() }
}
}
@@ -1,40 +0,0 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
/** Decides where the on-screen controls go and why they're hidden, from the session's state alone. */
object ControlsPresenter {
enum class Place { NONE, MAIN, BOTTOM, STEAM }
data class State(
val mode: String,
val desktop: Boolean,
val virtualPad: Boolean,
val covered: Boolean,
val controllerInUse: Boolean,
val hiddenByTap: Boolean,
val steamLayout: Boolean,
val bottomScreen: Boolean,
)
data class Plan(val place: Place, val hidden: OnScreenControls.Hidden? = null) {
val shown get() = place != Place.NONE && hidden == null
}
fun plan(state: State): Plan = when {
state.covered || !state.virtualPad || state.mode == SessionPrefs.OSC_NEVER -> Plan(Place.NONE)
state.mode == SessionPrefs.OSC_AUTO && state.desktop -> Plan(Place.NONE)
else -> Plan(
when {
state.bottomScreen -> Place.BOTTOM
state.steamLayout -> Place.STEAM
else -> Place.MAIN
},
when {
state.hiddenByTap -> OnScreenControls.Hidden.BY_TAP
state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse -> OnScreenControls.Hidden.BY_CONTROLLER
else -> null
},
)
}
}
@@ -82,12 +82,6 @@ object DualScreen {
fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? = fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context)) display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context))
fun selectedSessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, selectedDisplayId: Int): Display? =
displayManager.getDisplay(selectedDisplayId)?.takeIf {
SessionPrefs.dualScreenSessionMode(context) != MODE_OFF && it.isValid && it.displayId != primaryDisplayId &&
(it.flags and Display.FLAG_PRESENTATION) != 0 && !taken(it.displayId)
}
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? = fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
when (mode) { when (mode) {
MODE_OFF -> null MODE_OFF -> null
@@ -1,36 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
/** Which on-screen layout each game uses. Games without a choice use the default profile's main-screen layout. */
object GameControls {
const val STEAM = "steam"
private fun prefs(context: Context) = context.getSharedPreferences("game-controls", Context.MODE_PRIVATE)
/** The main-screen bindings preset saved for [game], whose layout is the one drawn. */
fun bindings(context: Context, game: Long?): String? = game?.let { prefs(context).getString("$it.bindings", null) }
fun steamLayout(context: Context, game: Long?): Boolean {
val p = prefs(context)
return if (game != null && p.contains("$game.steam")) p.getBoolean("$game.steam", false) else SessionPrefs.steamTouchLayout(context)
}
fun choose(context: Context, game: Long, bindings: String?, steam: Boolean, name: String? = null) {
prefs(context).edit().apply { if (bindings == null) remove("$game.bindings") else putString("$game.bindings", bindings) }
.apply { if (!name.isNullOrBlank()) putString("$game.name", name) }
.putBoolean("$game.steam", steam).apply()
}
/** Games with their own choice, in the order of their ids. */
fun games(context: Context): List<Long> = prefs(context).all.keys
.filter { it.endsWith(".steam") || it.endsWith(".bindings") }
.mapNotNull { it.substringBeforeLast('.').toLongOrNull() }.distinct().sorted()
fun name(context: Context, game: Long): String? = prefs(context).getString("$game.name", null)
fun clear(context: Context, game: Long) {
prefs(context).edit().remove("$game.bindings").remove("$game.steam").apply()
}
}
@@ -9,7 +9,6 @@ object GamepadGeometry {
VIEW, STEAM, QAM, MENU, VIEW, STEAM, QAM, MENU,
PANELS, PANELS,
L4, L5, R5, R4, L4, L5, R5, R4,
LEFT_TOUCH, RIGHT_TOUCH,
} }
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) { data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
@@ -27,11 +26,10 @@ object GamepadGeometry {
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false, grips: Boolean = false, upright: Boolean = false, fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> {
trackpads: Boolean = false): Map<Slot, Box> {
if (w <= 0f || h <= 0f) return emptyMap() if (w <= 0f || h <= 0f) return emptyMap()
if (upright || portraitDock && h >= w * 0.6f && w >= 300 * density && h >= 300 * density) { if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) {
return portraitLayout(w, h, density, grips, trackpads) return portraitLayout(w, h, density)
} }
val pad = 8 * density val pad = 8 * density
val buttonH = 40 * density val buttonH = 40 * density
@@ -72,7 +70,6 @@ object GamepadGeometry {
else -> 1 else -> 1
} }
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f) middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
if (grips) gripsBetween(boxes, w, gap - 2 * gutter, boxes.values.maxOf { if (it.cx in (w - gap) / 2f..(w + gap) / 2f) it.bottom else 0f } + gutter, h - pad, density)
} else { } else {
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f) val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
val main = side * 0.62f val main = side * 0.62f
@@ -88,75 +85,45 @@ object GamepadGeometry {
val gap = w - 2 * (side * 0.40f + main / 2f) val gap = w - 2 * (side * 0.40f + main / 2f)
val columns = if (gap >= 2 * gridButton) 2 else 1 val columns = if (gap >= 2 * gridButton) 2 else 1
val rows = (middle.size + columns - 1) / columns val rows = (middle.size + columns - 1) / columns
val gridTop = h - pad - rows * buttonH - (rows - 1) * 10 * density middleGrid(columns, gap - 2 * gutter, h - pad - rows * buttonH - (rows - 1) * 10 * density)
middleGrid(columns, gap - 2 * gutter, gridTop)
if (grips) gripsBetween(boxes, w, w - 2 * (side * 0.74f + second / 2f) - 2 * gutter, shoulderY + buttonH / 2f + gutter, gridTop - gutter, density)
val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter) val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter)
if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH) if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
} }
return boxes return boxes
} }
/** The back grips in the gap between a landscape panel's two clusters: one row of four, or two rows of two. */ private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> {
private fun gripsBetween(boxes: MutableMap<Slot, Box>, w: Float, span: Float, top: Float, bottom: Float, density: Float) {
val gap = 8 * density
val minimum = 44 * density
val rows = if ((span - 3 * gap) / 4f >= minimum) 1 else if ((span - gap) / 2f >= minimum) 2 else return
val perRow = 4 / rows
val cellW = ((span - (perRow - 1) * gap) / perRow).coerceAtMost(96 * density)
val cellH = ((bottom - top - (rows - 1) * gap) / rows).coerceAtMost(64 * density)
if (cellH < minimum) return
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
val col = i % perRow; val row = i / perRow
boxes[slot] = Box(w / 2f + (col - (perRow - 1) / 2f) * (cellW + gap), bottom - (rows - 1 - row) * (cellH + gap) - cellH / 2f, cellW, cellH)
}
}
/**
* The panel under a portrait game: shoulders with View and Menu across the top, the back grips under them when the kit has
* them, then the d-pad and face buttons and, along the bottom edge, the sticks or trackpads, each as large as the panel allows.
*/
private fun portraitLayout(w: Float, h: Float, density: Float, grips: Boolean, trackpads: Boolean): Map<Slot, Box> {
val pad = 8 * density val pad = 8 * density
val gap = 8 * density val gap = 8 * density
val buttonH = 44 * density val buttonH = 44 * density
val boxes = LinkedHashMap<Slot, Box>() val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f))
val topGap = 4 * density val main = w * 0.4f * scale
val topW = (w - 2 * pad - 5 * topGap) / 6f val second = w * 0.3f * scale
val top = listOf(Slot.LEFT_OUTER_SHOULDER, Slot.LEFT_INNER_SHOULDER, Slot.VIEW, Slot.MENU, Slot.RIGHT_INNER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER)
for ((i, slot) in top.withIndex()) boxes[slot] = Box(pad + topW / 2f + i * (topW + topGap), pad + buttonH / 2f, topW, buttonH)
var areaTop = pad + buttonH + gap
if (grips) {
val gripW = (w - 2 * pad - 3 * gap) / 4f
val gripH = min(56 * density, (h - areaTop) * 0.12f).coerceAtLeast(buttonH)
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex())
boxes[slot] = Box(pad + gripW / 2f + i * (gripW + gap), areaTop + gripH / 2f, gripW, gripH)
areaTop += gripH + gap
}
val area = h - pad - areaTop - gap
if (trackpads) {
val second = min(w * 0.42f, area * 0.5f)
val rowH = area - second
val col = (w - 2 * pad - 3 * gap) / 4f
val stick = min(col, rowH)
val rowY = h - pad - rowH / 2f
val secondY = areaTop + second / 2f
boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second)
boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second)
boxes[Slot.LEFT_TOUCH] = Box(pad + col / 2f, rowY, col, rowH)
boxes[Slot.LEFT_MAIN] = Box(pad + col * 1.5f + gap, rowY, stick, stick)
boxes[Slot.RIGHT_MAIN] = Box(w - pad - col * 1.5f - gap, rowY, stick, stick)
boxes[Slot.RIGHT_TOUCH] = Box(w - pad - col / 2f, rowY, col, rowH)
return boxes
}
val main = min(w * 0.46f, area * 0.53f)
val second = min(w * 0.42f, area - main)
val secondY = areaTop + second / 2f
val mainY = h - pad - main / 2f val mainY = h - pad - main / 2f
boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second) val secondY = mainY - main / 2f - gap - second / 2f
boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second) val shoulderY = secondY - second / 2f - gap - buttonH / 2f
boxes[Slot.LEFT_MAIN] = Box(w * 0.25f, mainY, main, main) val boxes = linkedMapOf(
boxes[Slot.RIGHT_MAIN] = Box(w * 0.75f, mainY, main, main) Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main),
Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main),
Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second),
Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second),
)
val utilityW = (w - 2 * pad - 3 * gap) / 4f
for ((i, slot) in middle.withIndex()) {
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH)
}
val gripTop = pad + buttonH + gap
val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop)
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH)
}
val panelsW = min(112 * density, w * 0.22f)
val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f
boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH)
boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH)
boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH)
boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH)
return boxes return boxes
} }
} }
@@ -10,7 +10,7 @@ import org.json.JSONObject
import java.util.UUID import java.util.UUID
object InputLibraries { object InputLibraries {
private const val VERSION = 15 private const val VERSION = 14
private const val KEY = "library" private const val KEY = "library"
private const val RECOVERY = "library-recovery." private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay" const val OVERLAY = "builtin.overlay"
@@ -29,10 +29,10 @@ object InputLibraries {
val version = raw?.let { JSONObject(it).getInt("version") } ?: 0 val version = raw?.let { JSONObject(it).getInt("version") } ?: 0
if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library))) if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library)))
if (version < 11) library = neutralStockLayouts(library) if (version < 11) library = neutralStockLayouts(library)
if (version < 10) library = restyleGamepads(context, library)
if (version < 12) library = barStockLayouts(library) if (version < 12) library = barStockLayouts(library)
if (version < 13) library = LegacyScreenKeyMigration.pin(library) if (version < 13) library = LegacyScreenKeyMigration.pin(library)
if (version < 14) library = deckGamepadSurfaces(context, library) if (version < 14) library = deckGamepadSurfaces(context, library)
if (version < 15) library = kitGamepads(library)
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) { if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context) val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) { if (legacy != null) {
@@ -83,12 +83,8 @@ object InputLibraries {
if (invalid) { if (invalid) {
val encoded = encode(updated) val encoded = encode(updated)
require(encoded.length <= 2_000_000) { "The input library is too large to save." } require(encoded.length <= 2_000_000) { "The input library is too large to save." }
val recovery = RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)) check(p.edit().putString(RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)), stored)
if (!p.edit().putString(recovery, stored).putString(KEY, encoded).commit()) { .putString(KEY, encoded).commit()) { "Could not save the input library and its recovery copy." }
// A failed commit has already changed the in-memory preferences; put the previous library back.
p.edit().putString(KEY, stored).remove(recovery).apply()
error("Could not save the input library and its recovery copy.")
}
} else write(context, updated) } else write(context, updated)
return updated return updated
} }
@@ -129,16 +125,29 @@ object InputLibraries {
return InputLibrary(profiles, layouts, bindings, selected).validate() return InputLibrary(profiles, layouts, bindings, selected).validate()
} }
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): Pair<List<InputSurfaceElement>, Float>? { fun setAdaptiveSticks(context: Context, layoutId: String, on: Boolean): Boolean = runCatching {
val origin = layout.origin ?: layout.id update(context) { library ->
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements to it.aspect } library.copy(layouts = library.layouts.map { layout ->
if (origin == OVERLAY) { if (layout.id != layoutId || !layout.editable) layout
val (surfaceContext, metrics) = primaryDisplay(context) else layout.copy(elements = layout.elements.map { if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = on) else it })
val w = metrics.widthPixels.coerceAtLeast(1) })
val h = metrics.heightPixels.coerceAtLeast(1)
return KitLayout.elements(surfaceContext, PadKit.current(context), w, h, scale = layout.scale) to w.toFloat() / h
} }
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect } }.onSuccess { ControllerPrefs.setAdaptiveSticks(context, on) }.isSuccess
fun setQuickButton(context: Context, layoutId: String, button: InputCommand, shown: Boolean): Boolean = runCatching {
update(context) { library -> library.layouts.firstOrNull { it.id == layoutId && it.editable }?.let { library.withLayout(it.withQuickButton(button, shown)) } ?: library }
}.isSuccess
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): List<InputSurfaceElement>? {
val origin = layout.origin ?: layout.id
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements }
if (origin == OVERLAY || origin.startsWith("migrated.layout.")) {
val (surfaceContext, metrics) = primaryDisplay(context)
val size = if (origin == OVERLAY) listOf(metrics.widthPixels, metrics.heightPixels)
else origin.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() }
}
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.elements
} }
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
@@ -148,12 +157,29 @@ object InputLibraries {
return surfaceContext to DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) } return surfaceContext to DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) }
} }
private fun restyleGamepads(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.none { it.id == OVERLAY || it.id.startsWith("migrated.layout.") }) return library
val (surfaceContext, metrics) = primaryDisplay(context)
return library.copy(layouts = library.layouts.map { layout ->
val size = when {
layout.id == OVERLAY -> listOf(metrics.widthPixels, metrics.heightPixels)
layout.id.startsWith("migrated.layout.") -> layout.id.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
else -> emptyList()
}
if (size.size != 2 || size.any { it <= 0 }) layout
else layout.copy(elements = LegacyGamepadLayout(surfaceContext, size[0], size[1]).restyle(layout.elements))
})
}
private fun upgradeOverlay(context: Context, library: InputLibrary): InputLibrary { private fun upgradeOverlay(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.none { it.template == InputLayoutTemplate.OVERLAY }) return library if (library.layouts.none { it.template == InputLayoutTemplate.OVERLAY }) return library
val (surfaceContext, metrics) = primaryDisplay(context)
val settings = ControllerPrefs.read(context) val settings = ControllerPrefs.read(context)
val style = InputSurfaceStyle(opacity = settings.opacity) val elements = LegacyGamepadLayout(surfaceContext, metrics.widthPixels.coerceAtLeast(1), metrics.heightPixels.coerceAtLeast(1)).elements()
val style = InputSurfaceStyle(settings.tint, settings.opacity)
val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old -> val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old ->
old.id to old.copy(name = "Gamepad", elements = emptyList(), template = InputLayoutTemplate.CUSTOM, style = style) old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style,
aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f))
} }
var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it }) var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
val migrated = mutableMapOf<Pair<String, String>, String>() val migrated = mutableMapOf<Pair<String, String>, String>()
@@ -164,8 +190,9 @@ object InputLibraries {
val id = migrated.getOrPut(key) { val id = migrated.getOrPut(key) {
val old = library.preset(part.bindings) val old = library.preset(part.bindings)
val newId = migrationBindingId(result, old.id, layout.id) val newId = migrationBindingId(result, old.id, layout.id)
val clicks = if (settings.stickClick) old.clicks else old.clicks + KitLayout.clickIds.associateWith { InputAction.Disabled } val keyboard = elements.filter { it.id == "builtin:keyboard" }.associate { it.id to InputAction.Command(InputCommand.KEYBOARD) }
result = result.withPreset(old.copy(id = newId, layoutId = layout.id, clicks = clicks)) val clicks = if (settings.stickClick) old.clicks else old.clicks + elements.filter { it.hasClick }.associate { it.id to InputAction.Disabled }
result = result.withPreset(old.copy(id = newId, layoutId = layout.id, elements = old.elements + keyboard, clicks = clicks))
newId newId
} }
part.copy(bindings = id) part.copy(bindings = id)
@@ -174,6 +201,15 @@ object InputLibraries {
} }
val oldBindings = migrated.keys.map { it.first }.toSet() val oldBindings = migrated.keys.map { it.first }.toSet()
result = result.copy(bindings = result.bindings.filter { it.id !in oldBindings || result.usersOfBindings(it.id).isNotEmpty() }) result = result.copy(bindings = result.bindings.filter { it.id !in oldBindings || result.usersOfBindings(it.id).isNotEmpty() })
// Older editor layouts were resolution-specific. Keep each as a selectable saved layout.
for (key in ControllerPrefs.prefs(context).all.keys.filter { it.startsWith("layout.") }.sorted()) {
val size = key.removePrefix("layout.").split('x').mapNotNull { it.toIntOrNull() }
if (size.size != 2 || size.any { it <= 0 } || result.layouts.size >= 128) continue
if (size[0] == metrics.widthPixels && size[1] == metrics.heightPixels) continue
val id = "migrated.$key"
if (result.layouts.none { it.id == id }) result = result.withLayout(SavedInputLayout(id, "Gamepad ${size[0]} × ${size[1]}",
LegacyGamepadLayout(surfaceContext, size[0], size[1]).elements(), style = style, aspect = (size[0].toFloat() / size[1]).coerceIn(.05f, 20f)))
}
return result.validate() return result.validate()
} }
@@ -239,16 +275,6 @@ object InputLibraries {
return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate() return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate()
} }
/** Gamepads saved by the old editor follow the virtual controller's kit again; their positions don't map onto the new controls. */
private fun kitGamepads(library: InputLibrary): InputLibrary {
return library.copy(layouts = library.layouts.map { layout ->
val origin = layout.origin ?: layout.id
if (origin != OVERLAY && !origin.startsWith("migrated.layout.")) return@map layout
val extras = layout.elements.filterNot { KitLayout.isKit(it.id) }
layout.copy(elements = extras, origin = if (layout.id == OVERLAY) null else OVERLAY, aspect = if (extras.isEmpty()) 0f else layout.aspect, scale = 1f)
}).validate()
}
private fun migrationBindingId(library: InputLibrary, binding: String, layout: String): String { private fun migrationBindingId(library: InputLibrary, binding: String, layout: String): String {
val seed = JSONArray(listOf(binding, layout)).toString().toByteArray(Charsets.UTF_8) val seed = JSONArray(listOf(binding, layout)).toString().toByteArray(Charsets.UTF_8)
val base = "migrated.bindings." + UUID.nameUUIDFromBytes(seed) val base = "migrated.bindings." + UUID.nameUUIDFromBytes(seed)
@@ -281,7 +307,7 @@ object InputLibraries {
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown)) .put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements) layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble()) .put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL).put("kitless", layout.kitless)) .put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
} }
val bindings = JSONArray() val bindings = JSONArray()
for (b in library.bindings) { for (b in library.bindings) {
@@ -325,7 +351,7 @@ object InputLibraries {
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100), InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()), layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), layout.optionalString("origin"), InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), layout.optionalString("origin"),
layout.optDouble("scale", 1.0).toFloat(), layout.optBoolean("kitless", false)) layout.optDouble("scale", 1.0).toFloat())
} }
val bindings = doc.getJSONArray("bindings").objects(512).map { b -> val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) } val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
@@ -22,8 +22,6 @@ data class SavedInputLayout(
val aspect: Float = 0f, val aspect: Float = 0f,
val origin: String? = null, val origin: String? = null,
val scale: Float = 1f, val scale: Float = 1f,
/** The player removed every kit control from this gamepad, so it must not follow the virtual controller again. */
val kitless: Boolean = false,
) { ) {
val editable get() = template == InputLayoutTemplate.CUSTOM val editable get() = template == InputLayoutTemplate.CUSTOM
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } } val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
@@ -51,7 +49,7 @@ data class SavedInputBindings(
fun action(element: InputSurfaceElement) = elements[element.id] fun action(element: InputSurfaceElement) = elements[element.id]
?: if (element.id == "legacy:${element.control.id}") controls[element.control] ?: InputAction.Native() ?: if (element.id == "legacy:${element.control.id}") controls[element.control] ?: InputAction.Native()
else defaultElementAction(element.id) else InputAction.Disabled
fun clickAction(element: InputSurfaceElement) = clicks[element.id] fun clickAction(element: InputSurfaceElement) = clicks[element.id]
?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() } ?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() }
@@ -99,16 +97,6 @@ data class InputLibrary(
fun compileActive(isDesktop: Boolean, panel: String? = null): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith { fun compileActive(isDesktop: Boolean, panel: String? = null): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith {
preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel).bindings else activePart(isDesktop, it).bindings) preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel).bindings else activePart(isDesktop, it).bindings)
}) })
fun compileStock(isDesktop: Boolean, panel: String? = null): InputProfile {
val defaults = InputProfile.defaults(profile(activeId(isDesktop)).base)
val stock = InputStockLayouts.presets(InputStockLayouts.layouts())
return compileParts(defaults.id, InputRole.entries.associateWith { role ->
val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel) else activePart(isDesktop, role)
val origin = layouts.firstOrNull { it.id == part.layout }?.origin ?: part.layout
stock.firstOrNull { it.id == part.bindings || (origin != null && it.layoutId == origin) }
?: SavedInputBindings(part.bindings, "", role == InputRole.PHYSICAL, part.layout, defaults.bindings[role].orEmpty())
})
}
fun saveSelection(isDesktop: Boolean, name: String, id: String = newInputId()): InputLibrary { fun saveSelection(isDesktop: Boolean, name: String, id: String = newInputId()): InputLibrary {
val current = profile(activeId(isDesktop)) val current = profile(activeId(isDesktop))
@@ -138,8 +126,8 @@ data class InputLibrary(
fun withPreset(value: SavedInputBindings) = copy(bindings = bindings.filterNot { it.id == value.id } + value) fun withPreset(value: SavedInputBindings) = copy(bindings = bindings.filterNot { it.id == value.id } + value)
fun withLayout(value: SavedInputLayout) = copy(layouts = layouts.filterNot { it.id == value.id } + value, fun withLayout(value: SavedInputLayout) = copy(layouts = layouts.filterNot { it.id == value.id } + value,
bindings = bindings.map { preset -> if (preset.layoutId != value.id) preset else preset.copy( bindings = bindings.map { preset -> if (preset.layoutId != value.id) preset else preset.copy(
elements = preset.elements.filter { (id, action) -> value.element(id)?.let { action.validFor(it) } == true }, elements = preset.elements.filter { (id, action) -> value.elements.any { it.id == id && action.validFor(it) } },
clicks = preset.clicks.filter { (id, action) -> value.element(id)?.hasClick == true && action.validForClick() }) }) clicks = preset.clicks.filter { (id, action) -> value.elements.any { it.id == id && it.hasClick && action.validForClick() } }) })
fun duplicateProfile(id: String, name: String, newId: String = newInputId(), sharePhysical: Boolean = false): InputLibrary { fun duplicateProfile(id: String, name: String, newId: String = newInputId(), sharePhysical: Boolean = false): InputLibrary {
require(profiles.size < 64) require(profiles.size < 64)
@@ -273,8 +261,8 @@ data class InputLibrary(
require(preset.physical || preset.keys.isEmpty()) require(preset.physical || preset.keys.isEmpty())
val layout = preset.layoutId?.let { id -> layouts.first { it.id == id } } val layout = preset.layoutId?.let { id -> layouts.first { it.id == id } }
require(!preset.physical || layout == null && preset.elements.isEmpty() && preset.clicks.isEmpty()) require(!preset.physical || layout == null && preset.elements.isEmpty() && preset.clicks.isEmpty())
require(preset.elements.all { (id, action) -> layout?.element(id)?.let { action.validFor(it) } == true }) require(preset.elements.all { (id, action) -> layout?.elements?.firstOrNull { it.id == id }?.let { action.validFor(it) } == true })
require(preset.clicks.all { (id, action) -> layout?.element(id)?.hasClick == true && action.validForClick() }) require(preset.clicks.all { (id, action) -> layout?.elements?.any { it.id == id && it.hasClick } == true && action.validForClick() })
require(preset.keys.all { it.key.device.isNotBlank() && it.key.keyCode >= 0 && it.key.scanCode >= 0 && require(preset.keys.all { it.key.device.isNotBlank() && it.key.keyCode >= 0 && it.key.scanCode >= 0 &&
it.action.validFor(InputControl.A) && (it.action !is InputAction.Native || it.action.target == null) }) it.action.validFor(InputControl.A) && (it.action !is InputAction.Native || it.action.target == null) })
} }
@@ -314,12 +302,3 @@ internal fun InputAction.validFor(element: InputSurfaceElement): Boolean = when
element.kind == InputElementKind.TRIGGER -> target == InputControl.LT || target == InputControl.RT element.kind == InputElementKind.TRIGGER -> target == InputControl.LT || target == InputControl.RT
else -> target.dimensions == 1 && target != InputControl.LT && target != InputControl.RT else -> target.dimensions == 1 && target != InputControl.LT && target != InputControl.RT
} }
/**
* A saved element, or the kit control that [id] names: in a layout made from the built-in gamepad every kit control keeps its
* binding while it's removed, so Reset or Restore brings it back with its action.
*/
internal fun SavedInputLayout.element(id: String): InputSurfaceElement? =
elements.firstOrNull { it.id == id } ?: KitLayout.element(id)?.takeIf {
this.id == InputLibraries.OVERLAY || origin == InputLibraries.OVERLAY || KitLayout.bindsTo(id, elements)
}
@@ -48,21 +48,11 @@ data class InputProfile(
copy(bindings = bindings + (role to (bindings[role].orEmpty() + (control to action)))) copy(bindings = bindings + (role to (bindings[role].orEmpty() + (control to action))))
fun elementAction(role: InputRole, id: String, control: InputControl): InputAction = fun elementAction(role: InputRole, id: String, control: InputControl): InputAction =
elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else defaultElementAction(id) elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else InputAction.Disabled
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id) fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) } ?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
fun showsMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
val action = elementAction(role, element.id, element.control).takeIf {
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
}
val click = elementClickAction(role, element).takeIf {
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
}
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) }
}
companion object { companion object {
const val GAME = "game" const val GAME = "game"
const val DESKTOP = "desktop" const val DESKTOP = "desktop"
@@ -115,10 +105,3 @@ internal fun InputAction.validFor(control: InputControl): Boolean = when (this)
is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f
else -> true else -> true
} }
/** What an on-screen element with no saved action does: kit controls press their own button, everything else is unassigned. */
internal fun defaultElementAction(id: String): InputAction = when (id) {
KitLayout.DPAD_ID -> InputAction.Native()
KitLayout.KEYBOARD_ID -> InputAction.Command(InputCommand.KEYBOARD)
else -> InputAction.Disabled
}
@@ -38,13 +38,8 @@ data class InputSurfaceElement(
) { ) {
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
fun bounded() = copy(x = x.coerceIn(0f, 1f - MIN_SIZE), y = y.coerceIn(0f, 1f - MIN_SIZE), fun bounded() = copy(x = x.coerceIn(0f, 0.97f), y = y.coerceIn(0f, 0.97f),
width = width.coerceIn(MIN_SIZE, (1f - x.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)), width = width.coerceIn(0.03f, (1f - x.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)), height = height.coerceIn(0.03f, (1f - y.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)))
height = height.coerceIn(MIN_SIZE, (1f - y.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)))
companion object {
const val MIN_SIZE = .01f
}
} }
internal val QUICK_BUTTONS = listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.KEYBOARD) internal val QUICK_BUTTONS = listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.KEYBOARD)
@@ -56,31 +51,15 @@ val InputSurfaceElement.quickButton: InputCommand? get() = when {
else -> null else -> null
} }
/** Controls whose boxes touch, grown by 15%, scale around one shared anchor so a cluster such as the face buttons keeps its shape. */ internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> = map { e ->
internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> {
fun anchor(centre: Float) = when { centre < 1f / 3f -> 0f; centre > 2f / 3f -> 1f; else -> .5f } fun anchor(centre: Float) = when { centre < 1f / 3f -> 0f; centre > 2f / 3f -> 1f; else -> .5f }
val group = IntArray(size) { it } val w = (e.width * factor).coerceIn(.03f, 1f)
fun root(i: Int): Int = if (group[i] == i) i else root(group[i]).also { group[i] = it } val h = (e.height * factor).coerceIn(.03f, 1f)
for (i in indices) for (j in i + 1 until size) {
val a = this[i]; val b = this[j]
val near = kotlin.math.abs(a.x + a.width / 2 - b.x - b.width / 2) < (a.width + b.width) / 2 * 1.15f &&
kotlin.math.abs(a.y + a.height / 2 - b.y - b.height / 2) < (a.height + b.height) / 2 * 1.15f
if (near) group[root(i)] = root(j)
}
val anchors = indices.groupBy(::root).mapValues { (_, members) ->
anchor(members.map { this[it].x + this[it].width / 2 }.average().toFloat()) to anchor(members.map { this[it].y + this[it].height / 2 }.average().toFloat())
}
return mapIndexed { i, e -> e.scaledAround(factor, anchors.getValue(root(i))) }
}
private fun InputSurfaceElement.scaledAround(factor: Float, anchor: Pair<Float, Float>): InputSurfaceElement {
val e = this
val w = (e.width * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val h = (e.height * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val cx = e.x + e.width / 2 val cx = e.x + e.width / 2
val cy = e.y + e.height / 2 val cy = e.y + e.height / 2
val (ax, ay) = anchor val ax = anchor(cx)
return e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h), val ay = anchor(cy)
e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h),
width = w, height = h).bounded() width = w, height = h).bounded()
} }
@@ -3,10 +3,6 @@ package com.droiddeck.launcher.input
class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole, val element: InputSurfaceElement) { class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole, val element: InputSurfaceElement) {
private val router = pad.inputRouter private val router = pad.inputRouter
private val route = router?.channel(role, element.control, element = element) private val route = router?.channel(role, element.control, element = element)
/** The kit's D-pad keeps each direction's own binding, as the separate direction buttons it replaced did. */
private val arms = if (element.id == KitLayout.DPAD_ID && router != null)
listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { router.channel(role, it, element = KitLayout.element("legacy:${it.id}")) }
else emptyList()
private val deck = DeckControls.source(role, routed = true) private val deck = DeckControls.source(role, routed = true)
private val clickDeck = DeckControls.source(role, routed = true) private val clickDeck = DeckControls.source(role, routed = true)
private val clickOwner = Any() private val clickOwner = Any()
@@ -59,15 +55,6 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
fingerDown = down fingerDown = down
if (latched) 1f else 0f if (latched) 1f else 0f
} else value } else value
if (arms.isNotEmpty() && route?.action is InputAction.Native) {
val ready = route.update(x, y, touching) != null
val values = listOf(y < -.5f, x > .5f, y > .5f, x < -.5f).map { if (it && ready) 1f else 0f }
val toPad = arms.mapIndexed { i, arm -> arm.update(values[i])?.takeIf { it.isPad }?.let { it to values[i] } }.filterNotNull()
if (toPad.isNotEmpty() || nativePad) writePad(this, null) { state -> state.clear(); for ((t, v) in toPad) state.add(t, v) }
nativePad = toPad.isNotEmpty()
InputTiming.end(timing)
return
}
val target = if (router == null) element.control else route?.update(x, y, touching) val target = if (router == null) element.control else route?.update(x, y, touching)
val toPad = target?.isPad == true val toPad = target?.isPad == true
val toDeck = target != null && !target.isPad val toDeck = target != null && !target.isPad
@@ -88,7 +75,6 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
fun cancel() { fun cancel() {
if (closed) return if (closed) return
route?.takeIf { it.action is InputAction.Command }?.release() route?.takeIf { it.action is InputAction.Command }?.release()
arms.filter { it.action is InputAction.Command }.forEach { it.release() }
update(0f) update(0f)
} }
@@ -126,13 +112,13 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
closed = true closed = true
router?.removeSnapshot(snapshot) router?.removeSnapshot(snapshot)
releaseNative(); resetLatch() releaseNative(); resetLatch()
route?.close(); arms.forEach { it.close() }; clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close() route?.close(); clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close()
} }
fun release() { fun release() {
if (closed) return if (closed) return
releaseNative(); resetLatch() releaseNative(); resetLatch()
route?.release(); arms.forEach { it.release() }; clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release() route?.release(); clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release()
} }
} }
@@ -26,8 +26,6 @@ class KeyboardHost(
var imeShowing = false var imeShowing = false
private set private set
var onImeChanged: ((Boolean) -> Unit)? = null var onImeChanged: ((Boolean) -> Unit)? = null
val hideMeansDismissal: Boolean
get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R || (shown && imeShowing)
init { init {
isFocusable = false isFocusable = false
@@ -1,222 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.max
import kotlin.math.min
/**
* Places a virtual controller's default on-screen controls. Each kit is drawn on a 1600 × 900 reference screen; controls keep
* their distance from the nearest edge, so wider screens spread them apart instead of stretching them. Clusters such as the face
* buttons are placed by their centre so they move as one, and the row along the bottom-left edge always starts after DroidDeck's
* corner button.
*/
object KitLayout {
const val DPAD_ID = "kit:dpad"
const val KEYBOARD_ID = "builtin:keyboard"
/** Whether [id] names one of a kit's own controls rather than a key or control the player added. */
fun isKit(id: String) = id.startsWith("legacy:") || id == DPAD_ID || id == KEYBOARD_ID
/** The control a kit id stands for in a layout that keeps no kit positions, so bindings saved for it stay valid. */
fun element(id: String): InputSurfaceElement? = when {
id == DPAD_ID -> InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, id, InputElementKind.DPAD)
id == KEYBOARD_ID -> InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, id)
id.startsWith("legacy:") -> InputControl.entries.firstOrNull { "legacy:${it.id}" == id }
?.let { InputSurfaceElement(it, 0f, 0f, .1f, .1f, id, InputElementKind.from(it)) }
else -> null
}
/** The direction buttons the kit's D-pad stands in for; their saved overrides stay with the D-pad. */
val dpadDirectionIds = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { "legacy:${it.id}" }
/** Whether a binding for [id] belongs to a layout made of [elements]. */
fun bindsTo(id: String, elements: List<InputSurfaceElement>) =
elements.any { it.id == id } || id in dpadDirectionIds && elements.any { it.id == DPAD_ID }
/** Every kit control that has a click, across all virtual controllers. */
val clickIds = listOf(InputControl.LS, InputControl.RS, InputControl.LEFT_PAD, InputControl.RIGHT_PAD).map { "legacy:${it.id}" }
private const val REF_W = 1600f
private const val REF_H = 900f
/** The widest pair of side controls on any kit: a larger size never pushes the two halves, or the rows, into each other. */
private const val MIN_SPAN = 1200f
private const val MAX_HEIGHT_MM = 80f
/** The smallest half-size of any kit control in reference units. */
private const val SMALLEST_HALF = 26f
private const val CORNER_DP = 52f
private const val ROW_DP = 60f
private const val BUTTON_DP = 44f
private const val GAP_DP = 8f
private class Spec(val control: InputControl, val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw, val id: String = "legacy:${control.id}",
val kind: InputElementKind = InputElementKind.from(control), val shape: InputButtonShape = InputButtonShape.CIRCLE, val icon: Int = 0, val name: String = control.label,
val ax: Float = cx, val ay: Float = cy)
private fun shoulders() = listOf(
Spec(InputControl.LT, 140f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.LB, 140f, 148f, 88f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.RT, 1460f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.RB, 1460f, 148f, 88f, 30f, shape = InputButtonShape.PILL))
private fun face(cx: Float, cy: Float, r: Float, off: Float) = listOf(
Spec(InputControl.Y, cx, cy - off, r, ax = cx, ay = cy), Spec(InputControl.X, cx - off, cy, r, ax = cx, ay = cy),
Spec(InputControl.B, cx + off, cy, r, ax = cx, ay = cy), Spec(InputControl.A, cx, cy + off, r, ax = cx, ay = cy))
private fun dpad(cx: Float, cy: Float, half: Float) =
Spec(InputControl.LS, cx, cy, half, id = DPAD_ID, kind = InputElementKind.DPAD, shape = InputButtonShape.ROUNDED, name = "D-pad")
private fun keyboard(cx: Float) = Spec(InputControl.A, cx, 848f, 46f, id = KEYBOARD_ID, icon = InputButtonIcons.KEYBOARD, name = "Keyboard")
private fun specs(kit: PadKit): List<Spec> = when {
kit.steam -> shoulders() + listOf(
Spec(InputControl.L4, 30f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.L5, 30f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.R4, 1570f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.R5, 1570f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED),
dpad(220f, 345f, 150f)) + face(1375f, 345f, 58f, 96f) + listOf(
Spec(InputControl.LS, 290f, 640f, 96f), Spec(InputControl.RS, 1310f, 640f, 96f),
Spec(InputControl.LEFT_PAD, 470f, 360f, 88f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1130f, 360f, 88f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.SELECT, 660f, 150f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 150f, 46f, 26f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL),
keyboard(136f))
kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 58f, 96f) + listOf(
Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f),
Spec(InputControl.L3, 430f, 590f, 42f, ax = 565f, ay = 690f), Spec(InputControl.R3, 1170f, 590f, 42f, ax = 1035f, ay = 690f),
Spec(InputControl.SELECT, 640f, 150f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 150f, 50f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 800f, 250f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 675f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf(
Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f, ax = 235f, ay = 400f), Spec(InputControl.R3, 1290f, 790f, 42f, ax = 1130f, ay = 690f),
Spec(InputControl.SELECT, 690f, 162f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 162f, 38f),
Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
}
/** The default controls for [kit] on a [width] × [height] screen. */
fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f): List<InputSurfaceElement> {
if (width <= 0 || height <= 0) return emptyList()
// Insets stay as reported unless what's left is too small to keep every control above the minimum element size.
val smallestUnit = InputSurfaceElement.MIN_SIZE * max(width, height) / (2 * SMALLEST_HALF)
fun fit(a: Int, b: Int, side: Int, reference: Float): Pair<Int, Int> {
val first = a.coerceAtLeast(0); val second = b.coerceAtLeast(0)
val room = (side - (smallestUnit * reference).toInt() - 1).coerceAtLeast(0)
return if (first + second <= room) first to second else (first.toLong() * room / (first + second)).toInt() to (second.toLong() * room / (first + second)).toInt()
}
val (left, right) = fit(inset.left, inset.right, width, MIN_SPAN)
val (top, bottom) = fit(inset.top, inset.bottom, height, REF_H)
val safe = Rect(left, top, right, bottom)
if (height > width) return portrait(context, kit, width, height, safe, scale)
val w = width.toFloat(); val h = height.toFloat()
val unit = (min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale).coerceAtMost(min((w - safe.left - safe.right).coerceAtLeast(1f) / MIN_SPAN, (h - safe.top - safe.bottom).coerceAtLeast(1f) / REF_H))
fun x(ref: Float) = when {
ref < REF_W / 3f -> safe.left + ref * unit
ref > REF_W * 2f / 3f -> w - safe.right - (REF_W - ref) * unit
else -> (w / 2f + (ref - REF_W / 2f) * unit).between(safe.left + ref * unit, w - safe.right - (REF_W - ref) * unit)
}
fun y(ref: Float) = when {
ref < REF_H / 3f -> safe.top + ref * unit
ref > REF_H * 2f / 3f -> h - safe.bottom - (REF_H - ref) * unit
else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit)
}
val density = context.resources.displayMetrics.density
var edge = safe.left + CORNER_DP * density
val specs = specs(kit)
val row = specs.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s ->
val hw = s.hw * unit
max(x(s.cx), edge + hw).also { edge = it + hw + GAP_DP * density }
}
return specs.map { s ->
val cx = row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit); val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit
InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, if (s.name == s.control.label) kit.name(s.control) else s.name,
floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded()
}
}
/**
* A portrait surface gets the same pad as the panel under the game, in the lower part of the screen, with the keyboard,
* Steam, Quick Access and stick-click buttons in a row along the bottom edge that starts after DroidDeck's corner button.
*/
private fun portrait(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val density = context.resources.displayMetrics.density
val row = ROW_DP * density
val inner = (w - safe.left - safe.right).coerceAtLeast(1f)
val area = (min(h * .6f, inner * 1.15f) * scale).coerceAtMost(h - safe.top - safe.bottom - row).coerceAtLeast(1f)
val top = h - safe.bottom - row - area
val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true).map { e ->
e.copy(x = (safe.left + e.x * inner) / w, y = (top + e.y * area) / h, width = e.width * inner / w, height = e.height * area / h,
floating = e.kind == InputElementKind.STICK)
}
val specs = specs(kit)
fun spec(control: InputControl, id: String = "legacy:${control.id}") = specs.firstOrNull { it.control == control && it.id == id }
val gap = GAP_DP * density
val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3))
val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3))
val start = safe.left + CORNER_DP * density
val span = (w - safe.right - gap - start - gap * (leftRow.size + rightRow.size - 1)).coerceAtLeast(1f)
val size = min(BUTTON_DP * density, span / (leftRow + rightRow).sumOf { (it.hw / it.hh).toDouble() }.toFloat())
val cy = h - safe.bottom - row / 2f
val placed = mutableListOf<InputSurfaceElement>()
fun put(s: Spec, cx: Float) {
val bw = size * s.hw / s.hh
placed += InputSurfaceElement(s.control, (cx - bw / 2) / w, (cy - size / 2) / h, bw / w, size / h, s.id, s.kind,
if (s.name == s.control.label) kit.name(s.control) else s.name, buttonShape = s.shape, icon = s.icon)
}
var left = start
for (s in leftRow) {
val bw = size * s.hw / s.hh
put(s, left + bw / 2); left += bw + gap
}
var right = w - safe.right - gap
for (s in rightRow) {
val bw = size * s.hw / s.hh
put(s, right - bw / 2); right -= bw + gap
}
return pad + placed
}
/** Controls for the panel below the game, in [GamepadGeometry]'s slots. */
fun dock(context: Context, kit: PadKit, width: Int, height: Int, portrait: Boolean, left: InputControl, right: InputControl,
upright: Boolean = false): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val boxes = GamepadGeometry.layout(w, h, context.resources.displayMetrics.density, portrait, grips = kit.steam, upright = upright,
trackpads = kit.steam)
val placed = mutableListOf<InputSurfaceElement>()
fun put(control: InputControl, box: GamepadGeometry.Box?, shape: InputButtonShape, id: String = "legacy:${control.id}",
kind: InputElementKind = InputElementKind.from(control), name: String = kit.name(control)) {
val b = box ?: return
placed += InputSurfaceElement(control, b.left / w, b.top / h, b.width / w, b.height / h, id, kind, name, floating = false, buttonShape = shape).bounded()
}
fun square(box: GamepadGeometry.Box?) = box?.let { val side = min(it.width, it.height); GamepadGeometry.Box(it.cx, it.cy, side, side) }
val four = GamepadGeometry.Slot.LEFT_TOUCH in boxes
val leftMain = if (four || !kit.steam && left == InputControl.LEFT_PAD) InputControl.LS else left
val rightMain = if (four || !kit.steam && right == InputControl.RIGHT_PAD) InputControl.RS else right
if (four) {
put(InputControl.LEFT_PAD, boxes[GamepadGeometry.Slot.LEFT_TOUCH], InputButtonShape.ROUNDED)
put(InputControl.RIGHT_PAD, boxes[GamepadGeometry.Slot.RIGHT_TOUCH], InputButtonShape.ROUNDED)
}
put(leftMain, square(boxes[GamepadGeometry.Slot.LEFT_MAIN]), InputButtonShape.CIRCLE)
put(InputControl.LS, square(boxes[GamepadGeometry.Slot.LEFT_SECOND]), InputButtonShape.ROUNDED, DPAD_ID, InputElementKind.DPAD, "D-pad")
put(rightMain, square(boxes[GamepadGeometry.Slot.RIGHT_MAIN]), InputButtonShape.CIRCLE)
square(boxes[GamepadGeometry.Slot.RIGHT_SECOND])?.let { b ->
val r = b.width * .17f; val off = b.width * .3f
listOf(InputControl.Y to (0f to -1f), InputControl.B to (1f to 0f), InputControl.A to (0f to 1f), InputControl.X to (-1f to 0f)).forEach { (c, d) ->
put(c, GamepadGeometry.Box(b.cx + d.first * off, b.cy + d.second * off, 2 * r, 2 * r), InputButtonShape.CIRCLE)
}
}
put(InputControl.LT, boxes[GamepadGeometry.Slot.LEFT_OUTER_SHOULDER], InputButtonShape.PILL)
put(InputControl.LB, boxes[GamepadGeometry.Slot.LEFT_INNER_SHOULDER], InputButtonShape.PILL)
put(InputControl.RB, boxes[GamepadGeometry.Slot.RIGHT_INNER_SHOULDER], InputButtonShape.PILL)
put(InputControl.RT, boxes[GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER], InputButtonShape.PILL)
put(InputControl.SELECT, boxes[GamepadGeometry.Slot.VIEW], InputButtonShape.PILL)
put(InputControl.START, boxes[GamepadGeometry.Slot.MENU], InputButtonShape.PILL)
if (kit.steam) listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4).forEach { (c, slot) -> put(c, boxes[slot], InputButtonShape.ROUNDED) }
return placed
}
private fun cap(context: Context, shortSide: Int): Float {
val metrics = context.resources.displayMetrics
val nominal = metrics.densityDpi.toFloat()
val dpi = metrics.ydpi.takeIf { it > nominal * .6f && it < nominal * 1.6f } ?: nominal
val mm = shortSide / dpi * 25.4f
return min(1f, MAX_HEIGHT_MM / max(mm, 1f))
}
/** The middle band never comes closer to an edge than the edge rows' own reference spacing allows. */
private fun Float.between(low: Float, high: Float) = coerceIn(low, max(low, high))
}
@@ -0,0 +1,352 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.*
internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int, private val safe: Rect = Rect(),
private val scale: Float = 1f) {
private val resources get() = context.resources
private val settings = ControllerPrefs.read(context)
private var fit = 1f
private class Control(val id: String, val group: String, val stick: Int, val radiusDp: Float, val offsetXDp: Float, val offsetYDp: Float) {
var radius = 0f
var cx = 0f
var cy = 0f
val halfW get() = if (id in shoulderIds) radius * SHOULDER_WIDTH else radius
val halfH get() = if (id in shoulderIds) radius * SHOULDER_HEIGHT else radius
}
private val controls = listOf(
Control("up", "dpad", -1, 30f, 0f, -50f),
Control("right", "dpad", -1, 30f, 50f, 0f),
Control("down", "dpad", -1, 30f, 0f, 50f),
Control("left", "dpad", -1, 30f, -50f, 0f),
Control("ls", "ls", 0, 48f, 0f, 0f),
Control("rs", "rs", 1, 48f, 0f, 0f),
Control("a", "face", -1, 30f, 0f, 50f),
Control("b", "face", -1, 30f, 50f, 0f),
Control("x", "face", -1, 30f, -50f, 0f),
Control("y", "face", -1, 30f, 0f, -50f),
Control("lb", "lb", -1, 24f, 0f, 0f),
Control("rb", "rb", -1, 24f, 0f, 0f),
Control("lt", "lt", -1, 24f, 0f, 0f),
Control("rt", "rt", -1, 24f, 0f, 0f),
Control("select", "select", -1, 20f, 0f, 0f),
Control("start", "start", -1, 20f, 0f, 0f),
Control("guide", "guide", -1, 22f, 0f, 0f),
Control("qam", "qam", -1, 22f, 0f, 0f),
)
private val groups = controls.map { it.group }.distinct()
private fun dp(value: Float) = value * resources.displayMetrics.density
private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit
private fun fitScale(): Float {
val metrics = resources.displayMetrics
val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
}
private fun pxPerMm(dpi: Float): Float {
val nominal = resources.displayMetrics.densityDpi.toFloat()
return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
}
private fun placeAuto(w: Float, h: Float) {
val metrics = resources.displayMetrics
val mmX = pxPerMm(metrics.xdpi)
val mmY = pxPerMm(metrics.ydpi)
val usableW = w - safe.left - safe.right
val usableH = h - safe.top - safe.bottom
val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
val gap = dp(12f)
val floor = BOTTOM_MARGIN_MM * mmY
val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
put("ls", safe.left + inboard, restY)
put("face", w - safe.right - inboard, restY)
besideBelow("dpad", "ls", 1f, gap, floor)
besideBelow("rs", "face", -1f, gap, floor)
val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
val shoulderY = if (phone) safe.top + floor + halfH("lb")
else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
shoulders("face", "rb", "rt", -1f, gap, shoulderY)
val bottom = h - safe.bottom - floor - extent("guide")
val spread = extent("guide") + gap / 2f
put("guide", w / 2f - spread, bottom)
put("qam", w / 2f + spread, bottom)
val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
put("select", inner, restY)
put("start", w - inner, restY)
if (phone) {
val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
put("select", top, shoulderY)
put("start", w - top, shoulderY)
}
if (crowded("select", gap) || crowded("start", gap)) {
above("select", "dpad", gap)
val (sx, sy) = centre("select")
put("start", w - sx, sy)
if (crowded("start", gap)) above("start", "rs", gap)
}
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
val row = centre("select").second
put("guide", w / 2f - spread, row)
put("qam", w / 2f + spread, row)
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
val top = safe.top + dp(8f) + extent("guide")
put("guide", w / 2f - spread, top)
put("qam", w / 2f + spread, top)
}
}
}
private fun drop(group: String, anchor: String, gap: Float): Float =
(extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
val (ax, ay) = centre(anchor)
val reach = extent(anchor) + extent(group) + gap
val floor = height - safe.bottom - margin - extent(group)
val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
val dx = sqrt(max(0f, reach * reach - dy * dy))
put(group, ax + inward * dx, ay + dy)
}
private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
val (ax, _) = centre(anchor)
val spread = extent(bumper) + gap / 2f
put(bumper, ax + inward * spread, y)
put(trigger, ax - inward * spread, y)
}
private fun above(group: String, anchor: String, gap: Float) {
val (ax, ay) = centre(anchor)
put(group, ax, ay - extent(anchor) - gap - extent(group))
}
private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
val (x, y) = centre(group)
return groups.any { other ->
if (other == group || other == except) return@any false
val (ox, oy) = centre(other)
val dx = x - ox
val dy = y - oy
sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
}
}
private fun members(group: String) = controls.filter { it.group == group }
private fun centre(group: String): Pair<Float, Float> {
val first = members(group).first()
return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
}
private fun extent(group: String): Float = members(group).maxOf { control ->
sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
}
private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
private fun put(group: String, x: Float, y: Float) {
for (control in members(group)) {
control.cx = x + scaled(control.offsetXDp)
control.cy = y + scaled(control.offsetYDp)
}
}
private fun clamp(group: String) {
val list = members(group)
val margin = dp(4f)
val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
if (dx == 0f && dy == 0f) return
for (control in list) { control.cx += dx; control.cy += dy }
}
fun elements(): List<InputSurfaceElement> {
fit = fitScale()
controls.forEach { it.radius = scaled(it.radiusDp) }
placeAuto(width.toFloat(), height.toFloat())
for ((group, position) in ControllerPrefs.layout(context, width, height)) {
if (group in groups && position.first.isFinite() && position.second.isFinite()) put(group, position.first * width, position.second * height)
}
groups.forEach(::clamp)
val result = controls.filter {
settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton)
}.map { c ->
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let(::widenStick).bounded()
}.toMutableList()
if (settings.keyboardButton) result += keyboard()
return result
}
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
val before = from.elements().associateBy { it.id }
val after = elements().associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
val inset = dp(BUTTONS_ONLY_INSET_DP)
val bottom = height - safe.bottom - inset
val radius = dp(BUTTONS_ONLY_RADIUS_DP)
fun pick(control: InputControl, shown: Boolean) = stored.firstOrNull { it.id == "legacy:${control.id}" }
?: stored.firstOrNull { it.control == control && it.kind == InputElementKind.BUTTON }
?: InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE).takeIf { shown }
return listOfNotNull(
pick(InputControl.GUIDE, settings.steamButton)?.let { circle(it, safe.left + inset, bottom, radius) },
pick(InputControl.QAM, settings.qamButton)?.let { circle(it, width - safe.right - inset, bottom, radius) },
stored.firstOrNull { it.id == KEYBOARD_ID }?.let { circle(it, width / 2f, bottom, dp(KEYBOARD_RADIUS_DP)) },
)
}
fun dock(stored: List<InputSurfaceElement>, portrait: Boolean, grips: Boolean, left: InputControl = InputControl.LS,
right: InputControl = InputControl.RS): List<InputSurfaceElement> {
val boxes = GamepadGeometry.layout(width.toFloat(), height.toFloat(), resources.displayMetrics.density, portrait)
val placed = mutableListOf<InputSurfaceElement>()
fun box(control: InputControl, slot: GamepadGeometry.Slot, shape: InputButtonShape) {
val b = boxes[slot] ?: return
placed += InputSurfaceElement(control, b.left / width, b.top / height, b.width / width, b.height / height,
floating = false, buttonShape = shape).bounded()
}
fun cross(controls: List<InputControl>, slot: GamepadGeometry.Slot) {
val b = boxes[slot] ?: return
val side = min(b.width, b.height)
val spread = side * CROSS_SPREAD
val radius = side * CROSS_RADIUS
controls.zip(listOf(0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f)).forEach { (control, direction) ->
placed += circle(InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE),
b.cx + direction.first * spread, b.cy + direction.second * spread, radius)
}
}
box(left, GamepadGeometry.Slot.LEFT_MAIN, InputButtonShape.CIRCLE)
cross(DPAD_ORDER, GamepadGeometry.Slot.LEFT_SECOND)
box(right, GamepadGeometry.Slot.RIGHT_MAIN, InputButtonShape.CIRCLE)
cross(FACE_ORDER, GamepadGeometry.Slot.RIGHT_SECOND)
box(InputControl.LT, GamepadGeometry.Slot.LEFT_OUTER_SHOULDER, InputButtonShape.PILL)
box(InputControl.LB, GamepadGeometry.Slot.LEFT_INNER_SHOULDER, InputButtonShape.PILL)
box(InputControl.RB, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER, InputButtonShape.PILL)
box(InputControl.RT, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER, InputButtonShape.PILL)
box(InputControl.SELECT, GamepadGeometry.Slot.VIEW, InputButtonShape.PILL)
box(InputControl.START, GamepadGeometry.Slot.MENU, InputButtonShape.PILL)
if (grips) GRIPS.forEach { (control, slot) -> box(control, slot, InputButtonShape.ROUNDED) }
val surfaces = listOf(left, right).filter { it.isTrackpad }
return withGeometry(stored, placed) + placed.filter { p -> (GRIPS.any { it.first == p.control } || p.control in surfaces) && stored.none { it.id == p.id } }
}
private fun circle(e: InputSurfaceElement, cx: Float, cy: Float, radius: Float) =
e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height).bounded()
private fun withGeometry(stored: List<InputSurfaceElement>, placed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = placed.associateBy { it.id }
return stored.mapNotNull { e -> byId[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } }
}
private fun keyboard(): InputSurfaceElement {
val radius = dp(KEYBOARD_RADIUS_DP)
val cx = safe.left + dp(KEYBOARD_X_DP)
val cy = height - safe.bottom - dp(KEYBOARD_Y_DP)
return InputSurfaceElement(InputControl.A, (cx - radius) / width, (cy - radius) / height, 2 * radius / width, 2 * radius / height,
KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded()
}
fun restyle(elements: List<InputSurfaceElement>): List<InputSurfaceElement> {
val dpad = elements.filter { it.id == "legacy:${it.control.id}" && it.control in DPAD && it.buttonShape == InputButtonShape.ROUNDED }
val centreX = dpad.map { (it.x + it.width / 2f) * width }.average().toFloat()
val centreY = dpad.map { (it.y + it.height / 2f) * height }.average().toFloat()
val resize = untouchedDpad(dpad, centreX, centreY)
return elements.map { e ->
when {
e.id == KEYBOARD_ID && e.icon == 0 && e.name == "Keyboard" && e.buttonShape == InputButtonShape.ROUNDED &&
e.x == .02f && e.y == .9f && e.width == .12f && e.height == .08f -> keyboard()
e.id == "legacy:${e.control.id}" && e.buttonShape == InputButtonShape.ROUNDED -> {
val round = e.copy(buttonShape = if (e.control.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE)
(if (resize && e.control in DPAD) resizeDpad(round, centreX, centreY) else widenStick(round)).bounded()
}
else -> e
}
}
}
private fun untouchedDpad(dpad: List<InputSurfaceElement>, centreX: Float, centreY: Float): Boolean {
if (dpad.size != DPAD.size) return false
val radius = dpad[0].width * width / 2f
val tolerance = 1.5f
val offset = radius * LEGACY_DPAD_OFFSET_DP / LEGACY_DPAD_RADIUS_DP
return dpad.all { e ->
val old = controls.first { it.id == e.control.id }
val dx = (e.x + e.width / 2f) * width - centreX
val dy = (e.y + e.height / 2f) * height - centreY
abs(e.width * width / 2f - radius) <= tolerance && abs(e.height * height / 2f - radius) <= tolerance &&
abs(dx - offset * sign(old.offsetXDp)) <= tolerance && abs(dy - offset * sign(old.offsetYDp)) <= tolerance
}
}
private fun resizeDpad(e: InputSurfaceElement, centreX: Float, centreY: Float): InputSurfaceElement {
val old = controls.first { it.id == e.control.id }
val radius = e.width * width / 2f * old.radiusDp / LEGACY_DPAD_RADIUS_DP
val cx = centreX + ((e.x + e.width / 2f) * width - centreX) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
val cy = centreY + ((e.y + e.height / 2f) * height - centreY) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height)
}
private fun widenStick(e: InputSurfaceElement): InputSurfaceElement {
val extra = e.width * (STICK_REACH - 1f)
return when (e.control) {
InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) }
InputControl.RS -> e.copy(width = (e.width + extra).coerceAtMost(1f - e.x))
else -> e
}
}
private companion object {
const val MIN_FACE_MM = 9.5f
const val FULL_SIZE_HEIGHT_MM = 85f
const val BOTTOM_MARGIN_MM = 5f
const val DROP_DEGREES = 35.0
const val PHONE_MAX_HEIGHT_MM = 90f
const val SHOULDER_WIDTH = 1.45f
const val SHOULDER_HEIGHT = 0.8f
val shoulderIds = setOf("lb", "rb", "lt", "rt")
const val STICK_REACH = 1.25f
const val LEGACY_DPAD_RADIUS_DP = 26f
const val LEGACY_DPAD_OFFSET_DP = 52f
val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
const val KEYBOARD_ID = "builtin:keyboard"
const val KEYBOARD_RADIUS_DP = 18f
const val KEYBOARD_X_DP = 90f
const val KEYBOARD_Y_DP = 34f
const val BUTTONS_ONLY_RADIUS_DP = 30f
const val BUTTONS_ONLY_INSET_DP = 44f
const val CROSS_SPREAD = .30f
const val CROSS_RADIUS = .16f
val DPAD_ORDER = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
val FACE_ORDER = listOf(InputControl.Y, InputControl.B, InputControl.A, InputControl.X)
val GRIPS = listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
}
}
@@ -3,78 +3,102 @@ package com.droiddeck.launcher.input
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.graphics.Canvas import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint import android.graphics.Paint
import android.graphics.Rect import android.graphics.Rect
import android.graphics.RectF import android.graphics.Typeface
import android.os.Build import android.os.Build
import android.view.Gravity import android.view.Gravity
import android.view.HapticFeedbackConstants import android.view.HapticFeedbackConstants
import android.view.MotionEvent import android.view.MotionEvent
import android.view.View import android.view.View
import android.view.ViewConfiguration
import android.view.WindowInsets import android.view.WindowInsets
import android.widget.FrameLayout import android.widget.FrameLayout
import com.droiddeck.launcher.ui.InputSurfaceView import com.droiddeck.launcher.ui.InputSurfaceView
import com.droiddeck.launcher.ui.PadArt
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) { class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
/** Why the controls are hidden while the corner button stays. */
enum class Hidden { BY_TAP, BY_CONTROLLER }
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null) private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
private var layout: SavedInputLayout? = null private var layout: SavedInputLayout? = null
private val safe = Rect() private val safe = Rect()
private var viewWidth = 0 private var viewWidth = 0
private var viewHeight = 0 private var viewHeight = 0
private val corner = CornerButton(context) private val placements = object : LinkedHashMap<Placement, List<InputSurfaceElement>>(4, .75f, true) {
var hidden: Hidden? = null override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Placement, List<InputSurfaceElement>>) = size > PLACEMENT_CACHE
}
private val quickToggle = QuickToggle(context)
var isButtonsOnly = false
private set private set
/** Holding the corner button opens DroidDeck's controller menu. */ var isQuickHidden = false
var onCornerHold: (() -> Unit)? = null private set
/** The player tapped the corner button. */ var isPinnedOnly = false
var onCornerTap: ((Hidden?) -> Unit)? = null private set
val inputSurface: InputSurfaceView get() = surface val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true
var onTouchMiss: ((MotionEvent) -> Unit)? var onTouchMiss: ((MotionEvent) -> Unit)?
get() = surface.onTouchMiss get() = surface.onTouchMiss
set(value) { surface.onTouchMiss = value } set(value) { surface.onTouchMiss = value }
init { init {
addView(surface, LayoutParams(-1, -1)) addView(surface, LayoutParams(-1, -1))
val size = (CORNER_HIT_DP * resources.displayMetrics.density).toInt() val size = (QUICK_HIT_DP * 2 * resources.displayMetrics.density).toInt()
addView(corner, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM)) addView(quickToggle, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
} }
fun updateLayout(value: SavedInputLayout?) { fun updateLayout(value: SavedInputLayout?) {
val kit = PadKit.current(context) if (layout == value) return
if (layout == value && surface.kit == kit) return
releaseAll() releaseAll()
layout = value layout = value
surface.kit = kit
render() render()
} }
fun setHidden(value: Hidden?) { fun setButtonsOnly(enabled: Boolean) {
if (hidden == value) return if (isButtonsOnly == enabled) return
releaseAll() releaseAll()
hidden = value isButtonsOnly = enabled
isQuickHidden = false
render() render()
} }
fun setQuickHidden(hidden: Boolean) {
if (isButtonsOnly || isQuickHidden == hidden) return
releaseAll()
isQuickHidden = hidden
render()
}
fun setPinnedOnly(enabled: Boolean) {
if (isPinnedOnly == enabled) return
releaseAll()
isPinnedOnly = enabled
render()
}
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
private fun placed(): List<InputSurfaceElement> {
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
return placements.getOrPut(key) {
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock)
}
}
private fun render() { private fun render() {
val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock) val elements = placed()
surface.updateCustomLayout(if (hidden != null) placed.filter { it.alwaysShown } else placed) surface.updateCustomLayout(when {
surface.updateStyle(layout?.style ?: InputSurfaceStyle()) isPinnedOnly -> elements.filter { it.alwaysShown }
corner.visibility = if (layout == null || dock != null) GONE else VISIBLE isQuickHidden -> elements.filter { it.id == "builtin:keyboard" || it.alwaysShown }
corner.alpha = (layout?.style?.opacity ?: 100) / 100f else -> elements
corner.invalidate() })
val style = layout?.style ?: InputSurfaceStyle()
surface.updateStyle(style)
quickToggle.tint = style.tint
quickToggle.alpha = style.opacity / 100f
quickToggle.visibility = if (isButtonsOnly || isPinnedOnly || layout == null || dock != null) GONE else VISIBLE
quickToggle.invalidate()
} }
fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y) || fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y) ||
corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom quickToggle.visibility == VISIBLE && x >= quickToggle.left && x < quickToggle.right && y >= quickToggle.top && y < quickToggle.bottom
fun cornerTakes(x: Float, y: Float) = corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
fun releaseAll() = surface.releaseInputs() fun releaseAll() = surface.releaseInputs()
fun reload() { releaseAll(); surface.kit = PadKit.current(context); render() } fun reload() { releaseAll(); placements.clear(); render() }
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val w = MeasureSpec.getSize(widthMeasureSpec) val w = MeasureSpec.getSize(widthMeasureSpec)
@@ -91,14 +115,14 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets { override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
val margin = (CORNER_MARGIN_DP * resources.displayMetrics.density).toInt() val offset = ((QUICK_CENTER_DP - QUICK_HIT_DP) * resources.displayMetrics.density).toInt()
val params = corner.layoutParams as LayoutParams val params = quickToggle.layoutParams as LayoutParams
val left = (cutout?.safeInsetLeft ?: 0) + margin val left = (cutout?.safeInsetLeft ?: 0) + offset
val bottom = (cutout?.safeInsetBottom ?: 0) + margin val bottom = (cutout?.safeInsetBottom ?: 0) + offset
if (params.leftMargin != left || params.bottomMargin != bottom) { if (params.leftMargin != left || params.bottomMargin != bottom) {
params.leftMargin = left params.leftMargin = left
params.bottomMargin = bottom params.bottomMargin = bottom
corner.layoutParams = params quickToggle.layoutParams = params
} }
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
if (fresh != safe) { if (fresh != safe) {
@@ -108,45 +132,42 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
return super.onApplyWindowInsets(insets) return super.onApplyWindowInsets(insets)
} }
private inner class CornerButton(context: Context) : View(context) { private inner class QuickToggle(context: Context) : View(context) {
private val art = PadArt(context) var tint: Int? = ControllerPrefs.STEAM_BLUE
private val badge = Paint(Paint.ANTI_ALIAS_FLAG) private val density = resources.displayMetrics.density
private var armed = false private var armed = false
private var held = false private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val hold = Runnable { if (armed) { held = true; performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } } private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.5f * density }
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
textSize = 22 * density
}
override fun onDraw(canvas: Canvas) { override fun onDraw(canvas: Canvas) {
val w = width.toFloat(); val h = height.toFloat() val x = width / 2f
val dimmed = hidden != null && !armed val y = height / 2f
if (dimmed) canvas.saveLayerAlpha(0f, 0f, w, h, 170) val radius = QUICK_RADIUS_DP * density
art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.MARK, armed) val color = tint
if (dimmed) canvas.restore() fill.color = if (color != null) InputSurfaceView.shade(color, 190, 0.12f) else (InputSurfaceView.SURFACE and 0x00ffffff) or (190 shl 24)
if (hidden == Hidden.BY_CONTROLLER) { canvas.drawCircle(x, y, radius, fill)
val d = art.density stroke.color = if (color != null) InputSurfaceView.light(color, 150, 0.25f) else InputSurfaceView.LINE
val r = RectF(w - 15 * d, 3 * d, w - 2 * d, 12 * d) canvas.drawCircle(x, y, radius, stroke)
badge.style = Paint.Style.FILL; badge.color = Color.rgb(0x16, 0x19, 0x1E) text.color = if (color != null) InputSurfaceView.light(color, 210, 0.75f) else InputSurfaceView.TEXT
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge) canvas.drawText(if (isQuickHidden) "+" else "−", x, y + text.textSize * 0.35f, text)
badge.style = Paint.Style.STROKE; badge.strokeWidth = 1.3f * d; badge.color = Color.rgb(0xFF, 0xB3, 0x47)
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
}
} }
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean { override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) { when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> { armed = true; held = false; postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()); invalidate() } MotionEvent.ACTION_DOWN -> armed = true
MotionEvent.ACTION_CANCEL -> { armed = false; removeCallbacks(hold); invalidate() } MotionEvent.ACTION_CANCEL -> armed = false
MotionEvent.ACTION_UP -> { MotionEvent.ACTION_UP -> {
removeCallbacks(hold) if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
if (armed && held) post { onCornerHold?.invoke() }
else if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
val next = if (hidden == null) Hidden.BY_TAP else null setQuickHidden(!isQuickHidden)
setHidden(next)
onCornerTap?.invoke(next)
} }
armed = false armed = false
invalidate()
} }
} }
return true return true
@@ -154,7 +175,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
} }
private companion object { private companion object {
const val CORNER_HIT_DP = 48f const val QUICK_CENTER_DP = 34f
const val CORNER_MARGIN_DP = 4f const val QUICK_HIT_DP = 26f
const val QUICK_RADIUS_DP = 18f
const val PLACEMENT_CACHE = 4
} }
} }
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.input
import android.content.Context import android.content.Context
import android.graphics.Rect import android.graphics.Rect
import kotlin.math.abs
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
@@ -19,31 +20,25 @@ object OnScreenLayout {
} }
} }
/** private const val TOLERANCE = .01f
* The built-in gamepad keeps no kit positions until its kit is edited; until then the kit follows the virtual controller and private const val KEYBOARD_ID = "builtin:keyboard"
* the layout stores only the keys and controls the player added on top.
*/
fun generated(layout: SavedInputLayout) = (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY) &&
!layout.kitless && layout.elements.none { KitLayout.isKit(it.id) }
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null): List<InputSurfaceElement> { fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
layout ?: return emptyList() buttonsOnly: Boolean = false, dock: Dock? = null): List<InputSurfaceElement> {
if (width <= 0 || height <= 0) return layout.elements val stored = layout?.elements ?: return emptyList()
if (generated(layout)) { if (width <= 0 || height <= 0) return stored
val kit = PadKit.current(context) val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val extras = if (layout.elements.isEmpty()) emptyList() else fit(layout.elements, aspect(context, layout), 1f, width, height, safe) val (reference, generated) = reference(context, layout, width, height)
return (if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right) if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
else KitLayout.elements(context, kit, width, height, safe, layout.scale)) + extras val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
val placed = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
else -> generator.regenerate(gamepad)
} }
return fit(layout.elements, aspect(context, layout), 1f, width, height, safe) val byId = (placed + others).associateBy { it.id }
} return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect())
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = displayed.associateBy { it.id }
return layout.elements.map { byId[it.id] ?: it }
} }
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> { fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
@@ -69,8 +64,32 @@ object OnScreenLayout {
} }
} }
private fun aspect(context: Context, layout: SavedInputLayout): Float = layout.aspect.takeIf { it > 0f } ?: run { private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
val metrics = InputLibraries.primaryDisplay(context).second
max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1).toFloat() / min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1) fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
reference(context, layout, width, height).takeIf { it.second }?.first?.let { it.first.toInt() to it.second.toInt() }
private fun reference(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Pair<Float, Float>, Boolean> {
val (display, metrics) = InputLibraries.primaryDisplay(context)
val long = max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val short = min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val gamepad = layout.elements.filter(::isGamepad)
if (gamepad.any { it.id.startsWith("legacy:") }) {
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
for ((w, h) in listOfNotNull(named, width to height, long to short, short to long).distinct()) {
if (matches(gamepad, LegacyGamepadLayout(display, w, h, scale = layout.scale).elements())) return (w.toFloat() to h.toFloat()) to true
}
}
val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short)
return (aspect to 1f) to false
}
private fun matches(stored: List<InputSurfaceElement>, generated: List<InputSurfaceElement>): Boolean {
val byId = generated.associateBy { it.id }
return stored.all { e ->
val g = byId[e.id] ?: return@all false
abs(e.x - g.x) <= TOLERANCE && abs(e.y - g.y) <= TOLERANCE && abs(e.width - g.width) <= TOLERANCE && abs(e.height - g.height) <= TOLERANCE
}
} }
} }
@@ -12,8 +12,6 @@ import com.droiddeck.launcher.session.SessionState;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicIntegerArray;
public final class PadBridge { public final class PadBridge {
@@ -58,7 +56,6 @@ public final class PadBridge {
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS]; private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS]; private final PadState[] playerStates = new PadState[SLOTS];
private final float[][] rawSticks = new float[SLOTS][4]; private final float[][] rawSticks = new float[SLOTS][4];
private final Map<Integer, Boolean> rightStickLayouts = new HashMap<>();
private final boolean[][] keyTriggers = new boolean[SLOTS][2]; private final boolean[][] keyTriggers = new boolean[SLOTS][2];
private final int[] retainedSticks = new int[SLOTS]; private final int[] retainedSticks = new int[SLOTS];
private final PadState effectiveState = new PadState(); private final PadState effectiveState = new PadState();
@@ -107,8 +104,6 @@ public final class PadBridge {
private volatile Runnable onPlayerInput; private volatile Runnable onPlayerInput;
private Runnable onChordInput; private Runnable onChordInput;
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean(); private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private volatile Runnable onPhysicalInput;
private final java.util.concurrent.atomic.AtomicBoolean physicalInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private static final long STATS_WINDOW_MS = 10_000; private static final long STATS_WINDOW_MS = 10_000;
private int statButtons, statAxes, statOnScreen, statDropped; private int statButtons, statAxes, statOnScreen, statDropped;
@@ -245,7 +240,6 @@ public final class PadBridge {
clearBackQamWrites(); clearBackQamWrites();
releaseBackPaddles(); releaseBackPaddles();
activeControllerId = NO_CONTROLLER; activeControllerId = NO_CONTROLLER;
rightStickLayouts.clear();
for (int slot = 0; slot < SLOTS; slot++) { for (int slot = 0; slot < SLOTS; slot++) {
owners[slot] = NO_CONTROLLER; owners[slot] = NO_CONTROLLER;
partners[slot] = NO_CONTROLLER; partners[slot] = NO_CONTROLLER;
@@ -370,20 +364,6 @@ public final class PadBridge {
onPlayerInput = listener; onPlayerInput = listener;
} }
/** Input from a controller the player holds, never from the on-screen controls. */
public void setOnPhysicalInput(Runnable listener) {
onPhysicalInput = listener;
}
private void notePhysicalInput() {
Runnable listener = onPhysicalInput;
if (listener == null || !physicalInputPosted.compareAndSet(false, true)) return;
mainHandler.post(() -> {
physicalInputPosted.set(false);
listener.run();
});
}
public synchronized void setOnChordInput(Runnable listener) { public synchronized void setOnChordInput(Runnable listener) {
onChordInput = listener; onChordInput = listener;
} }
@@ -449,7 +429,7 @@ public final class PadBridge {
} }
noteDevice(device, slot); noteDevice(device, slot);
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot); if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
if (pressed) { notePlayerInput(); notePhysicalInput(); } if (pressed) notePlayerInput();
statButtons++; statButtons++;
scheduleStats(); scheduleStats();
publish(slot); publish(slot);
@@ -537,7 +517,7 @@ public final class PadBridge {
retainStick(slot, side, x, y); retainStick(slot, side, x, y);
projectSticks(slot); projectSticks(slot);
if (chordStickInput) noteChordInput(slot); if (chordStickInput) noteChordInput(slot);
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) { notePlayerInput(); notePhysicalInput(); } if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
publish(slot); publish(slot);
InputTiming.end(timing); InputTiming.end(timing);
return true; return true;
@@ -545,23 +525,20 @@ public final class PadBridge {
float lx = event.getAxisValue(MotionEvent.AXIS_X); float lx = event.getAxisValue(MotionEvent.AXIS_X);
float ly = event.getAxisValue(MotionEvent.AXIS_Y); float ly = event.getAxisValue(MotionEvent.AXIS_Y);
boolean wired = wiredXboxLayout(device, event.getSource()); boolean wired = wiredXboxLayout(device, event.getSource());
boolean rxRyStick = rightStickUsesRxRy(event, device, rightStickLayouts); float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
float rx = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z); float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
float ry = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
retainStick(slot, JoyCon.LEFT, lx, ly); retainStick(slot, JoyCon.LEFT, lx, ly);
retainStick(slot, JoyCon.RIGHT, rx, ry); retainStick(slot, JoyCon.RIGHT, rx, ry);
projectSticks(slot); projectSticks(slot);
int source = event.getSource(); int source = event.getSource();
float lt = 0f; float lt = 0f;
float rt = 0f; float rt = 0f;
boolean signedLeft = signedZTriggers(event, device, wired, rxRyStick, true); if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) {
boolean signedRight = signedZTriggers(event, device, wired, rxRyStick, false); lt = axisTrigger(leftTrigger(event, wired), keyTriggers[slot], 0);
if (signedLeft || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) {
lt = axisTrigger(triggerValue(event, device, wired, rxRyStick, true), keyTriggers[slot], 0);
pad.leftTrigger = lt; pad.leftTrigger = lt;
} }
if (signedRight || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) { if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) {
rt = axisTrigger(triggerValue(event, device, wired, rxRyStick, false), keyTriggers[slot], 1); rt = axisTrigger(rightTrigger(event, wired), keyTriggers[slot], 1);
pad.rightTrigger = rt; pad.rightTrigger = rt;
} }
if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) { if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) {
@@ -579,7 +556,6 @@ public final class PadBridge {
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) { || lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
notePlayerInput(); notePlayerInput();
notePhysicalInput();
} }
publish(slot); publish(slot);
InputTiming.end(timing); InputTiming.end(timing);
@@ -620,92 +596,6 @@ public final class PadBridge {
return false; return false;
} }
static boolean rightStickUsesRxRy(MotionEvent event, InputDevice device, Map<Integer, Boolean> layouts) {
int source = event.getSource();
if (wiredXboxLayout(device, source)) return true;
boolean hasRxRy = hasAxis(device, source, MotionEvent.AXIS_RX)
&& hasAxis(device, source, MotionEvent.AXIS_RY);
boolean hasZRz = hasAxis(device, source, MotionEvent.AXIS_Z)
&& hasAxis(device, source, MotionEvent.AXIS_RZ);
if (!hasRxRy) return false;
if (!hasZRz) return true;
Boolean cached = layouts.get(event.getDeviceId());
if (cached != null) return cached;
boolean rxRyEvidence = atMinimum(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)
&& nearCentre(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY);
boolean zRzEvidence = atMinimum(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY)
&& nearCentre(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ);
if (rxRyEvidence == zRzEvidence) return false;
boolean useRxRy = rxRyEvidence;
layouts.put(event.getDeviceId(), useRxRy);
return useRxRy;
}
static boolean signedZTriggers(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) {
if (wired) return true;
if (!rxRyStick) return false;
int source = event.getSource();
int signedAxis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ;
int dedicatedAxis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER;
int alternateAxis = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS;
return hasAxis(device, source, signedAxis)
&& !hasAxis(device, source, dedicatedAxis, alternateAxis);
}
static float triggerValue(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) {
if (signedZTriggers(event, device, wired, rxRyStick, left)) {
int axis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ;
float value = event.getAxisValue(axis);
if (!wired && device != null) {
InputDevice.MotionRange range = device.getMotionRange(axis, event.getSource());
if (range != null && range.getMax() > range.getMin()) {
return Math.max(0f, Math.min(1f,
(value - range.getMin()) / (range.getMax() - range.getMin())));
}
}
return Math.max(0f, Math.min(1f, (value + 1f) / 2f));
}
int source = event.getSource();
int axis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER;
int alternate = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS;
if (device == null) {
float value = event.getAxisValue(axis);
return value != 0f ? value : event.getAxisValue(alternate);
}
if (hasAxis(device, source, axis)) {
float value = event.getAxisValue(axis);
return value != 0f ? value : event.getAxisValue(alternate);
}
if (hasAxis(device, source, alternate)) return event.getAxisValue(alternate);
return 0f;
}
private static float restDistance(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
return (restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis))
+ restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis))) / 2f;
}
private static float restDistance(InputDevice.MotionRange range, float value) {
float span = range.getMax() - range.getMin();
if (span <= 0f) return 1f;
return Math.abs(value - (range.getMin() + range.getMax()) / 2f) / span;
}
private static boolean atMinimum(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
return atMinimum(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis))
&& atMinimum(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis));
}
private static boolean atMinimum(InputDevice.MotionRange range, float value) {
float span = range.getMax() - range.getMin();
return value - range.getMin() <= span * 0.02f;
}
private static boolean nearCentre(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) {
return restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) <= 0.1f
&& restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis)) <= 0.1f;
}
public interface TouchRoute { public interface TouchRoute {
boolean active(); boolean active();
@@ -1292,4 +1182,16 @@ public final class PadBridge {
&& device.getMotionRange(MotionEvent.AXIS_RZ, source) != null; && device.getMotionRange(MotionEvent.AXIS_RZ, source) != null;
} }
public static float leftTrigger(MotionEvent event, boolean wired) {
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f));
float value = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_BRAKE);
}
public static float rightTrigger(MotionEvent event, boolean wired) {
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_RZ) + 1f) / 2f));
float value = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_GAS);
}
} }
@@ -1,48 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
enum class DpadStyle { CROSS, DISC, ARROWS }
enum class StickCap { RINGED, DISHED, KNURLED }
enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) {
STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true),
DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED),
DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED);
val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER
val playStation get() = this == DUALSHOCK || this == DUALSENSE
fun label(control: InputControl): String = when (control) {
InputControl.LB -> if (xbox) "LB" else "L1"
InputControl.RB -> if (xbox) "RB" else "R1"
InputControl.LT -> if (xbox) "LT" else "L2"
InputControl.RT -> if (xbox) "RT" else "R2"
else -> control.label
}
/** What the player calls [control] on this controller. */
fun name(control: InputControl): String = if (!playStation) label(control) else when (control) {
InputControl.A -> "Cross"
InputControl.B -> "Circle"
InputControl.X -> "Square"
InputControl.Y -> "Triangle"
else -> label(control)
}
companion object {
fun of(type: String) = when (type) {
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
else -> STEAM_DECK
}
fun current(context: Context) = of(SessionPrefs.steamController(context))
}
}
@@ -42,7 +42,6 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
private val total = Sticks() private val total = Sticks()
private val triggerAxes = HashMap<Int, Boolean>() private val triggerAxes = HashMap<Int, Boolean>()
private val wiredLayout = HashMap<Int, Boolean>() private val wiredLayout = HashMap<Int, Boolean>()
private val rightStickLayouts = HashMap<Int, Boolean>()
private val down = HashMap<Int, MutableSet<Int>>() private val down = HashMap<Int, MutableSet<Int>>()
private val sent = HashMap<Int, IntArray>() private val sent = HashMap<Int, IntArray>()
private val held = LinkedHashMap<Int, Int>() private val held = LinkedHashMap<Int, Int>()
@@ -88,21 +87,14 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
fun onMotion(event: MotionEvent): Boolean { fun onMotion(event: MotionEvent): Boolean {
if (event.actionMasked != MotionEvent.ACTION_MOVE) return true if (event.actionMasked != MotionEvent.ACTION_MOVE) return true
val sticks = physical.getOrPut(event.deviceId) { Sticks() } val sticks = physical.getOrPut(event.deviceId) { Sticks() }
val device = event.device val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }
val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(device, event.source) }
val rxRyStick = PadBridge.rightStickUsesRxRy(event, device, rightStickLayouts)
sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X) sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X)
sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y) sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y)
sticks.rightX = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z) sticks.rightX = scrollAxis(event, if (wired) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z)
sticks.rightY = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ) sticks.rightY = scrollAxis(event, if (wired) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ)
val signedLeft = PadBridge.signedZTriggers(event, device, wired, rxRyStick, true) if (hasTriggerAxes(event)) {
val signedRight = PadBridge.signedZTriggers(event, device, wired, rxRyStick, false) sticks.leftTrigger = PadBridge.leftTrigger(event, wired)
val analogTriggers = hasTriggerAxes(event) sticks.rightTrigger = PadBridge.rightTrigger(event, wired)
if (analogTriggers || signedLeft) {
sticks.leftTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, true)
}
if (analogTriggers || signedRight) {
sticks.rightTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, false)
} }
val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X) val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y) val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
@@ -137,7 +129,6 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
physical.clear() physical.clear()
triggerAxes.clear() triggerAxes.clear()
wiredLayout.clear() wiredLayout.clear()
rightStickLayouts.clear()
touch.clear() touch.clear()
down.clear() down.clear()
sent.clear() sent.clear()
@@ -216,7 +207,6 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
private fun hasTriggerAxes(event: android.view.InputEvent): Boolean = triggerAxes.getOrPut(event.deviceId) { private fun hasTriggerAxes(event: android.view.InputEvent): Boolean = triggerAxes.getOrPut(event.deviceId) {
val device = event.device ?: return@getOrPut true val device = event.device ?: return@getOrPut true
device.getMotionRange(MotionEvent.AXIS_LTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_BRAKE) != null || device.getMotionRange(MotionEvent.AXIS_LTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_BRAKE) != null ||
device.getMotionRange(MotionEvent.AXIS_RTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_GAS) != null ||
(event is MotionEvent && wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }) (event is MotionEvent && wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) })
} }
@@ -25,10 +25,7 @@ data class PhysicalInputKey(val device: String, val name: String, val keyCode: I
data class PhysicalInputBinding(val key: PhysicalInputKey, val action: InputAction) data class PhysicalInputBinding(val key: PhysicalInputKey, val action: InputAction)
class PhysicalInputBindings( class PhysicalInputBindings(private val router: InputRouter) {
private val router: InputRouter,
private val onPress: (KeyEvent) -> Unit = {},
) {
private class Entry(val binding: PhysicalInputBinding, val channel: InputRouter.Channel) { private class Entry(val binding: PhysicalInputBinding, val channel: InputRouter.Channel) {
var heldDevice = -1 var heldDevice = -1
var suppressed = false var suppressed = false
@@ -69,10 +66,7 @@ class PhysicalInputBindings(
if (identity != key.device) continue if (identity != key.device) continue
entry.heldDevice = event.deviceId entry.heldDevice = event.deviceId
entry.suppressed = event.repeatCount != 0 entry.suppressed = event.repeatCount != 0
if (!entry.suppressed) { if (!entry.suppressed) entry.channel.update(1f)
entry.channel.update(1f)
onPress(event)
}
return true return true
} }
return false return false
@@ -42,7 +42,6 @@ class ScrollTouchGestures(
private var flingY = 0f private var flingY = 0f
private var flingAt = 0L private var flingAt = 0L
private var flinging = false private var flinging = false
var clicks = true
private val longPress = Runnable { private val longPress = Runnable {
held = true held = true
@@ -87,7 +86,7 @@ class ScrollTouchGestures(
lastY = startY lastY = startY
tracker = VelocityTracker.obtain().also { it.addMovement(event) } tracker = VelocityTracker.obtain().also { it.addMovement(event) }
listener.onMove(startX, startY) listener.onMove(startX, startY)
if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS) handler.postDelayed(longPress, TouchTiming.HOLD_MS)
} }
MotionEvent.ACTION_MOVE -> { MotionEvent.ACTION_MOVE -> {
val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true
@@ -154,7 +153,6 @@ class ScrollTouchGestures(
private fun click(button: Int) { private fun click(button: Int) {
releaseClick() releaseClick()
if (!clicks) return
listener.onButton(button, true) listener.onButton(button, true)
clicked = button clicked = button
handler.postDelayed(clickUp, TouchTiming.CLICK_MS) handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
@@ -40,18 +40,6 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
data class SecondScreenDisplay(val id: Int, val label: String) data class SecondScreenDisplay(val id: Int, val label: String)
object SecondScreenDisplays { object SecondScreenDisplays {
fun selection(selected: Int, available: List<Int>, gameRequested: Boolean): Int =
if (selected in available || gameRequested && selected >= 0) selected else available.firstOrNull() ?: -1
fun selection(selected: Int, available: List<Int>, gameRequested: Boolean, save: (Int) -> Unit): Int =
selection(selected, available, gameRequested).also { if (it != selected) save(it) }
fun keyboardOnPrimary(gameRequested: Boolean, selected: Int, available: List<Int>, visible: Boolean = true, taken: (Int) -> Boolean): Boolean =
visible && gameRequested && selected >= 0 && (selected !in available || taken(selected))
fun routeKeyboard(steam: Boolean, enabled: Boolean, panel: Boolean, dock: Boolean, primaryFallback: Boolean): Boolean =
steam && enabled && (panel || dock || primaryFallback)
fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List<SecondScreenDisplay> = fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List<SecondScreenDisplay> =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION) displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
.asSequence() .asSequence()
@@ -178,56 +178,4 @@ class ShortcutsRelay : Service(), InputManager.InputDeviceListener {
private companion object { private companion object {
const val KEY_TIMEOUT_MS = 200L const val KEY_TIMEOUT_MS = 200L
} }
// Frontends such as Cocoon treat a running player process as an open game, so the relay runs only while a screen is started.
object Holder : android.app.Application.ActivityLifecycleCallbacks, android.content.ServiceConnection {
private const val RELEASE_MS = 1_000L
private val handler = Handler(Looper.getMainLooper())
private var app: android.app.Application? = null
private var started = 0
private var bound = false
private val release = Runnable { unbind() }
fun install(application: android.app.Application) {
app?.unregisterActivityLifecycleCallbacks(this)
handler.removeCallbacks(release)
started = 0
bound = false
app = application
application.registerActivityLifecycleCallbacks(this)
}
override fun onActivityStarted(activity: android.app.Activity) {
started++
handler.removeCallbacks(release)
if (!bound) bind()
}
override fun onActivityStopped(activity: android.app.Activity) {
started = (started - 1).coerceAtLeast(0)
if (started == 0) handler.postDelayed(release, RELEASE_MS)
}
private fun bind() {
val context = app ?: return
if (runCatching { context.packageManager.getPackageInfo(Relay.PACKAGE, 0) }.isFailure) return
bound = runCatching {
context.bindService(Intent(context, ShortcutsRelay::class.java), this, Context.BIND_AUTO_CREATE)
}.getOrDefault(false)
}
private fun unbind() {
if (!bound) return
bound = false
runCatching { app?.unbindService(this) }
}
override fun onServiceConnected(name: android.content.ComponentName?, service: IBinder?) = Unit
override fun onServiceDisconnected(name: android.content.ComponentName?) = Unit
override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
override fun onActivityResumed(activity: android.app.Activity) = Unit
override fun onActivityPaused(activity: android.app.Activity) = Unit
override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
override fun onActivityDestroyed(activity: android.app.Activity) = Unit
}
} }
@@ -20,11 +20,7 @@ import java.util.ArrayDeque
import java.util.UUID import java.util.UUID
@SuppressLint("MissingPermission") @SuppressLint("MissingPermission")
class SteamControllerBle( class SteamControllerBle(private val context: Context, router: InputRouter? = null) {
private val context: Context,
router: InputRouter? = null,
private val onPhysicalInput: (() -> Unit)? = null,
) {
private val inputLock = router ?: Any() private val inputLock = router ?: Any()
private var routedInput = router?.let(::TritonInputRouter) private var routedInput = router?.let(::TritonInputRouter)
@Volatile private var stopped = false @Volatile private var stopped = false
@@ -43,7 +39,6 @@ class SteamControllerBle(
private var outputSequence = 0L private var outputSequence = 0L
private var outputWritePending = false private var outputWritePending = false
private var featureRead = 0L private var featureRead = 0L
private var lastPressedControls = 0
fun start(): Unit = synchronized(inputLock) { fun start(): Unit = synchronized(inputLock) {
if (stopped || started) return@synchronized if (stopped || started) return@synchronized
@@ -271,18 +266,12 @@ class SteamControllerBle(
val timing = InputTiming.begin() val timing = InputTiming.begin()
FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data) FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data)
InputTiming.end(timing) InputTiming.end(timing)
if (connected && onPhysicalInput != null) {
val pressed = TritonInputRouter.pressedControls(data)
if (pressed and lastPressedControls.inv() != 0) onPhysicalInput()
lastPressedControls = pressed
}
} }
private fun release() = synchronized(inputLock) { private fun release() = synchronized(inputLock) {
if (stopped) return@synchronized if (stopped) return@synchronized
routedInput?.release() routedInput?.release()
withSlot { withSlot {
lastPressedControls = 0
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES)) FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
} }
} }
@@ -119,7 +119,6 @@ class SteamTouchControls(
private var selectedArm = 0 private var selectedArm = 0
private val fill = Paint(Paint.ANTI_ALIAS_FLAG) private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val art = com.droiddeck.launcher.ui.PadArt(context)
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; isFakeBoldText = true } private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; isFakeBoldText = true }
@@ -241,10 +240,7 @@ class SteamTouchControls(
private fun cx(e: Element) = e.x * width private fun cx(e: Element) = e.x * width
private fun cy(e: Element) = e.y * height private fun cy(e: Element) = e.y * height
private fun reach(e: Element, x: Float, y: Float): Float { private fun reach(e: Element, x: Float, y: Float) = hypot((x - cx(e)) / radius(e), (y - cy(e)) / radiusY(e))
val dx = (x - cx(e)) / radius(e); val dy = (y - cy(e)) / radiusY(e)
return if (e.type in TRACKPADS) max(abs(dx), abs(dy)) else hypot(dx, dy)
}
private fun hit(list: List<Element>, x: Float, y: Float): Element? = private fun hit(list: List<Element>, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) } list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
@@ -285,61 +281,58 @@ class SteamTouchControls(
val r = radius(e) val r = radius(e)
val pressed = !editing && e.type in pressedTypes() val pressed = !editing && e.type in pressedTypes()
val alpha = (255 * alphaScale * if (faded) FADED else 1f).toInt().coerceIn(30, 255) val alpha = (255 * alphaScale * if (faded) FADED else 1f).toInt().coerceIn(30, 255)
stroke.color = Color.rgb(Color.red(tint), Color.green(tint), Color.blue(tint)); stroke.strokeWidth = lineWidth() val ink = Color.argb(alpha, Color.red(tint), Color.green(tint), Color.blue(tint))
fill.color = Color.argb(217, 230, 233, 236) stroke.color = if (isSelected) Color.rgb(26, 159, 255) else ink
if (alpha < 255) canvas.saveLayerAlpha(x - r * 1.5f, y - r * 1.5f, x + r * 1.5f, y + r * 1.5f, alpha) stroke.strokeWidth = if (isSelected) lineWidth() * 2f else lineWidth()
fill.color = Color.argb((alpha * 0.85f).toInt(), 230, 233, 236)
text.color = ink
text.typeface = android.graphics.Typeface.DEFAULT_BOLD
when (e.type) { when (e.type) {
SteamTouchConfig.DPAD -> if (visuals[SteamTouchConfig.DPAD].orEmpty().any { it.binding?.hasIcon == true }) drawDpad(canvas, e, x, y, r) else { SteamTouchConfig.DPAD -> drawDpad(canvas, e, x, y, r)
val bits = if (editing) 0L else dpadBits(e)
val held = (if (bits and DPAD_UP != 0L) 1 else 0) or (if (bits and DPAD_RIGHT != 0L) 2 else 0) or
(if (bits and DPAD_DOWN != 0L) 4 else 0) or (if (bits and DPAD_LEFT != 0L) 8 else 0)
canvas.save(); canvas.translate(x - r, y - r)
art.dpad(canvas, 2 * r, 2 * r, PadKit.STEAM_DECK, held, ink = glyphInk())
canvas.restore()
}
SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> { SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> {
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing } canvas.drawCircle(x, y, r, stroke)
var kx = 0f; var ky = 0f val f = fingers.values.firstOrNull { it.element?.type == e.type }
if (f != null) { if (f != null && !editing) {
val d = hypot(f.x - x, f.y - y) val d = hypot(f.x - x, f.y - y)
val k = if (d > r) r / d else 1f val k = if (d > r) r / d else 1f
kx = (f.x - x) * k * .54f; ky = (f.y - y) * k * .54f val kx = x + (f.x - x) * k
val ky = y + (f.y - y) * k
canvas.drawCircle(kx, ky, r * 0.42f, fill)
} }
art.stick(canvas, x, y, r, PadKit.STEAM_DECK, kx, ky, f != null)
} }
SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> { SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> {
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing } val rect = RectF(x - r * 1.3f, y - r * 0.85f, x + r * 1.3f, y + r * 0.85f)
canvas.save(); canvas.translate(x - r, y - r) if (pressed) canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, fill)
art.trackpad(canvas, r * 2f, r * 2f, f != null, (f?.x ?: x) - x + r, (f?.y ?: y) - y + r) canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, stroke)
canvas.restore() if (editing) {
if (editing) art.text(canvas, context.getString(R.string.deck_surface_trackpad), x, y, r * .3f, Color.argb(128, 255, 255, 255)) text.textSize = r * 0.3f
text.color = Color.argb(alpha / 2, 255, 255, 255)
canvas.drawText(context.getString(R.string.deck_surface_trackpad), x, y - (text.descent() + text.ascent()) / 2, text)
}
}
SteamTouchConfig.STEAM -> {
if (isSelected) canvas.drawCircle(x, y, r, stroke)
drawMark(canvas, x, y, r * 0.5f, if (pressed) accent else ink, alpha)
} }
SteamTouchConfig.STEAM -> systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.PILL, com.droiddeck.launcher.ui.PadArt.Icon.STEAM, pressed)
SteamTouchConfig.SELECT, SteamTouchConfig.START -> { SteamTouchConfig.SELECT, SteamTouchConfig.START -> {
val binding = visuals[e.type]?.firstOrNull()?.binding val binding = visuals[e.type]?.firstOrNull()?.binding
if (binding?.hasIcon == true) drawFace(canvas, e.type, binding, x, y, r, pressed) if (binding?.hasIcon == true) {
else systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.CHIP, drawFace(canvas, e.type, binding, x, y, r, alpha, pressed); return
if (e.type == SteamTouchConfig.START) com.droiddeck.launcher.ui.PadArt.Icon.MENU else com.droiddeck.launcher.ui.PadArt.Icon.VIEW, pressed) }
val rect = RectF(x - r * 1.08f, y - r * 0.55f, x + r * 1.08f, y + r * 0.55f)
if (pressed) canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, fill)
canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, stroke)
val t = r * 0.26f
val dir = if (e.type == SteamTouchConfig.START) 1f else -1f
val tri = Path().apply {
moveTo(x + dir * t, y); lineTo(x - dir * t * 0.75f, y - t); lineTo(x - dir * t * 0.75f, y + t); close()
}
canvas.drawPath(tri, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (pressed) Color.argb(alpha, 23, 26, 33) else ink })
} }
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, pressed) else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, alpha, pressed)
}
if (alpha < 255) canvas.restore()
if (isSelected) {
stroke.color = accent; stroke.strokeWidth = lineWidth() * 2f
if (isSquare(e.type)) canvas.drawRoundRect(RectF(x - r, y - r, x + r, y + r), r * .3f, r * .3f, stroke) else canvas.drawCircle(x, y, r, stroke)
} }
} }
private fun systemButton(canvas: Canvas, x: Float, y: Float, r: Float, shape: com.droiddeck.launcher.ui.PadArt.Shape,
icon: com.droiddeck.launcher.ui.PadArt.Icon, pressed: Boolean) {
canvas.save(); canvas.translate(x - r * 1.4f, y - r * 1.4f)
art.system(canvas, r * 2.8f, r * 2.8f, shape, icon, pressed, glyphInk())
canvas.restore()
}
/** Glyphs follow the colour picked for Steam touch controls; white keeps the shared artwork's own ink. */
private fun glyphInk() = if (tint != Color.WHITE) tint else com.droiddeck.launcher.ui.PadArt.INK
private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT, private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT,
SteamTouchConfig.TRIGGER_LEFT, SteamTouchConfig.TRIGGER_RIGHT, SteamTouchConfig.THUMB, SteamTouchConfig.KEYBOARD, SteamTouchConfig.TRIGGER_LEFT, SteamTouchConfig.TRIGGER_RIGHT, SteamTouchConfig.THUMB, SteamTouchConfig.KEYBOARD,
SteamTouchConfig.PASTE, SteamTouchConfig.MACRO_1_FINGER, SteamTouchConfig.MACRO_2_FINGER) || SteamTouchConfig.PASTE, SteamTouchConfig.MACRO_1_FINGER, SteamTouchConfig.MACRO_2_FINGER) ||
@@ -357,29 +350,53 @@ class SteamTouchControls(
canvas.restore() canvas.restore()
} }
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float, pressed: Boolean) { private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
val shape = if (isSquare(type)) art.roundRect(x - r, y - r, x + r, y + r, r * .3f) else art.circle(x, y, r) alpha: Int, pressed: Boolean) {
val square = isSquare(type)
val rect = RectF(x - r, y - r, x + r, y + r)
val corner = r * 0.3f
fun shape(paint: Paint) = if (square) canvas.drawRoundRect(rect, corner, corner, paint) else canvas.drawCircle(x, y, r, paint)
val icon = binding?.icon?.takeIf { it.isNotEmpty() }?.let(::iconOrLoad) val icon = binding?.icon?.takeIf { it.isNotEmpty() }?.let(::iconOrLoad)
val custom = binding != null && binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
art.glass(canvas, shape, pressed && !custom, if (custom) parseColor(binding!!.background, SteamTouchBindings.DEFAULT_BACKGROUND) else 0x850E1014.toInt())
val ink = if (pressed && !custom) com.droiddeck.launcher.ui.PadArt.ON_ACCENT else glyphInk()
if (icon != null) { if (icon != null) {
val s = r * 0.62f val s = r * 0.62f
if (custom) canvas.drawBitmap(tinted(binding!!.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s), Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)) val custom = binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
else canvas.drawBitmap(inked(binding!!.icon, icon), null, RectF(x - s, y - s, x + s, y + s), if (custom) {
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN) }) shape(Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = parseColor(binding.background, SteamTouchBindings.DEFAULT_BACKGROUND)
this.alpha = if (pressed) alpha else (alpha * 0.85f).toInt()
})
canvas.drawBitmap(tinted(binding.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { this.alpha = alpha })
} else {
if (pressed) shape(fill)
val ink = if (pressed) Color.argb(alpha, 23, 26, 33) else stroke.color
canvas.drawBitmap(inked(binding.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply {
colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN)
})
}
shape(stroke)
return return
} }
if (type == SteamTouchConfig.THUMB) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.QAM, ink); return } if (pressed) shape(fill)
if (type == SteamTouchConfig.KEYBOARD) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.KEYBOARD, ink); return } shape(stroke)
val shown = label(type) if (type == SteamTouchConfig.THUMB) { drawDots(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
val size = when { if (type == SteamTouchConfig.KEYBOARD) { drawKeyboardGlyph(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
val own = label(type)
val shown = own
text.textSize = when {
shown.length <= 1 -> r * 0.9f shown.length <= 1 -> r * 0.9f
shown.length <= 2 -> r * 0.66f shown.length <= 2 -> r * 0.66f
shown.length <= 5 -> r * 0.4f shown.length <= 5 -> r * 0.4f
else -> r * 0.3f else -> r * 0.3f
} }
art.text(canvas, if (shown.length > 10) shown.take(9) + "…" else shown, x, y, size, ink, r * 1.8f) text.color = when {
pressed -> Color.argb(alpha, 23, 26, 33)
shown == own -> LABEL_COLORS[type]?.let { Color.argb(alpha, Color.red(it), Color.green(it), Color.blue(it)) } ?: text.color
else -> text.color
}
val line = if (shown.length > 10) shown.take(9) + "…" else shown
canvas.drawText(line, x, y - (text.descent() + text.ascent()) / 2, text)
} }
private fun drawDots(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) { private fun drawDots(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
@@ -387,6 +404,15 @@ class SteamTouchControls(
for (i in -1..1) canvas.drawCircle(x + i * r * 0.3f, y + r * 0.22f, r * 0.08f, p) for (i in -1..1) canvas.drawCircle(x + i * r * 0.3f, y + r * 0.22f, r * 0.08f, p)
} }
private fun drawKeyboardGlyph(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = lineWidth() * 0.8f }
val body = RectF(x - r * 0.6f, y - r * 0.34f, x + r * 0.6f, y + r * 0.34f)
canvas.drawRoundRect(body, r * 0.08f, r * 0.08f, p)
val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }
for (row in 0..1) for (i in 0..5) canvas.drawCircle(body.left + r * 0.15f + i * r * 0.18f, body.top + r * 0.18f + row * r * 0.17f, r * 0.035f, dot)
canvas.drawLine(x - r * 0.3f, body.bottom - r * 0.14f, x + r * 0.3f, body.bottom - r * 0.14f, p)
}
private val iconsLoading = HashSet<String>() private val iconsLoading = HashSet<String>()
private val inkedIcons = android.util.LruCache<String, android.graphics.Bitmap>(48) private val inkedIcons = android.util.LruCache<String, android.graphics.Bitmap>(48)
@@ -1452,7 +1478,6 @@ class SteamTouchControls(
var onSaved: () -> Unit = {} var onSaved: () -> Unit = {}
companion object { companion object {
private val TRACKPADS = setOf(SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER)
private const val TAG = "SteamTouch" private const val TAG = "SteamTouch"
private const val POLL_MS = 150L private const val POLL_MS = 150L
private const val MOVE_REDRAW_MS = 33L private const val MOVE_REDRAW_MS = 33L
@@ -1494,5 +1519,11 @@ class SteamTouchControls(
put(SteamTouchConfig.PASTE, 0L) put(SteamTouchConfig.PASTE, 0L)
} }
private val LABEL_COLORS = mapOf(
SteamTouchConfig.A to Color.rgb(72, 133, 48),
SteamTouchConfig.B to Color.rgb(211, 68, 37),
SteamTouchConfig.X to Color.rgb(23, 60, 184),
SteamTouchConfig.Y to Color.rgb(235, 200, 70),
)
} }
} }
@@ -17,11 +17,6 @@ class TouchpadGestures(
var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f) var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f)
var sensitivity = 1.15f var sensitivity = 1.15f
var desktop = false var desktop = false
var clicks = true
set(value) {
if (field != value) lastTapAt = 0L
field = value
}
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(Looper.getMainLooper())
private var lastX = 0f private var lastX = 0f
@@ -55,17 +50,12 @@ class TouchpadGestures(
held = true held = true
dragging = true dragging = true
listener.onLongPress() listener.onLongPress()
press(PointerGestures.BTN_LEFT) listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
} }
private val clickUp = Runnable { releaseClick() } private val clickUp = Runnable { releaseClick() }
private fun press(button: Int) {
if (clicks) listener.onButton(button, true, x, y)
}
private fun click(button: Int) { private fun click(button: Int) {
releaseClick() releaseClick()
if (!clicks) return
listener.onButton(button, true, x, y) listener.onButton(button, true, x, y)
clicked = button clicked = button
handler.postDelayed(clickUp, TouchTiming.CLICK_MS) handler.postDelayed(clickUp, TouchTiming.CLICK_MS)
@@ -118,12 +108,12 @@ class TouchpadGestures(
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
fingers = 1; pinching = false fingers = 1; pinching = false
anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false
if (clicks && event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) { if (event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) {
dragging = true dragging = true
press(PointerGestures.BTN_LEFT) listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
} else { } else {
dragging = false dragging = false
if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS) handler.postDelayed(longPress, TouchTiming.HOLD_MS)
} }
return true return true
} }
@@ -163,7 +153,7 @@ class TouchpadGestures(
secondWasTap = false secondWasTap = false
if (!dragging) { if (!dragging) {
dragging = true dragging = true
press(PointerGestures.BTN_LEFT) listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
} }
} }
} }
@@ -63,25 +63,16 @@ class TritonInputRouter(private val router: InputRouter) {
fun release() = synchronized(router) { channels.forEach { it.release() }; last = null } fun release() = synchronized(router) { channels.forEach { it.release() }; last = null }
fun close() = synchronized(router) { release(); channels.forEach { it.close() }; router.removeSnapshot(snapshot) } fun close() = synchronized(router) { release(); channels.forEach { it.close() }; router.removeSnapshot(snapshot) }
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
private fun putBits(data: ByteArray, value: Int) { for (i in 0..3) data[i + 1] = (value ushr (i * 8)).toByte() } private fun putBits(data: ByteArray, value: Int) { for (i in 0..3) data[i + 1] = (value ushr (i * 8)).toByte() }
private fun short(data: ByteArray, offset: Int) = ((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
private fun axis(data: ByteArray, offset: Int): Float = short(data, offset).let { it / if (it < 0) 32768f else 32767f } private fun axis(data: ByteArray, offset: Int): Float = short(data, offset).let { it / if (it < 0) 32768f else 32767f }
private fun shortValue(value: Float) = (value * if (value < 0f) 32768f else 32767f).roundToInt().coerceIn(-32768, 32767) private fun shortValue(value: Float) = (value * if (value < 0f) 32768f else 32767f).roundToInt().coerceIn(-32768, 32767)
private fun putShort(data: ByteArray, offset: Int, value: Int) { data[offset] = value.toByte(); data[offset + 1] = (value shr 8).toByte() } private fun putShort(data: ByteArray, offset: Int, value: Int) { data[offset] = value.toByte(); data[offset + 1] = (value shr 8).toByte() }
companion object { companion object {
private const val CONTROL_BITS = 0x0fffffff private const val CONTROL_BITS = 0x0fffffff
internal fun pressedControls(data: ByteArray): Int {
var active = bits(data) and CONTROL_BITS
if ((5..15 step 2).any { kotlin.math.abs(short(data, it)) > 16384 }) active = active or (1 shl 28)
return active
}
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
private fun short(data: ByteArray, offset: Int) =
((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
private fun bit(c: InputControl): Int = when (c) { private fun bit(c: InputControl): Int = when (c) {
InputControl.A -> 0x1; InputControl.B -> 0x2; InputControl.X -> 0x4; InputControl.Y -> 0x8 InputControl.A -> 0x1; InputControl.B -> 0x2; InputControl.X -> 0x4; InputControl.Y -> 0x8
InputControl.QAM -> 0x10; InputControl.R3 -> 0x20; InputControl.START -> 0x40 InputControl.QAM -> 0x10; InputControl.R3 -> 0x20; InputControl.START -> 0x40
@@ -218,15 +218,12 @@ object BwrapSpawner {
private fun runtimeLib(rootfs: String, name: String): File? = private fun runtimeLib(rootfs: String, name: String): File? =
LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() } LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() }
internal fun gpu( private fun gpu(rootfs: String, root: File, env: MutableMap<String, String>): List<Bind>? {
rootfs: String, root: File, env: MutableMap<String, String>,
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(),
): List<Bind>? {
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) } 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 || !File("/dev/kgsl-3d0").exists()) 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
if (env["LIBGL_ALWAYS_SOFTWARE"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null if (env["BL_DESKTOP"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null
val binds = arrayListOf(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_freedreno.so")) val binds = arrayListOf(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_freedreno.so"))
for (name in GPU_LIBS) { for (name in GPU_LIBS) {
val f = runtimeLib(rootfs, name) ?: continue val f = runtimeLib(rootfs, name) ?: continue
@@ -21,10 +21,6 @@ object LegacyNames {
"etc/bannerlator-network.json" to "etc/droiddeck-network.json", "etc/bannerlator-network.json" to "etc/droiddeck-network.json",
"etc/bannerlator-wifi-scan-request" to "etc/droiddeck-wifi-scan-request", "etc/bannerlator-wifi-scan-request" to "etc/droiddeck-wifi-scan-request",
) )
private val RETIRED_FILES = listOf("libblsession.so", "libblfastpath.so", "libblaudit.so").map { "usr/local/lib/$it" } +
listOf("x86_64", "i386").map { "usr/local/lib/droiddeck-fex/$it/libblsession.so" }
private const val LEGACY_MARKER = ".bl-"
private val QUEUED_MARKERS = setOf(".bl-proton-extra", ".bl-steam-urls")
private val MENU_REWRITES = listOf( private val MENU_REWRITES = listOf(
Triple("usr/local/share/applications", "/usr/local/bin/bannerlator-", "/usr/local/bin/droiddeck-"), Triple("usr/local/share/applications", "/usr/local/bin/bannerlator-", "/usr/local/bin/droiddeck-"),
Triple("usr/share/applications", "Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/", Triple("usr/share/applications", "Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/",
@@ -42,20 +38,6 @@ object LegacyNames {
fun migrateRootfs(root: File) { fun migrateRootfs(root: File) {
migrateEtc(root) migrateEtc(root)
for ((old, new) in MOVED_FILES) move(File(root, old), File(root, new)) for ((old, new) in MOVED_FILES) move(File(root, old), File(root, new))
for (path in RETIRED_FILES) File(root, path).delete()
File(root, "root").listFiles { f -> f.name.startsWith(LEGACY_MARKER) }?.forEach {
val target = File(it.parentFile, ".dd-" + it.name.removePrefix(LEGACY_MARKER))
if (it.name in QUEUED_MARKERS && it.isFile && !isLink(it) && target.isFile && !isLink(target)) {
val queued = it.readText()
if (queued.isNotBlank()) {
val separator = if (target.length() > 0 && !target.readText().endsWith("\n")) "\n" else ""
target.appendText(separator + if (queued.endsWith("\n")) queued else queued + "\n")
}
FileUtils.delete(it)
} else {
move(it, target)
}
}
linkScripts(root) linkScripts(root)
rewriteMenuEntries(root) rewriteMenuEntries(root)
} }
@@ -9,7 +9,7 @@ import java.security.MessageDigest
object ProotFastPath { object ProotFastPath {
private const val TAG = "ProotFastPath" private const val TAG = "ProotFastPath"
const val LIBRARY = "/usr/local/lib/libddfastpath.so" const val LIBRARY = "/usr/local/lib/libblfastpath.so"
const val MAX_BINDS = 256 const val MAX_BINDS = 256
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean = fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
@@ -315,11 +315,11 @@ object BottomDesktop {
main.post { if (generation == guestGeneration) watchIme(imeDir) } main.post { if (generation == guestGeneration) watchIme(imeDir) }
val binds = LinuxRuntime.binds(context, current.sessionRoot, runtime, Environment.getExternalStorageDirectory(), current.binds) val binds = LinuxRuntime.binds(context, current.sessionRoot, runtime, Environment.getExternalStorageDirectory(), current.binds)
val guest = ArrayList(current.guest).apply { val guest = ArrayList(current.guest).apply {
add("DD_WIDTH=$width") add("BL_WIDTH=$width")
add("DD_HEIGHT=$height") add("BL_HEIGHT=$height")
add("DD_DEBUG_DIR=" + dir.path) add("BL_DEBUG_DIR=" + dir.path)
add("DD_TOP_SESSION=" + SessionState.mode) add("BL_TOP_SESSION=" + SessionState.mode)
add("DD_IME_DIR=" + imeDir.path) add("BL_IME_DIR=" + imeDir.path)
add(SCRIPT) add(SCRIPT)
} }
val command = if (current.nativeUserland) { val command = if (current.nativeUserland) {
Loaded 100 of 717 files, more files were not shown because too many files have changed in this diff. Show more