Compare commits

...
Author SHA1 Message Date
Kurt Himebauch 4eda6abf92 ci: pin the Python tests to the hosted runner and set up Node 2026-11-11 19:53:56 +00:00
Kurt Himebauch 5b5c65246f Merge branch 'main' into ci/python-tests-on-workstation-runner 2026-11-11 14:36:06 -05:00
Kurt Himebauch 9d99232f99 feat(agent): the agent's commits and pull requests carry no Claude credit by default (#2482)
feat(agent): Claude Code commits and pull requests carry no co-author or Claude Code credit by default
2026-11-11 14:32:29 -05:00
Kurt Himebauch 9a6d770c1d ci: install Node for the Python tests on either runner and update the job-dependency test 2026-11-11 19:32:10 +00:00
Kurt Himebauch dc38a56418 Merge branch 'main' into ci/python-tests-on-workstation-runner 2026-11-11 14:14:30 -05:00
Kurt Himebauch 2426ea793a fix(ctl): long agent calls over the broadcast bridge no longer make Android report DroidDeck as not responding (#2363) 2026-11-11 14:11:31 -05:00
Kurt Himebauch db933e4232 feat(agent): an Agent tab, a session drawer page, and a bubble over the game (#2376)
* feat(agent): an Agent tab in the launcher that talks to Claude Code outside any session

* feat(agent): the agent in the session drawer and as a bubble over the game

* fix(agent): connect loopback adb, show unread replies, and fit the drawer page to the screen

* feat(agent): first-run setup in the Agent tab, a harness choice with Codex, and no permission prompts

* fix(agent): install helpers off the main thread and offer sign-in only after the install

* fix(agent): connect adb only for commands that use it and run setup checks one at a time

* fix(agent): show why a setup check failed

* fix(agent): each harness has its own setup state and conversation

* fix(agent): start the adb server before connecting and retry the connection check

* fix(agent): switching harness clears the previous harness's setup results

* feat(agent): a header, a composer with send and stop, and Markdown replies in the agent chat

* fix(agent): leave room under the chat composer

* feat(agent): continue the conversation after a Lab build restarts the app

* feat(agent): show and remove what the agent stores in the Linux userland

* fix(agent): the build tools take about 5 GB

* feat(agent): DroidDeck opens on the Agent tab after restarting on a Lab build

* feat(agent): conversation history, model and plan mode, live replies, full tool input and output, processes, attachments, queued messages and a Stop that ends the turn

* fix(agent): check the Lab build less often while nothing is happening

* fix(agent): an old Lab build's progress is not shown as a failure, and a restart counts as success

* feat(agent): rebuild a kept Lab build from Updates, and tidy the chat's tool rows, costs, processes and times

* feat(agent): a setup step that prepares fast Lab builds for the installed version, kept alive while it runs

* fix(agent): the notification names a prepare and shows its percent without repeating the title

* fix(agent): run the agent's Lab builds in the app's own process and continue the conversation that asked after the restart

* fix(agent): setup's prepare runs the build itself instead of handing it to the app

* feat(agent): a turn that ends without a reply says so and offers Retry, the resume is retried once, and each turn's raw output is kept

* fix(agent): keep the previous turn's raw output too

* fix(agent): a resumed Claude Code turn no longer ends at the result for a background task the last run left behind

* fix(agent): install Codex's code-mode host with it, without which Codex runs no commands

* feat(agent): setup and storage collapse into a summary card like Setup's, and Codex tool rows show the command without its shell wrapper

* feat(agent): drop the agent bubble over sessions for now; the drawer keeps the agent

* fix(agent): the Agent tab shows once the Linux runtime is downloaded, even while its proot pack is still being fetched

* fix(agent): before the install brings adb, the connection step checks the app's own pairing instead of failing with adb not found

* fix(agent): proot's binding warnings are not shown as a setup step's reason

* fix(agent): the session drawer's Agent page fills the height under the drawer's header instead of a guess from the screen height

* fix(agent): write the browser and GitHub helpers before every setup step, not only the install

* fix(agent): find Wireless debugging's current port when the saved one no longer answers, so sign-ins open the browser after it restarts

* fix(agent): only take a Wireless debugging port that answers, since mDNS can still advertise an old one

* fix(agent): find a loopback Wireless debugging port by scanning when mDNS advertises none

* fix(agent): keep a Codex turn going through reconnect notices and read gh login's status reliably

* fix(agent): time out hung setup checks and keep their results and actions with their harness

* fix(agent): keep the draft across settings and show the Agent tab once the runtime installs

* fix(agent): keep the backslash when quoting apostrophes in a URL the browser helper opens

* fix(agent): refresh apt's package lists before installing, since a fresh Linux runtime ships without them

* fix(agent): sign-in links open through the app itself, so they work without Wireless debugging

* fix(agent): the connection step passes only when adb really reaches the device, not on adb's own error

* fix(agent): say Wireless debugging isn't reachable instead of adb's error

* fix(agent): keep prompts, tool ids, attachments and retries with their own turn and chat

* fix(agent): the service stops only once foreground, and Rebuild waits for a ready agent

* fix(agent): the Codex install says what it is downloading, so a long download doesn't look stuck

* fix(agent): pass the prompt to both CLIs the way they were tested on devices

* fix(agent): the browser helper uses the running app's files directory, falls back to adb when the app cannot open a link, and the link is not logged
2026-11-11 14:10:02 -05:00
Kurt Himebauch 9eabb296a2 Merge branch 'main' into ci/python-tests-on-workstation-runner 2026-11-11 13:42:14 -05:00
Kurt Himebauch 61031e3c4b feat(lab): build and run Lab builds of DroidDeck on the device itself (#2375)
* feat(lab): load an on-device Lab build over the installed app

* feat(lab): build Lab builds on the device and report the APK commit to agents

* fix(lab): dd-agent connects loopback adb before starting Claude Code

* feat(lab): tell the app's own agent to continue after a Lab build restart

* fix(lab): size the build heap from the device's memory

* feat(lab): keep earlier Lab builds and list them in Updates

* feat(lab): notify when DroidDeck comes back on a Lab build or turns one off

* feat(lab): estimate the time left and compile the installed commit ahead of the first build

* fix(lab): report a failed command as a failed build and update progress every five seconds

* feat(lab): a kept build for another version can be rebuilt

* feat(lab): record which installed commit the build caches are warm for

* fix(lab): the app's agent hands its builds to the app, so they outlive the agent's turn

* perf(lab): BuildConfig describes the installed base, so a Lab commit does not change it

* perf(lab): compile with the Kotlin daemon, since in-process Kotlin compiles always redo the whole app

* fix(lab): a build whose last task was up to date no longer counts as failed

* feat(lab): dd-lab-build --explain logs why tasks ran and Kotlin's build report

* fix(lab): keep a waiting build when another is staged or Lab is turned off, and never restart during a session

* fix(lab): keep the installed build's label and exact commit, and refuse AppLanguage changes

* fix(lab): setup verifies its downloads and waits for adb before preparing

* fix(agent): quote apostrophes in opened URLs and keep the sign-in pid
2026-11-11 12:44:39 -05:00
Kurt Himebauch 2dbc007a95 fix(ci): fall back to the kernel.org Ubuntu mirror when Canonical's are unreachable (#2469)
* fix(ci): fall back to the kernel.org Ubuntu mirror when Canonical's are unreachable

* fix(ci): fall back to the Berkeley ports mirror on arm64 runners
2026-11-11 12:10:33 -05:00
Kurt Himebauch c265b66e80 fix(agent): start sessions from their own task so repeat starts aren't swallowed (#2468)
* fix(agent): start sessions from their own task so repeat starts aren't swallowed

* fix(ci): fall back to the kernel.org Ubuntu mirror when Canonical's are unreachable

* fix(ci): fall back to the Berkeley ports mirror on arm64 runners
2026-11-11 10:59:04 -05:00
K11MCH1andKurt Himebauch f16b023f0d fix(ubisoft): R2 games get a session matching the subsystems they ask for (#2450)
uplay_r2.dll speaks the same UplayDll.proto as uplay_r1.dll, but its InitReq
names the subsystems the game uses (fields 4 to 11) and its ApiContext only
creates objects for those. It copies gameInstall and storage into their
objects without checking for them, so the gameInstall droiddeck-upc always
sent crashed Prince of Persia: The Lost Crown (6145), which asks for overlay,
product and store only: an access violation reading 0x68 in
uplay_r264.dll+0xaca2 two seconds after the session.

- When the request names subsystems, gameInstall (14) is sent only with
  subSystemInstall and storage (17) only with subSystemStorage, and an empty
  multiplayerInit (20) is added. Requests that name none keep the old session.
- streamingReq (27) is answered: the streaming type is None, other streaming
  queries are not found.
- The log records the subsystems each init asked for.

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-11 10:34:06 -05:00
Kurt Himebauch 2848484a99 feat: fuck proot and proots mama (#2300)
* feat: experimental native userland that runs the Linux side without proot

* fix(native): keep the visible name of link2symlink binaries

* fix(ci): run the native hook build through bash

* fix(native): address review findings in the hook and the ctl fallback

* fix(ctl): use the broadcast fallback only when content is missing

* fix(native): survive Android's seccomp filter in ld.so, libc and posix_spawn children

* docs(native): how to test under Android's seccomp filter

* fix(session): hide an unlistable /sys/bus/pci/devices so libpci does not abort Chromium's GPU init

* fix(native): nested syscall() redirects no longer loop with libblsession's openat2

* fix(native): controllers reach Steam and the install-script evaluator no longer blocks game moves

* fix(native): write the hook's NUL character literals as escapes

* fix(native): proot fast path turns off and greys out while running without proot

* fix(native): D-Bus logins work and Xwayland still admits root once peers read as root

* fix(native): scripts on session mounts outside the rootfs run with the rootfs shell

* fix(native): games on the SD card library start in their own folder

* fix(native): Wine drive links proot made point at their real places

* fix(native): at-calls, uid lookups and relative programs follow the session's mounts

* fix(native): close-from in spawned programs covers what is open at the spawn

* fix(native): service names resolve and the DNS fallback answers what was asked

* build(native): the hook is built with its Go support and tracked by the preload recipe

* fix(native): drive links into identity mounts stay, and relink and seccomp patch failures are logged

* fix(native): seccomp-sim's filter holds every allowed call

* fix(ctl): the broadcast fallback only stands in for a missing content command

* fix(native): pre-2.33 glibc stat calls present owners as root too

* fix(native): res_init and res_ninit call glibc, so Steam's store resolves names

* fix(ci): a preload lock older than a new output rebuilds that group, and generated headers are not hashed

* fix(native): a second seccomp patch run leaves other system calls alone

* fix(native): the terminal and bottom desktop keep proot's environment in a native session

* fix(native): any number of session mounts, and openat2 relative to a mounted folder

* fix(agent): a native command's stdin is written beside its timeout

* fix(ctl): native rejects --env without = and timeouts outside 0-600 s

* fix(native): the resolver fallback has the network's IPv6 servers, and lookups keep the fallback's validation errors

* fix(native): a spawn whose dup2 source close-from closed fails with EBADF

* fix(native): __getcwd_chk checks its buffer, and seccomp-sim -a takes only call numbers

* feat(native): guests see the session hostname from uname and gethostname

* feat(native): the terminal and bottom desktop run without proot

* fix(components): an origin APK without a newer preload output still proves the rest

* fix(native): seccomp-sim -a rejects empty fields

* fix(native): gethostbyname no longer answers failed lookups with Ubuntu and Debian addresses

* feat(native): store installers, root helpers, Comet and Xodus run without proot

* fix(native): the hook finds libraries, preloads and itself through a sandbox's mounts, and ldconfig -C makes its cache

* feat(native): Flatpak sandboxes run without proot, and apply_extra runs without a runtime

* fix(native): remove, glob and nftw take guest paths, and links in a mount are followed as the guest sees them

* fix(native): Flatpak sandboxes get the session's mounts, their libraries' RUNPATHs, and no rootfs-only settings

* fix(native): gethostbyname asks the network's DNS servers, nftw of / gives single slashes, and the library path fits mapped directories

* fix(native): a native process starts in its working directory's real place

* fix(native): the library path given to ld.so holds whole directories only

* fix(native): Wine drive links keep their guest paths, so proot finds the library after a native session

* fix(native): droiddeckctl native prepares the rootfs with the setting off

* fix(native): a SysV segment stays while any process has it attached

* fix(native): DNS lookups ask the network's own servers before public ones

* fix(native): a program's own seccomp traps reach its own SIGSYS handler

* feat(native): run native sessions under a device's own app seccomp filter for testing

* fix(native): SysV attaches and collection take a lock, a failed mark fails the attach, and collection closes its directory

* fix(native): shmat fails when it cannot take the segment lock

* fix(native): the SysV segment lock is retried when a signal interrupts it

* fix(native): process tools see the session's processes as root's

* fix(native): native processes are named after their program, not ld.so

* fix(native): a session's helpers keep the mode the session started in

* fix(native): a keyed SysV segment stays until IPC_RMID

* fix(native): a rootfs link to an absolute guest path is followed in the guest, so Wine finds its z: drive

* fix(native): a sandbox whose loader can't be patched runs under proot

* fix(native): creating a private SysV segment also collects stale ones

* fix(native): a session stopped during startup forgets its mode

* fix(xbox): a native backend is authorized by its process ancestry

* fix(native): Wine's drive links are followed in the guest from any prefix

* fix(native): only the startup that owns the running session publishes its mode

* fix(native): a SysV segment stays until IPC_RMID even after its maker ends

* fix(native): a sandbox mount nested in another mount gets its own place

* fix(native): a sandbox whose mount places can't be made runs under proot
2026-11-11 09:13:17 -05:00
K11MCH1 b1a410ccd2 fix(ubisoft): answer Orbit, login and process-only check-ins (#2460) 2026-11-11 07:49:18 -05:00
Kurt Himebauch 45ef6b7d1a chore(ci): trust KeegantheVeganat0r for automatic test builds (#2434) 2026-11-11 07:44:59 -05:00
Kurt Himebauch 2aeff3bd9b chore: CodeRabbit reviews draft PRs (#2447) 2026-11-10 20:57:42 -05:00
Kurt Himebauch 0c79a742c4 fix(game-env): keep the x64 Visual C++ runtime in ARM64 prefixes (#2442) 2026-11-10 20:30:11 -05:00
MaxsTechReview e4b2526d2c chore(ci): trust contributor for test builds (#2443) 2026-11-10 18:39:13 -05:00
Kurt Himebauch dd9363e5f2 fix: ship the Ubisoft launcher service as an add-on pack, scan only the standard APK on main (#2436)
* fix: ship the Ubisoft launcher service as an add-on pack, not inside the APK

* fix: treat the Ubisoft service as a packed tree, stage it when its pack lands

* fix: serialize staging of the Ubisoft service
2026-11-10 16:33:41 -05:00
Kurt Himebauch 055e2ec78f Fix Electron Node mode sandbox injection (#2418)
* Fix Electron Node mode sandbox injection

* fix(preload): treat any nonempty ELECTRON_RUN_AS_NODE as Electron Node mode
2026-11-10 16:10:42 -05:00
Kurt Himebauch 3c96df4ab1 feat(ubisoft): Ubisoft Connect store with native sign-in, library, downloads and launch (#2322)
* feat(ubisoft): sign in to Ubisoft Connect and list the owned library

* feat(ubisoft): download games natively through Demux and Ubisoft's CDN

* fix(ubisoft): show the owned games on the store page

* fix(ctl): reach the agent bridge by broadcast when the shell has no content command

* feat(ubisoft): run Ubisoft games in one prefix with Ubisoft Connect installed and the game registered

* feat(ubisoft): launch games through a native stand-in for Ubisoft Connect's local service

* feat(ubisoft): document the launcher pipes, log why owned games have no download, drop the installer after extraction

* feat(ubisoft): Steam-owned Ubisoft games install through Steam, and the launch session carries the game's application id

* feat(ubisoft): answer Denuvo activations through Ubisoft's activation service and log unanswered pipe traffic

* feat(ubisoft): report installed chunks to the game and skip add-ons the account does not own

* fix(ubisoft): the overlay stays off, Ubisoft's install steps pick Windows components, and shared-prefix games keep their own settings

* fix(ubisoft): write the manifest's registry values, and pick the game's exe over Ubisoft's installer stubs

* fix(ubisoft): stream download slices, guard the launch hook, and keep per-game components in the shared prefix

* fix(ubisoft): direct launches in the shared prefix keep their own game id

* ci(ubisoft): build the launcher service after the prepared components are verified

* fix(ubisoft): verify reused files, drop syncs from a signed-out account, and clear activation requests before launch

* fix(ubisoft): fetch again a reused file whose slices cannot be checked
2026-11-10 15:08:37 -05:00
Kurt Himebauch d8ed02f2cf feat: EA store with sign-in, library, native downloads, updates and launch without the EA app (#2259)
* docs: research and plan for EA and Ubisoft stores

* feat(ea): EA store with sign-in, library, native downloads, updates and launch without the EA app

* perf(ea): fetch large archive records as parallel ranges

* fix(ea): register game display names

* fix(ea): license legacy EA Core games and harden the LSX endpoint

* fix(ea): run legacy Origin SDK games with a stand-in Origin process

* fix(ea): trust only the prepared game on LSX and stop stale library syncs

* fix(ea): close LSX sessions on stop and drop clients that never hand-shake

* fix(ea): require every hashed field before licensing or caching a probe

* fix(ea): trust one LSX session per launch

* fix(ea): serialize the library cache write with sign-out and rerun a skipped sync

* fix(ea): hand off library sync requests under one lock

* fix(ea): clear the sign-in before invalidating the library

* fix(ea): serialize sign-out with token refresh and with the library cache

* fix(ea): LSX trusts only verified peers, new launch closes old sessions, exit stops its own game

* fix(ea): LSX hides profile and presence from unverified peers

* fix(ea): LSX handshake has a fixed deadline and untrusted sessions yield their slot

* fix(ea): LSX never registers a client after its listener was stopped

* fix(ea): LSX evicts each untrusted session at most once

* fix(ea): LSX admission and eviction share one lock and keep the cap

* fix(ea): LSX trust promotion excludes eviction

* fix(ea): LSX launch generation guards restarts and drops results after shutdown

* fix(ea): LSX publishes launch state under the admission lock and tags accepts by generation

* fix(ea): LSX restarts rebind its listener and promotion checks the launch generation

* fix(ea): record why EA refuses a game licence in the store log

* chore(ea): log owned offers and the full licence refusal

* chore(ea): log the account's entitlements when no game licence is granted

* chore(ea): log legacy entitlements when no game licence is granted

* chore(ea): log only the refused game's own entitlements

* fix(ea): skip trial launchers flagged 1 and license games whose LSX peer Android cannot name
2026-11-10 14:56:29 -05:00
MaxsTechReview 9bf638a3c4 fix(input): system Back only turns into a right-click with an external mouse (#2323)
* fix(input): injected Back is a right-click only while an external mouse is attached

* input: order imports

* fix(input): reject built-in devices for injected Back

* fix(input): log matched mouse for injected Back

* fix(input): ignore mice that name themselves virtual for injected Back
2026-11-10 11:55:38 -05:00
Kurt Himebauch 40242fa082 ci: scan signed main and release APKs on VirusTotal (#2408)
* ci: scan signed main and release APKs on VirusTotal

* ci: upload to VirusTotal only for unknown hashes and escape annotations
2026-11-10 11:15:07 -05:00
Kurt Himebauch 98ab71a814 docs: point README downloads at 0.7.1 (#2401) 2026-11-10 07:38:07 -05:00
Kurt Himebauch 2982e474ab ci: run Python and native regression tests on the workstation runner when idle 2026-11-07 20:23:37 -05:00
210 changed files with 27534 additions and 204 deletions

No files matched your search

+1 -1
View File
@@ -18,7 +18,7 @@ reviews:
enabled: true
auto_incremental_review: true
auto_pause_after_reviewed_commits: 0
drafts: false
drafts: true
pre_merge_checks:
docstrings:
mode: "off"
+3
View File
@@ -10,3 +10,6 @@ tools/mangoapp/mangoapp text eol=lf
app/src/main/assets/desktop-removal/*.json text eol=lf
app/src/main/assets/desktop-removal/*.txt text eol=lf
*.pdf binary
app/src/main/resources/ea/graphql/*.gql -text
app/src/main/assets/agent/* text eol=lf
+2
View File
@@ -1,5 +1,7 @@
ASEbrahim
FX192
K11MCH1
KeegantheVeganat0r
kingokksa
ovurrsl
KeegantheVeganat0r
+24
View File
@@ -195,6 +195,7 @@ jobs:
!app/src/main/assets/linuxfs/i386/libfaultreport.so
!app/src/main/assets/linuxfs/libblaudit.so
!app/src/main/assets/linuxfs/libblfastpath.so
!app/src/main/assets/linuxfs/libddnatv-hook.so
!app/src/main/assets/linuxfs/libblsession.so
!app/src/main/assets/linuxfs/libfakeinput.so
!app/src/main/assets/linuxfs/libssbs.so
@@ -555,6 +556,12 @@ jobs:
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
- name: Ubisoft launcher service (x86_64-pc-windows-gnu)
run: |
set -euo pipefail
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
bash tools/ubisoft-launcher/build.sh
- uses: actions/download-artifact@v4
with:
name: xbox-arm64
@@ -791,6 +798,9 @@ jobs:
set -o pipefail
cd app/src/main/rust/stores
cargo test --locked 2>&1 | tail -60
- name: Ubisoft launcher service host unit tests
timeout-minutes: 10
run: cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml
python-tests:
name: Python and native regression tests
@@ -823,6 +833,9 @@ jobs:
env:
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
- uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Python test dependencies
timeout-minutes: 7
run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers
@@ -883,6 +896,17 @@ jobs:
variants: ${{ needs.build.outputs.variants }}
secrets: inherit
scan:
needs: sign
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
permissions:
contents: read
uses: ./.github/workflows/scan.yml
with:
artifact: droiddeck-signed
variant: standard
secrets: inherit
packs:
needs: [build, checks]
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
+1 -1
View File
@@ -55,7 +55,7 @@ jobs:
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
}
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
for name in proot directaudio tracking xbox comet butler powervr; do
for name in proot directaudio tracking xbox comet butler powervr ubisoft; do
file="packs/$name.tar.zst"
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
sha=$(sha256sum "$file" | cut -d' ' -f1)
+9
View File
@@ -63,6 +63,15 @@ jobs:
artifact: droiddeck-release
secrets: inherit
scan:
needs: sign
permissions:
contents: read
uses: ./.github/workflows/scan.yml
with:
artifact: droiddeck-release
secrets: inherit
packs:
needs: find
permissions:
+49
View File
@@ -0,0 +1,49 @@
name: Scan APKs
on:
workflow_call:
inputs:
artifact:
description: Prefix of the signed artifacts to scan, as passed to sign.yml
type: string
required: true
variant:
description: Variant to scan, as listed in tools/release/variants.txt; every variant when omitted
type: string
default: '*'
fail_on_detection:
type: boolean
default: false
permissions:
contents: read
jobs:
virustotal:
name: VirusTotal
runs-on: ubuntu-24.04
timeout-minutes: 90
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
sparse-checkout: tools/release
- uses: actions/download-artifact@v4
with:
pattern: ${{ inputs.artifact }}-${{ inputs.variant }}
merge-multiple: true
path: scan
- name: Scan
continue-on-error: ${{ !inputs.fail_on_detection }}
env:
VT_API_KEY: ${{ secrets.VIRUSTOTAL_API_KEY }}
FAIL_ON_DETECTION: ${{ inputs.fail_on_detection && '1' || '0' }}
run: |
set -euo pipefail
if [ -z "$VT_API_KEY" ]; then
echo "::warning title=VirusTotal::no VIRUSTOTAL_API_KEY secret; skipping the scan"
exit 0
fi
bash tools/release/virustotal-scan.sh scan/*.apk
+3 -2
View File
@@ -10,7 +10,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
<p align="center"><b>100% open source. No ads. No telemetry. No proprietary components. No source withheld.</b></p>
<p align="center">
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.0/DroidDeck-0.7.0.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.0%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.0"></a>
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.1%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.1"></a>
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
</p>
@@ -38,7 +38,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.0/DroidDeck-0.7.0.apk), install the Linux runtime, press **Play** and sign in to Steam.
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk), install the Linux runtime, press **Play** and sign in to Steam.
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
@@ -93,6 +93,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them.
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
- 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.
- 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.
- 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.
+2 -2
View File
@@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr'].collectEntries { name ->
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
@@ -205,7 +205,7 @@ android {
}
androidResources {
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>directaudio:<dir>hybris'
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>directaudio:<dir>hybris'
}
packagingOptions {
+2
View File
@@ -258,6 +258,7 @@
android:exported="true"
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="${applicationId}.agent"
android:permission="android.permission.DUMP"
android:theme="@style/SessionTheme" />
@@ -302,6 +303,7 @@
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density"
android:theme="@style/SessionTheme" />
<service android:name=".agent.AgentHostService" android:exported="false" />
<service
android:name=".session.SessionService"
android:exported="false"
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Opens a URL in Android's browser on the display the agent is being used on ($DD_BROWSER_DISPLAY).
# DroidDeck opens what is left in $DD_AGENT_INBOX/open-url; adb is the fallback when it cannot.
url=$1
[ -n "$url" ] || exit 1
inbox=${DD_AGENT_INBOX:-/data/user/0/com.droiddeck.launcher/files/agent}
rm -f "$inbox/open-url.failed" 2>/dev/null
if [ -d "$inbox" ] && printf '%s\n' "$url" > "$inbox/open-url.part" && mv -f "$inbox/open-url.part" "$inbox/open-url"; then
i=0
while [ $i -lt 30 ] && [ -e "$inbox/open-url" ]; do
sleep 0.2
i=$((i + 1))
done
if [ -e "$inbox/open-url" ]; then
rm -f "$inbox/open-url"
elif [ -e "$inbox/open-url.failed" ]; then
rm -f "$inbox/open-url.failed"
else
sleep 0.3
[ -e "$inbox/open-url.failed" ] && rm -f "$inbox/open-url.failed" || exit 0
fi
fi
serial=${ADB_SERIAL:-127.0.0.1:5555}
adb connect "$serial" >/dev/null 2>&1
quoted=$(printf "%s" "$url" | sed "s/'/'\\\\''/g")
adb -s "$serial" shell "am start --display ${DD_BROWSER_DISPLAY:-0} -a android.intent.action.VIEW -d '$quoted'" >/dev/null 2>&1 ||
echo "Open this on any device: $url" >&2
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# GitHub sign-in through Android's browser, with the one-time code typed in for the person.
serial=${ADB_SERIAL:-127.0.0.1:5555}
display=${DD_BROWSER_DISPLAY:-0}
adb connect "$serial" >/dev/null 2>&1
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
# bash drops GH and GH_PID once gh exits, which can be before the loop reads its last line.
ghpid=$GH_PID
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
typed=
while IFS= read -r line <&"$ghout"; do
printf '%s\n' "$line"
code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1)
if [ -n "$code" ] && [ -z "$typed" ]; then
typed=1
echo >&"$ghin"
adb -s "$serial" shell "am start --display $display -a android.intent.action.VIEW -d https://github.com/login/device" >/dev/null 2>&1
# Chrome drops characters from `input text` and from fast key events on this page.
keys=
for ((i = 0; i < ${#code}; i++)); do
c=${code:i:1}
[ "$c" = - ] || keys+="input -d $display keyevent KEYCODE_$c; sleep 0.4; "
done
(sleep 7; adb -s "$serial" shell "$keys" >/dev/null 2>&1) &
fi
done
wait "$ghpid"
+9 -1
View File
@@ -2322,7 +2322,15 @@ __attribute__((visibility("hidden"))) static bool is_deck_sysfs_path(const char
if (!path) return false;
if (!strncmp(path, "/sys/devices/droiddeck", 22) || !strncmp(path, "/sys/class/hidraw", 17)) return true;
const char *listing = deck_listing_dir();
return listing && !strncmp(path, listing, strlen(listing));
if (!listing) return false;
if (!strncmp(path, listing, strlen(listing))) return true;
// Without proot, a descriptor's /proc/self/fd link names the stand-in where it really is (the
// listing's parent holds devices/ and class-hidraw/), not /sys
const char *slash = strrchr(listing, '/');
if (!slash || slash == listing) return false;
size_t root = static_cast<size_t>(slash - listing);
return !strncmp(path, listing, root) && path[root] == '/' &&
(!strncmp(path + root, "/devices", 8) || !strncmp(path + root, "/class-hidraw", 13));
}
__attribute__((visibility("hidden"))) static bool is_deck_sysfs_fd(int fd) {
@@ -7,8 +7,11 @@ import com.droiddeck.launcher.session.EnhancedSessionLogShare
import com.droiddeck.launcher.session.GpuClockPin
class App : Application() {
override fun attachBaseContext(base: android.content.Context) =
override fun attachBaseContext(base: android.content.Context) {
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(base))
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName() else packageName
com.droiddeck.launcher.lab.LabOverlay.load(this, process == packageName)
}
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
@@ -39,6 +42,9 @@ class App : Application() {
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
CrashHandler.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this)
if (com.droiddeck.launcher.agent.AgentHost.available) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
com.droiddeck.launcher.lab.LabNotice.started(this)
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
@@ -61,6 +67,9 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
com.droiddeck.launcher.sync.Syncthing.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ubisoft.UbisoftBackend)
com.droiddeck.launcher.stores.ea.EaBackend.app = this
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
}
private fun prefetchAddonPacks() {
@@ -74,6 +83,8 @@ class App : Application() {
if (com.droiddeck.launcher.stores.gog.GogComet.enabled(app)) com.droiddeck.launcher.core.AddonPack.COMET.ensure(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.XBOX) != null)
com.droiddeck.launcher.core.AddonPack.XBOX.ensure(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.UBISOFT) != null)
com.droiddeck.launcher.session.SessionFiles.ensureUbisoftService(app)
com.droiddeck.launcher.handtracking.HandTracking.load(app)
}.onFailure { android.util.Log.w("App", "add-on pack prefetch failed", it) }
}, "addon-packs").start()
@@ -185,6 +185,7 @@ class FrontEndActivity : ComponentActivity() {
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(false)
private var cursorComposite by mutableStateOf(false)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
@@ -1104,6 +1105,8 @@ class FrontEndActivity : ComponentActivity() {
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
if (savedInstanceState == null) readIntegrationIntent(intent)
readGameIntent(intent)
// A Lab build is usually the agent's work, so the app comes back where the agent is.
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentHost.available) navRequest = "agent"
gameSyncFolder = GameFileSync.folder(this)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
@@ -2557,7 +2560,7 @@ class FrontEndActivity : ComponentActivity() {
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
@@ -2575,6 +2578,7 @@ class FrontEndActivity : ComponentActivity() {
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
@@ -2797,6 +2801,7 @@ class FrontEndActivity : ComponentActivity() {
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
@@ -3076,6 +3081,7 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, it, android.widget.Toast.LENGTH_LONG).show()
}
refresh()
com.droiddeck.launcher.agent.AgentHost.refresh(this)
if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
}
}, "runtime-operation").start()
@@ -391,8 +391,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
)
private val mouseBackInput = com.droiddeck.launcher.input.MouseBackInput(
sendRight = { down -> heldButtons.set(32, PointerGestures.BTN_RIGHT, down) },
mouseAttached = ::mouseAttached,
mouseAttached = ::externalMouseAttached,
)
private var lastExternalMouse: InputDevice? = null
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
private var drawerDirectionDownTime = 0L
private var drawerDirectionDeviceId = -1
@@ -2683,7 +2684,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
val mouseToGuest = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen &&
!SessionState.suspended && !(::loading.isInitialized && (loading.visible || loading.ended))
if (mouseBackInput.onKeyEvent(event, mouseToGuest)) return true
if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0 &&
com.droiddeck.launcher.input.MouseBackInput.isInjectedBack(event)) lastExternalMouse = null
val mouseBackHandled = mouseBackInput.onKeyEvent(event, mouseToGuest)
if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0 &&
com.droiddeck.launcher.input.MouseBackInput.isInjectedBack(event) && mouseToGuest) {
val device = lastExternalMouse
if (mouseBackHandled && device != null) {
Log.i(TAG, String.format(java.util.Locale.ROOT,
"injected Back right-click mouse=\"%s\" (%04x:%04x, id %d, sources 0x%x, external=%s, virtual=%s)",
device.name, device.vendorId, device.productId, device.id, device.sources,
Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || device.isExternal, device.isVirtual))
} else if (!mouseBackHandled) {
Log.i(TAG, "injected Back no external mouse found")
}
}
if (mouseBackHandled) return true
val backToQam = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
@@ -4163,6 +4179,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
isHardwareMouse(d) && d?.supportsSource(InputDevice.SOURCE_TOUCHPAD) != true
}
private fun externalMouseAttached(): Boolean {
lastExternalMouse = InputDevice.getDeviceIds().map { InputDevice.getDevice(it) }
.firstOrNull { device -> device != null && com.droiddeck.launcher.input.MouseBackInput.isExternalMouse(device) }
return lastExternalMouse != null
}
private fun relativeMouseAttached(): Boolean = !isInMultiWindowMode && !glassesOutputActive && InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
isHardwareMouse(d) && d?.supportsSource(InputDevice.SOURCE_TOUCHPAD) != true
@@ -0,0 +1,44 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.core.WirelessAdbFix
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/**
* Loopback adb for the agent, so droiddeckctl in the Linux userland reaches the app. It reuses
* the Wireless debugging pairing DroidDeck already made (for the phantom process fix): the paired
* key goes to the guest as an adb vendor key, and the serial is the paired TLS connect port.
* Without a pairing it falls back to adbd on 127.0.0.1:5555, which some devices and `adb tcpip`
* leave listening.
*/
object AgentAdb {
data class Link(val serial: String, val vendorKeys: String, val paired: Boolean)
private const val LEGACY = "127.0.0.1:5555"
private const val VENDOR_KEY = "/root/.android/droiddeck-paired.adbkey"
/** The display the browser opens on for sign-ins: the one the agent is being used on. */
@Volatile var browserDisplay = 0
/** Blocks while it looks up the connect port when none is saved; call it off the main thread. */
fun prepare(app: Context): Link {
val key = File(app.noBackupFilesDir, "wireless-adb-key.pem")
val address = WirelessAdbFix.liveConnectAddress(app) ?: WirelessAdbFix.savedConnectionAddress(app)
if (address == null || !key.isFile) return Link(LEGACY, VENDOR_KEY, false)
val guestKey = File(LinuxRuntime.rootDir(app), VENDOR_KEY.removePrefix("/"))
runCatching {
if (!guestKey.isFile || !guestKey.readBytes().contentEquals(key.readBytes())) {
guestKey.parentFile?.mkdirs()
guestKey.writeBytes(key.readBytes())
guestKey.setReadable(false, false)
guestKey.setReadable(true, true)
}
}
val host = address.substringBeforeLast(':')
val port = address.substringAfterLast(':').toIntOrNull()
?: WirelessAdbFix.findConnectPort(app, host.trim('[', ']'))
?: return Link(LEGACY, VENDOR_KEY, false)
return Link("$host:$port", VENDOR_KEY, true)
}
}
@@ -0,0 +1,67 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import androidx.compose.runtime.mutableStateListOf
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/**
* Files the user attaches to a message, copied into the Linux userland so the agent's own tools
* can read them (Claude Code's Read shows images and PDFs to the model).
*/
object AgentAttachments {
/** Guest paths waiting to go with the next message. */
val pending = mutableStateListOf<String>()
private const val NEW = "new"
private const val GUEST_DIR = "/root/.cache/droiddeck/attachments"
private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp")
fun hostDir(context: Context) = File(LinuxRuntime.rootDir(context.applicationContext), GUEST_DIR.removePrefix("/"))
fun host(context: Context, guestPath: String) = File(LinuxRuntime.rootDir(context.applicationContext), guestPath.removePrefix("/"))
fun isImage(path: String) = path.substringAfterLast('.', "").lowercase() in IMAGE
/** Copies [uris] for [chat] (or a new conversation) on the calling thread; returns their guest paths. */
fun copy(context: Context, chat: String?, uris: List<Uri>): List<String> {
val app = context.applicationContext
val folder = chat ?: NEW
val dir = File(hostDir(app), folder).apply { mkdirs() }
return uris.mapNotNull { uri ->
runCatching {
val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" }
var target = File(dir, name)
var n = 1
while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } }
"$GUEST_DIR/$folder/${target.name}"
}.getOrNull()
}
}
/** Moves files attached before [chat] existed into its folder, so deleting the chat removes them; returns their new guest paths. */
fun adopt(context: Context, chat: String, files: List<String>): List<String> = files.map { path ->
if (!path.startsWith("$GUEST_DIR/$NEW/")) return@map path
val dir = File(hostDir(context), chat).apply { mkdirs() }
val moved = File(dir, path.substringAfterLast('/'))
if (host(context, path).renameTo(moved)) "$GUEST_DIR/$chat/${moved.name}" else path
}
/** Deletes copies that will not be sent. */
fun discard(context: Context, files: List<String>) = files.forEach { host(context, it).delete() }
/** The message the CLI gets: the user's text, then where the attached files are. */
fun prompt(text: String, files: List<String>): String {
if (files.isEmpty()) return text
val list = files.joinToString("\n") { "- $it" }
return "$text\n\nAttached files (read them with your tools):\n$list".trim()
}
private fun displayName(context: Context, uri: Uri): String =
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
} ?: uri.lastPathSegment?.substringAfterLast('/') ?: "file"
}
@@ -85,6 +85,10 @@ class AgentBridgeProvider : ContentProvider() {
AgentAccess.requireCommands(context)
guest(context, JSONObject(request.toString()).put("kind", "exec"), timeoutMs(request, 30.0, 10_000))
}
"native" -> {
AgentAccess.requireCommands(context)
AgentNative.run(context, request, timeoutMs(request, 30.0, 0))
}
"cdp" -> {
AgentAccess.requireCommands(context)
guest(context, JSONObject(request.toString()).put("kind", "cdp"), timeoutMs(request, 15.0, 5_000))
@@ -284,6 +288,8 @@ class AgentBridgeProvider : ContentProvider() {
return JSONObject()
.put("schema", SCHEMA)
.put("build", BuildConfig.BUILD_LABEL)
.put("apkCommit", com.droiddeck.launcher.lab.LabOverlay.apkCommit)
.put("lab", com.droiddeck.launcher.lab.LabOverlay.active?.label ?: JSONObject.NULL)
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
.put("runtime", JSONObject()
.put("installed", LinuxRuntime.isInstalled(context))
@@ -4,6 +4,7 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.annotation.VisibleForTesting
import java.io.File
/**
@@ -17,9 +18,17 @@ class AgentCallReceiver : BroadcastReceiver() {
val id = intent.getStringExtra("id")?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{1,64}")) } ?: return
val arg = intent.getStringExtra("arg")
val request = intent.getStringExtra(AgentBridgeProvider.EXTRA_REQUEST)
val pending = goAsync()
Thread({
val json = try {
val app = context.applicationContext
// The caller waits for the answer file, not for the broadcast. Holding the broadcast open
// with goAsync() for a call that outlasts the broadcast timeout (10 s in the foreground)
// makes Android report the app as not responding.
Thread({ answer(app, method, id, call(app, method, arg, request)) }, "agent-call-$id").start()
}
companion object {
@VisibleForTesting
internal var call: (Context, String, String?, String?) -> String = { context, method, arg, request ->
try {
val extras = Bundle().apply { putString(AgentBridgeProvider.EXTRA_REQUEST, request) }
context.contentResolver.call("${context.packageName}.agent", method, arg, extras)
?.getString(AgentBridgeProvider.RESULT_JSON) ?: """{"ok":false,"error":{"code":"NO_RESPONSE","message":"no response"}}"""
@@ -27,15 +36,16 @@ class AgentCallReceiver : BroadcastReceiver() {
org.json.JSONObject().put("ok", false)
.put("error", org.json.JSONObject().put("code", "COMMAND_FAILED").put("message", e.message ?: e.javaClass.simpleName)).toString()
}
}
private fun answer(context: Context, method: String, id: String, json: String) {
try {
val dir = File(context.getExternalFilesDir(null), "agent-calls").apply { mkdirs() }
File(dir, "$id.json.part").writeText(json)
File(dir, "$id.json.part").renameTo(File(dir, "$id.json"))
} catch (e: Exception) {
android.util.Log.w("AgentCallReceiver", "could not write the answer to $method: ${e.message}")
} finally {
pending.finish()
}
}, "agent-call-$id").start()
}
}
}
@@ -0,0 +1,138 @@
package com.droiddeck.launcher.agent
import android.content.Context
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.agent.AgentHost.Entry
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* Conversations kept on the device, one JSON Lines file each in `files/agent/chats`: a header
* line with the harness, a line with the CLI's conversation id once it has one, then the entries.
*/
object AgentChats {
data class Chat(val id: String, val harness: String, val title: String, val updated: Long)
class Loaded(val harness: String?, val conversation: String?, val entries: List<Entry>)
private const val MAX_OUTPUT = 24_000
fun dir(context: Context) = File(context.filesDir, "agent/chats")
fun file(context: Context, id: String) = File(dir(context), "$id.jsonl")
fun newId(context: Context): String {
var stamp = System.currentTimeMillis()
while (file(context, stamp.toString()).exists()) stamp++
return stamp.toString()
}
/** Newest first; chats with nothing asked yet are left out. */
fun list(context: Context): List<Chat> = dir(context).listFiles { f -> f.name.endsWith(".jsonl") }.orEmpty()
.mapNotNull { f ->
val loaded = read(f)
val title = loaded.entries.firstNotNullOfOrNull { (it as? Entry.Asked)?.text } ?: return@mapNotNull null
Chat(f.name.removeSuffix(".jsonl"), loaded.harness ?: ClaudeCode.id, title.lineSequence().first().take(120), f.lastModified())
}
.sortedByDescending { it.updated }
fun delete(context: Context, id: String) {
file(context, id).delete()
File(AgentAttachments.hostDir(context), id).deleteRecursively()
}
fun start(file: File, harness: String) {
file.parentFile?.mkdirs()
file.writeText(JSONObject().put("harness", harness).toString() + "\n")
}
fun appendConversation(file: File, conversation: String) =
runCatching { file.appendText(JSONObject().put("conversation", conversation).toString() + "\n") }
fun append(file: File, entry: Entry) = runCatching { file.appendText(encode(entry) + "\n") }
/** The transcript before chats were kept, moved into the first chat. */
fun migrate(context: Context, harness: String, conversation: String?): String? {
val old = File(context.filesDir, "agent/transcript.jsonl")
if (!old.isFile) return null
val id = newId(context)
val target = file(context, id)
start(target, harness)
conversation?.let { appendConversation(target, it) }
target.appendText(old.readText())
old.delete()
return id
}
@VisibleForTesting
internal fun encode(entry: Entry): String = when (entry) {
is Entry.Asked -> JSONObject().put("asked", entry.text).apply { if (entry.files.isNotEmpty()) put("files", JSONArray(entry.files)) }
is Entry.Said -> JSONObject().put("said", entry.text)
is Entry.Thought -> JSONObject().put("thought", entry.text)
is Entry.Result -> JSONObject().put("result", entry.id).put("output", entry.output).put("failed", entry.failed)
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input)
.apply { entry.output?.let { put("output", it).put("failed", entry.failed) } }
is Entry.Finished -> JSONObject().put("finished", true).put("error", entry.error ?: JSONObject.NULL).put("stopped", entry.stopped).apply {
entry.usage?.let { put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens) }
}
}.toString()
@VisibleForTesting
internal fun read(file: File): Loaded {
var harness: String? = null
var conversation: String? = null
val entries = mutableListOf<Entry>()
runCatching {
file.forEachLine { line ->
val o = runCatching { JSONObject(line) }.getOrNull() ?: return@forEachLine
when {
o.has("harness") -> harness = o.getString("harness")
o.has("conversation") -> conversation = o.getString("conversation")
else -> decode(o)?.let { merge(entries, it) }
}
}
}
return Loaded(harness, conversation, entries)
}
private fun decode(o: JSONObject): Entry? = when {
o.has("asked") -> Entry.Asked(o.getString("asked"), o.optJSONArray("files")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty())
o.has("said") -> Entry.Said(o.getString("said"))
o.has("thought") -> Entry.Thought(o.getString("thought"))
o.has("used") -> Entry.Used(o.optString("id"), o.getString("used"), o.optString("detail"), o.optString("input"),
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"))
o.has("result") -> Entry.Result(o.getString("result"), o.optString("output"), o.optBoolean("failed"))
o.has("finished") -> Entry.Finished(
if (o.isNull("error")) null else o.optString("error"), o.optBoolean("stopped"),
if (o.has("ms")) AgentHost.Usage(o.optLong("ms"), o.optDouble("cost", 0.0), o.optLong("in"), o.optLong("out")) else null,
)
else -> null
}
/**
* A tool's result is shown on the call it answers, and a call seen again (an updated todo list)
* replaces it. Only the current turn is searched: Codex numbers its items again in each process.
*/
fun merge(entries: MutableList<Entry>, entry: Entry): Boolean {
val turn = entries.indexOfLast { it is Entry.Asked }
if (entry is Entry.Used && entry.id.isNotEmpty()) {
val same = entries.indexOfLast { it is Entry.Used && it.id == entry.id }
if (same > turn) {
entries[same] = entry
return true
}
}
if (entry !is Entry.Result) {
entries += entry
return true
}
val index = entries.indexOfLast { it is Entry.Used && it.id == entry.id && entry.id.isNotEmpty() }
if (index <= turn) return false
entries[index] = (entries[index] as Entry.Used).copy(output = clip(entry.output), failed = entry.failed)
return true
}
/** Long outputs keep their end, where errors and summaries usually are. */
fun clip(output: String) = if (output.length <= MAX_OUTPUT) output else "…\n" + output.takeLast(MAX_OUTPUT)
}
@@ -0,0 +1,306 @@
package com.droiddeck.launcher.agent
import androidx.annotation.VisibleForTesting
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/** One coding agent CLI in the Linux userland, run one process per turn. */
interface AgentHarness {
val id: String
val name: String
/** Absolute guest path of the CLI. */
val binary: String
/** Guest paths of everything the CLI needs installed, [binary] included. */
val files: List<String> get() = listOf(binary)
/** A guest shell script that installs the CLI. */
val install: String
/** A guest command whose exit status is 0 when the CLI is signed in. */
val signedIn: List<String>
/** A guest command that signs in through $BROWSER. */
val signIn: List<String>
/** Whether [Options.plan] means anything to this CLI. */
val plans: Boolean
/** 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>
/** The guest command for one turn; [conversation] is null for the first one. */
fun turn(message: String, conversation: String?, options: Options): List<String>
/** One line of the CLI's output, or null when it carries nothing to show. */
fun parse(line: String): AgentEvent?
/** Sets the CLI's own defaults in the userland before it runs; [rootfs] is the userland's root. */
fun prepare(rootfs: File) {}
data class Model(val id: String, val label: String)
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null)
companion object {
val all: List<AgentHarness> = listOf(ClaudeCode, Codex)
fun byId(id: String?): AgentHarness = all.firstOrNull { it.id == id } ?: ClaudeCode
}
}
/** What one line of output carries: whole entries, or text still being written. */
data class AgentEvent(
val conversation: String? = null,
val entries: List<AgentHost.Entry> = emptyList(),
val text: String? = null,
val thinking: String? = null,
/** Tokens the conversation's context holds after this step. */
val context: Long? = null,
val usage: AgentHost.Usage? = null,
)
/** Claude Code: `claude -p` with stream-json output, resumed by session id. */
object ClaudeCode : AgentHarness {
override val id = "claude"
override val name = "Claude Code"
override val binary = "/root/.local/bin/claude"
override val install = "curl -fsSL https://claude.ai/install.sh | bash"
override val signedIn = listOf("sh", "-c", "$binary auth status | grep -q '\"loggedIn\": true'")
override val signIn = listOf(binary, "auth", "login", "--claudeai")
override val plans = true
/**
* Commits and pull requests the agent makes carry no Claude Code credit or co-author line by
* default. Only keys the user has not set are written, so their own choice stays.
*/
override fun prepare(rootfs: File) {
val file = File(rootfs, "root/.claude/settings.json")
val settings = if (file.exists()) runCatching { JSONObject(file.readText()) }.getOrNull() ?: return else JSONObject()
var changed = false
if (!settings.has("includeCoAuthoredBy")) {
settings.put("includeCoAuthoredBy", false)
changed = true
}
if (!settings.has("attribution")) {
settings.put("attribution", JSONObject().put("commit", "").put("pr", ""))
changed = true
}
if (changed) runCatching {
file.parentFile?.mkdirs()
file.writeText(settings.toString(2) + "\n")
}
}
override fun models(rootfs: File) = listOf(
AgentHarness.Model("opus", "Opus"), AgentHarness.Model("sonnet", "Sonnet"), AgentHarness.Model("haiku", "Haiku"),
)
// DroidDeck runs the agent unattended on the user's own device; permission prompts have no one to answer them.
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
addAll(listOf(binary, "-p", message, "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions"))
options.model?.let { addAll(listOf("--model", it)) }
options.brief?.let { addAll(listOf("--append-system-prompt", it)) }
if (conversation != null) addAll(listOf("--resume", conversation))
}
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
return when (o.optString("type")) {
"stream_event" -> {
val delta = o.optJSONObject("event")?.takeIf { it.optString("type") == "content_block_delta" }?.optJSONObject("delta") ?: return null
when (delta.optString("type")) {
"text_delta" -> AgentEvent(conversation, text = delta.optString("text"))
"thinking_delta" -> AgentEvent(conversation, thinking = delta.optString("thinking"))
else -> null
}
}
"assistant" -> {
val message = o.optJSONObject("message")
val content = message?.optJSONArray("content") ?: JSONArray()
val entries = (0 until content.length()).mapNotNull { i ->
val block = content.optJSONObject(i) ?: return@mapNotNull null
when (block.optString("type")) {
"text" -> block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
"thinking" -> block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
"tool_use" -> {
val input = block.optJSONObject("input")
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input))
}
else -> null
}
}
val usage = message?.optJSONObject("usage")
val context = usage?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") + it.optLong("output_tokens") }
AgentEvent(conversation, entries, context = context?.takeIf { it > 0 })
}
"user" -> {
val content = o.optJSONObject("message")?.optJSONArray("content") ?: return conversation?.let { AgentEvent(it) }
val results = (0 until content.length()).mapNotNull { i ->
val block = content.optJSONObject(i)?.takeIf { it.optString("type") == "tool_result" } ?: return@mapNotNull null
AgentHost.Entry.Result(block.optString("tool_use_id"), resultText(block.opt("content")), block.optBoolean("is_error"))
}
AgentEvent(conversation, results)
}
// A resumed session first answers background tasks the last run left behind; that result is not the turn's.
"result" -> if (o.optJSONObject("origin")?.optString("kind") == "task-notification") conversation?.let { AgentEvent(it) } else AgentEvent(
conversation,
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
usage = AgentHost.Usage(
o.optLong("duration_ms"), o.optDouble("total_cost_usd", 0.0),
o.optJSONObject("usage")?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") } ?: 0,
o.optJSONObject("usage")?.optLong("output_tokens") ?: 0,
),
)
else -> conversation?.let { AgentEvent(it) }
}
}
private fun resultText(content: Any?): String = when (content) {
is String -> content
is JSONArray -> (0 until content.length()).mapNotNull { i ->
val part = content.optJSONObject(i) ?: return@mapNotNull null
when (part.optString("type")) {
"text" -> part.optString("text")
"image" -> "[image]"
else -> null
}
}.joinToString("\n")
null, JSONObject.NULL -> ""
else -> content.toString()
}
private fun detail(input: JSONObject?): String {
input ?: return ""
for (key in listOf("command", "file_path", "pattern", "url", "query", "description", "prompt")) {
input.optString(key).takeIf { it.isNotEmpty() }?.let { return firstLine(it) }
}
return ""
}
@VisibleForTesting
internal fun fullInput(tool: String, input: JSONObject?): String {
input ?: return ""
return when {
tool == "Bash" -> input.optString("command")
tool == "Edit" -> "${input.optString("file_path")}\n\n- ${input.optString("old_string").replace("\n", "\n- ")}\n\n+ ${input.optString("new_string").replace("\n", "\n+ ")}"
tool == "Write" -> "${input.optString("file_path")}\n\n${input.optString("content")}"
tool == "TodoWrite" -> todos(input.optJSONArray("todos"))
else -> input.toString(2)
}
}
private fun todos(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { i ->
val todo = list?.optJSONObject(i) ?: return@mapNotNull null
val mark = when (todo.optString("status")) { "completed" -> "[x]"; "in_progress" -> "[~]"; else -> "[ ]" }
"$mark ${todo.optString("content")}"
}.joinToString("\n")
}
/** OpenAI Codex: `codex exec --json`, resumed by thread id. */
object Codex : AgentHarness {
override val id = "codex"
override val name = "Codex"
override val binary = "/root/.local/bin/codex"
// Code mode runs in a helper that each release ships as its own download.
private const val HOST = "/root/.local/bin/codex-code-mode-host"
override val files get() = listOf(binary, HOST)
override val install = """
set -e
release=${'$'}(curl -fsSL https://api.github.com/repos/openai/codex/releases/latest)
mkdir -p /root/.local/bin
for name in codex codex-code-mode-host; do
url=${'$'}(printf '%s' "${'$'}release" | grep -o "https://[^\"]*/${'$'}name-aarch64-unknown-linux-musl.tar.gz" | head -1)
echo "Downloading ${'$'}name"
curl -fsSL "${'$'}url" | tar -xz -C /tmp
install -m755 /tmp/${'$'}name-aarch64-unknown-linux-musl /root/.local/bin/${'$'}name
done
""".trimIndent()
override val signedIn = listOf(binary, "login", "status")
override val signIn = listOf(binary, "login")
override val plans = false
/** 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 {
val o = JSONObject(File(rootfs, "root/.codex/models_cache.json").readText())
val list = o.optJSONArray("models") ?: JSONArray()
(0 until list.length()).mapNotNull { i ->
val m = list.optJSONObject(i) ?: return@mapNotNull null
val slug = m.optString("slug").ifEmpty { m.optString("id") }.takeIf { it.isNotEmpty() } ?: return@mapNotNull null
if (m.has("visibility") && m.optString("visibility") != "list") return@mapNotNull null
AgentHarness.Model(slug, m.optString("display_name").ifEmpty { slug })
}
}.getOrDefault(emptyList())
// 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)) }
// 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 parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val item = o.optJSONObject("item")
val id = item?.optString("id").orEmpty()
val entries = when (o.optString("type")) {
"thread.started" -> return AgentEvent(o.optString("thread_id").takeIf { it.isNotEmpty() })
"item.started" -> when (item?.optString("type")) {
"command_execution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) }
"mcp_tool_call" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.optJSONObject("arguments")?.toString(2).orEmpty()))
"web_search" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query")))
else -> emptyList()
}
"item.updated" -> when (item?.optString("type")) {
"todo_list" -> listOf(todoEntry(id, item))
else -> emptyList()
}
"item.completed" -> when (item?.optString("type")) {
"agent_message" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty()
"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(),
item.optString("status") == "failed"))
"web_search" -> listOf(AgentHost.Entry.Result(id, "", false))
"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"),
)
"todo_list" -> listOf(todoEntry(id, item))
"error" -> listOf(AgentHost.Entry.Said("⚠ " + item.optString("message")))
else -> emptyList()
}
"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")) },
)
"turn.failed" -> listOf(AgentHost.Entry.Finished(o.optJSONObject("error")?.optString("message") ?: "turn failed"))
// codex reports a dropped stream it is retrying as an error event, and the turn goes on.
"error" -> o.optString("message").let { message ->
if (message.startsWith("Reconnecting...")) emptyList() else listOf(AgentHost.Entry.Finished(message.ifEmpty { "error" }))
}
else -> emptyList()
}
return if (entries.isEmpty()) null else AgentEvent(entries = entries)
}
private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used {
val items = item.optJSONArray("items") ?: JSONArray()
val text = (0 until items.length()).mapNotNull { i ->
val todo = items.optJSONObject(i) ?: return@mapNotNull null
"${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
internal fun firstLine(text: String) = text.lineSequence().first().take(160)
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. */
@VisibleForTesting
internal fun shellCommand(command: String) = SHELL_WRAPPER.find(command)?.groupValues?.get(1)?.replace("'\''", "'") ?: command
@@ -0,0 +1,536 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.nio.file.Files
/**
* The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless
* one process per turn, outside any game or desktop session. Conversations are kept on disk
* ([AgentChats]), so a restart (a Lab build, a crash) continues the same one.
*/
object AgentHost {
sealed interface Entry {
data class Asked(val text: String, val files: List<String> = emptyList()) : Entry
data class Said(val text: String) : Entry
data class Thought(val text: String) : Entry
/** A tool call; [output] stays null until its result arrives. */
data class Used(val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false) : Entry
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null) : Entry
}
data class Usage(val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long)
/** A message typed while the agent was working, sent when the turn ends. */
data class Queued(val text: String, val files: List<String>)
enum class State { MISSING, IDLE, WORKING }
private const val TAG = "AgentHost"
private const val WORKSPACE = "/root/DroidDeck"
private const val TICK_MS = 1_000L
private const val IDLE_TICK_MS = 5_000L
/** Where the agent runs and what the user sees, which no file in the checkout tells it. */
@VisibleForTesting
internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " +
"and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " +
"droiddeckctl (in the /root/DroidDeck checkout, tools/droiddeckctl) inspects and drives the app over loopback adb (\$ADB_SERIAL). " +
"dd-lab-build builds the checkout as a Lab build and restarts DroidDeck on it (docs/lab-builds.md). DroidDeck runs the build in a " +
"process of its own and shows the user its progress and time left; dd-lab-build follows that build's log until it is done. " +
"Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " +
"The restart ends this process, and this conversation continues on the new build. " +
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note."
val entries = mutableStateListOf<Entry>()
val queue = mutableStateListOf<Queued>()
var state by mutableStateOf(State.IDLE)
private set
var installed by mutableStateOf(false)
private set
/** The Linux runtime is there, so the agent can be set up. */
var available by mutableStateOf(false)
private set
var harness by mutableStateOf<AgentHarness>(ClaudeCode)
private set
/** The chosen model for [harness]; null is the CLI's default. */
var model by mutableStateOf<String?>(null)
private set
var plan by mutableStateOf(false)
private set
var chat by mutableStateOf<String?>(null)
private set
/** A reply finished since the conversation was last on screen. */
var unseen by mutableStateOf(false)
private set
var failed by mutableStateOf(false)
private set
/** Text and thinking of the reply being written. */
var live by mutableStateOf("")
private set
var liveThinking by mutableStateOf("")
private set
/** When the current turn started, on [SystemClock.elapsedRealtime]. */
var turnStarted by mutableLongStateOf(0L)
private set
var now by mutableLongStateOf(0L)
private set
/** Tokens in the conversation's context after its last step. */
var context by mutableLongStateOf(0L)
private set
var lab by mutableStateOf<LabProgress?>(null)
private set
private class Turn(val process: Process, val pid: Int)
private val main = Handler(Looper.getMainLooper())
private var turn: Turn? = null
/** Counts turns, so a process that starts after its turn was stopped is not adopted by the next one. */
private var generation = 0
private var labProcess: Process? = null
/** The turn now running resends a message that got no reply, so it is not resent again. */
private var retrying = false
private var resend: Runnable? = null
/** The running Lab build was asked for by the current turn, so stopping the turn stops it. */
private var labFromTurn = false
private var conversation: String? = null
private var loaded = false
private var appContext: Context? = null
val turnPid: Int get() = turn?.pid ?: 0
fun seen() {
unseen = false
}
fun refresh(context: Context) {
val app = context.applicationContext
appContext = app
File(app.filesDir, "agent").mkdirs()
harness = AgentHarness.byId(prefs(app).getString(HARNESS_KEY, null))
model = prefs(app).getString(modelKey(harness), null)
plan = prefs(app).getBoolean(PLAN_KEY, false)
available = LinuxRuntime.hasRootfs(app)
installed = harness.files.all { guestFileExists(app, it) }
if (!installed) state = State.MISSING else if (state == State.MISSING) state = State.IDLE
if (!loaded) {
loaded = true
val migrated = AgentChats.migrate(app, harness.id, prefs(app).getString(LEGACY_CONVERSATION_KEY, null))
if (migrated != null) prefs(app).edit().remove(LEGACY_CONVERSATION_KEY).putString(CHAT_KEY, migrated).apply()
prefs(app).getString(CHAT_KEY, null)?.let { load(app, it) }
resumeAfterRestart(app)
tick()
}
}
private fun load(app: Context, id: String) {
val file = AgentChats.file(app, id)
if (!file.isFile) return
val loaded = AgentChats.read(file)
if (chat != id) AgentAttachments.pending.clear()
chat = id
conversation = loaded.conversation
entries.clear()
entries.addAll(loaded.entries)
context = 0
}
/** Opens a kept conversation, switching to the CLI it belongs to. */
fun open(context: Context, id: String) {
val app = context.applicationContext
if (state == State.WORKING || id == chat) return
val harnessId = AgentChats.read(AgentChats.file(app, id)).harness
if (harnessId != null && harnessId != harness.id) {
if (AgentSetup.busy) return
prefs(app).edit().putString(HARNESS_KEY, harnessId).apply()
AgentSetup.forget()
refresh(app)
}
load(app, id)
prefs(app).edit().putString(CHAT_KEY, id).apply()
}
fun delete(context: Context, id: String) {
if (id == chat) {
if (state == State.WORKING) return
forget(context)
}
AgentChats.delete(context.applicationContext, id)
}
/**
* A Lab build restarts the app, which ends the agent's process mid-turn. dd-lab-build leaves
* [RESUME] when the app's own agent ran it, so the same conversation picks up on the new build.
*/
private fun resumeAfterRestart(app: Context) {
val marker = File(app.filesDir, RESUME)
val claimed = File(app.filesDir, "$RESUME.claimed")
if (!marker.renameTo(claimed)) return
claimed.delete()
val asked = prefs(app).getString(LAB_CHAT_KEY, null)
prefs(app).edit().remove(LAB_CHAT_KEY).apply()
if (!installed) return
// The conversation that asked for the build hears about it, even if its turn had already ended.
if (asked != null && asked != chat && AgentChats.file(app, asked).isFile) {
load(app, asked)
prefs(app).edit().putString(CHAT_KEY, asked).apply()
}
if (asked != null || interrupted(entries)) send(app, app.getString(R.string.agent_resumed))
}
/** True when DroidDeck restarted in the middle of one of the agent's turns. */
fun resuming(context: Context) = File(context.applicationContext.filesDir, RESUME).isFile
@VisibleForTesting
internal fun interrupted(entries: List<Entry>) = entries.isNotEmpty() && entries.last() !is Entry.Finished
/** Switches the agent CLI; a conversation belongs to one CLI, so a new one starts. */
fun choose(context: Context, choice: AgentHarness) {
if (choice == harness || state == State.WORKING || AgentSetup.busy) return
forget(context)
AgentSetup.forget()
prefs(context).edit().putString(HARNESS_KEY, choice.id).apply()
refresh(context)
}
fun chooseModel(context: Context, id: String?) {
model = id
prefs(context).edit().putString(modelKey(harness), id).apply()
}
fun choosePlan(context: Context, on: Boolean) {
plan = on
prefs(context).edit().putBoolean(PLAN_KEY, on).apply()
}
fun models(context: Context) = harness.models(LinuxRuntime.rootDir(context.applicationContext))
/** Sends [text] now, or after the current turn when the agent is working. */
fun send(context: Context, text: String, files: List<String> = emptyList()) {
val app = context.applicationContext
val message = text.trim()
if (message.isEmpty() && files.isEmpty()) return
cancelResend()
if (state == State.WORKING) {
queue += Queued(message, files)
return
}
if (state != State.IDLE) return
val id = chat ?: AgentChats.newId(app).also { id ->
AgentChats.start(AgentChats.file(app, id), harness.id)
chat = id
conversation = null
prefs(app).edit().putString(CHAT_KEY, id).apply()
}
val attached = AgentAttachments.adopt(app, id, files)
record(app, Entry.Asked(message, attached))
state = State.WORKING
val gen = ++generation
live = ""
liveThinking = ""
turnStarted = SystemClock.elapsedRealtime()
AgentHostService.start(app)
val current = harness
val prompt = AgentAttachments.prompt(message, attached)
val command = current.turn(prompt, conversation, AgentHarness.Options(model, plan && current.plans, BRIEF))
val workdir = workspace(app)
Thread({
runCatching { current.prepare(LinuxRuntime.rootDir(app)) }
val child = try {
guest(app, command, workdir).start()
} catch (e: Exception) {
Log.w(TAG, "could not start ${current.name}", e)
main.post { if (generation == gen) finish(app, e.message ?: "could not start") }
return@Thread
}
val started = Turn(child, AgentProcesses.pidOf(child))
main.post { if (generation == gen && state == State.WORKING && turn == null) turn = started else AgentProcesses.killTree(started.pid) }
child.outputStream.close()
var ended = false
val raw = runCatching {
val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() }
log.renameTo(File(app.filesDir, "$TURN_LOG.1"))
log.bufferedWriter()
}.getOrNull()
runCatching {
child.inputStream.bufferedReader().forEachLine { line ->
runCatching { raw?.apply { write(line); newLine(); flush() } }
val event = current.parse(line) ?: return@forEachLine
if (event.entries.any { it is Entry.Finished }) ended = true
main.post { if (turn === started) apply(app, event) }
}
}
runCatching { raw?.close() }
val status = runCatching { child.waitFor() }.getOrDefault(-1)
main.post {
if (turn === started) {
turn = null
if (state == State.WORKING && !ended) finish(app, app.getString(R.string.agent_exited, current.name, status))
}
}
}, "agent-output").start()
}
/** Ends the turn now: its process and everything it started, a build included. */
fun stop(context: Context) {
val app = context.applicationContext
val running = turn
turn = null
queue.clear()
if (labFromTurn && lab?.running == true) cancelLabBuild(app)
if (running != null) {
AgentProcesses.killTree(running.pid)
running.process.destroy()
}
if (state == State.WORKING) finish(app, null, stopped = true)
}
fun unqueue(item: Queued) {
queue.remove(item)
}
/** Starts a new conversation; the current one stays in the history. */
fun forget(context: Context) {
stop(context)
entries.clear()
if (chat != null) AgentAttachments.pending.clear()
chat = null
conversation = null
this.context = 0
prefs(context).edit().remove(CHAT_KEY).apply()
state = if (installed) State.IDLE else State.MISSING
}
/**
* A process for [command] in the Linux userland, run the way the store helpers run theirs:
* proot over the installed rootfs, without a session. Loopback adb is connected first so
* droiddeckctl reaches the app.
*/
fun guest(app: Context, command: List<String>, workdir: String = "/root", connectAdb: Boolean = true): ProcessBuilder {
val adb = AgentAdb.prepare(app)
val env = listOf(
"/usr/bin/env", "HOME=/root", "PATH=/root/.local/bin:/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8",
"ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}",
"DD_AGENT=1", "DD_AGENT_INBOX=${File(app.filesDir, "agent").path}", "BROWSER=/root/.local/bin/android-open", "DD_BROWSER_DISPLAY=${AgentAdb.browserDisplay}",
)
val shell = listOf(
"/bin/sh", "-c",
// proot ends the adb server with the command, so each command that needs adb connects it.
(if (connectAdb) "adb start-server >/dev/null 2>&1; adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " else "") +
"cd \"$1\" 2>/dev/null; shift; exec \"$@\"", "sh", workdir,
)
val proot = LinuxRuntime.command(app, null, null, Environment.getExternalStorageDirectory(), env + shell + command)
return ProcessBuilder(proot).redirectErrorStream(true).apply {
environment().apply {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
}
fun guestFileExists(context: Context, path: String): Boolean {
val file = File(LinuxRuntime.rootDir(context), path.removePrefix("/"))
return file.exists() || Files.isSymbolicLink(file.toPath())
}
private fun workspace(app: Context) = if (guestFileExists(app, WORKSPACE)) WORKSPACE else "/root"
private fun apply(app: Context, event: AgentEvent) {
event.conversation?.takeIf { it != conversation }?.let { id ->
conversation = id
chat?.let { AgentChats.appendConversation(AgentChats.file(app, it), id) }
}
event.text?.let { live += it }
event.thinking?.let { liveThinking += it }
event.context?.let { context = it }
for (entry in event.entries) when (entry) {
is Entry.Finished -> finish(app, entry.error, usage = event.usage)
else -> {
if (entry is Entry.Said) live = ""
if (entry is Entry.Thought) liveThinking = ""
record(app, entry)
}
}
AgentHostService.update(app)
}
private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) {
if (state != State.WORKING) return
turn = null
if (!stopped) labFromTurn = false
live = ""
liveThinking = ""
record(app, Entry.Finished(error, stopped, usage))
state = State.IDLE
unseen = true
failed = error != null
AgentHostService.stop(app)
// Claude Code now and then ends a resumed turn at once without reading the message; nothing
// happened, so the message is sent once more.
val asked = entries.lastOrNull { it is Entry.Asked } as? Entry.Asked
if (!stopped && error == null && asked != null && answerless(entries) && !retrying) {
retrying = true
val retryChat = chat
resend = Runnable {
resend = null
if (state == State.IDLE && chat == retryChat) send(app, asked.text, asked.files) else retrying = false
}.also { main.postDelayed(it, RETRY_MS) }
return
}
retrying = false
if (!stopped && queue.isNotEmpty()) {
val next = queue.removeAt(0)
send(app, next.text, next.files)
}
}
/** A message typed or retried by the user replaces the automatic resend. */
private fun cancelResend() {
val pending = resend ?: return
main.removeCallbacks(pending)
resend = null
retrying = false
}
private fun record(app: Context, entry: Entry) {
if (!AgentChats.merge(entries, entry)) return
chat?.let { AgentChats.append(AgentChats.file(app, it), entry) }
}
/** The last turn ended without saying or doing anything. */
fun answerless(entries: List<Entry>): Boolean {
val start = entries.indexOfLast { it is Entry.Asked }
if (start < 0) return false
val turn = entries.subList(start + 1, entries.size)
return turn.lastOrNull() is Entry.Finished && turn.none { it is Entry.Said || it is Entry.Used || it is Entry.Thought } &&
(turn.last() as Entry.Finished).let { it.error == null && !it.stopped }
}
/** Sends the last message again, after a turn that ended without a reply. */
fun retry(context: Context) {
val asked = entries.lastOrNull { it is Entry.Asked } as? Entry.Asked ?: return
send(context, asked.text, asked.files)
}
/** The tool call still running in this turn, if any. */
fun running(): Entry.Used? {
if (state != State.WORKING) return null
val start = entries.indexOfLast { it is Entry.Asked }
return entries.withIndex().lastOrNull { (i, e) -> i > start && e is Entry.Used && e.output == null }?.value as? Entry.Used
}
/** The latest todo list the agent wrote in this conversation. */
fun todos(): String? = entries.lastOrNull { it is Entry.Used && it.tool == "TodoWrite" }?.let { (it as Entry.Used).input }
private fun tick() {
now = SystemClock.elapsedRealtime()
appContext?.let { app ->
claimLabRequest(app)
claimOpenUrl(app)
// proot comes from an add-on pack fetched after the app starts, so the runtime can become usable later.
if (!available && state != State.WORKING) available = LinuxRuntime.hasRootfs(app)
lab = LabProgress.read(LinuxRuntime.rootDir(app))
AgentHostService.update(app)
}
val busy = state == State.WORKING || lab != null || AgentSetup.status.values.any { it == AgentSetup.Status.WORKING }
main.postDelayed(::tick, if (busy) TICK_MS else IDLE_TICK_MS)
}
/**
* android-open, the userland's $BROWSER, leaves a URL here for the app to open, so sign-ins
* work without Wireless debugging.
*/
private fun claimOpenUrl(app: Context) {
val request = File(app.filesDir, OPEN_URL)
if (!request.isFile) return
val claimed = File(app.filesDir, "$OPEN_URL.claimed")
if (!request.renameTo(claimed)) return
val url = runCatching { claimed.readText().trim() }.getOrNull()
claimed.delete()
if (url == null || !(url.startsWith("https://") || url.startsWith("http://"))) return
val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(AgentAdb.browserDisplay).toBundle()
runCatching { app.startActivity(intent, options) }
.recoverCatching { app.startActivity(intent) }
.onFailure {
Log.w(TAG, "could not open a sign-in link: ${it.javaClass.simpleName}")
runCatching { File(app.filesDir, "$OPEN_URL.failed").writeText("") }
}
}
/**
* dd-lab-build run by the agent hands its build to the app: the turn's processes end with the
* turn, and a build must outlive a turn that ends early or is stopped.
*/
private fun claimLabRequest(app: Context) {
val request = File(app.filesDir, LAB_REQUEST)
if (!request.isFile) return
val claimed = File(app.filesDir, "$LAB_REQUEST.claimed")
if (!request.renameTo(claimed)) return
val o = runCatching { org.json.JSONObject(claimed.readText()) }.getOrNull()
claimed.delete()
if (o == null || labProcess?.isAlive == true) return
val args = o.optJSONArray("args")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty()
val cwd = o.optString("cwd").ifEmpty { WORKSPACE }
labFromTurn = state == State.WORKING
chat?.let { prefs(app).edit().putString(LAB_CHAT_KEY, it).apply() }
AgentHostService.setupStarted(app)
Thread({
runCatching {
val child = guest(app, listOf("sh", "-c",
"mkdir -p /root/.cache; DD_LAB_DETACHED=1 exec dd-lab-build \"\$@\" > /root/.cache/dd-lab-build.log 2>&1", "dd-lab-build") + args, cwd).start()
main.post { labProcess = child }
child.outputStream.close()
child.inputStream.readBytes()
child.waitFor()
}.onFailure { Log.w(TAG, "could not run a Lab build", it) }
main.post {
labProcess = null
labFromTurn = false
AgentHostService.setupEnded(app)
}
}, "agent-lab-build").start()
}
fun cancelLabBuild(context: Context) {
val progress = lab ?: return
LabProgress.cancel(LinuxRuntime.rootDir(context.applicationContext), progress)
lab = LabProgress.read(LinuxRuntime.rootDir(context.applicationContext))
}
private const val LEGACY_CONVERSATION_KEY = "session_id"
private const val HARNESS_KEY = "harness"
private const val CHAT_KEY = "chat"
private const val PLAN_KEY = "plan"
private const val RESUME = "agent/resume"
private const val LAB_REQUEST = "agent/lab-request"
private const val OPEN_URL = "agent/open-url"
private const val LAB_CHAT_KEY = "lab_chat"
/** The raw output of the latest turn, for working out what a CLI did when the chat shows nothing. */
private const val TURN_LOG = "agent/turn.log"
private const val RETRY_MS = 3_000L
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
}
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.agent
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.os.SystemClock
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
/** Keeps the app process alive while the agent works, and says what it is doing, with a way to stop it. */
class AgentHostService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) {
if (AgentHost.lab?.running == true) AgentHost.cancelLabBuild(this)
AgentHost.stop(this)
return START_NOT_STICKY
}
awaiting = (awaiting - 1).coerceAtLeast(0)
startForeground(NOTIFICATION_ID, build(this))
if (!started && awaiting == 0) stopSelf()
return START_NOT_STICKY
}
companion object {
private const val CHANNEL_ID = "agent"
private const val NOTIFICATION_ID = 4107
private const val ACTION_STOP = "com.droiddeck.launcher.agent.STOP"
private var lastText: String? = null
@Volatile private var started = false
/**
* startForegroundService calls not yet answered by onStartCommand. Stopping the service
* before it calls startForeground crashes the app, so it then stops itself instead.
*/
private var awaiting = 0
/** Setup steps that keep the app alive while they run, besides the agent's turn. */
private var setupSteps = 0
fun start(context: Context) {
lastText = null
started = true
runCatching { context.startForegroundService(Intent(context, AgentHostService::class.java)) }
.onSuccess { awaiting++ }
}
fun stop(context: Context) {
if (setupSteps > 0) return
started = false
if (awaiting == 0) context.stopService(Intent(context, AgentHostService::class.java))
}
fun setupStarted(context: Context) {
setupSteps++
start(context)
}
fun setupEnded(context: Context) {
setupSteps = (setupSteps - 1).coerceAtLeast(0)
if (AgentHost.state != AgentHost.State.WORKING) stop(context)
}
/** Refreshes the notification with the current step; unchanged text is not re-posted. */
fun update(context: Context) {
if (!started) return
val text = describe(context)
if (text == lastText) return
lastText = text
context.getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, build(context))
}
private fun describe(context: Context): String {
val lab = AgentHost.lab?.takeIf { it.running }
if (lab != null) return context.getString(R.string.agent_lab_progress, lab.permille / 10, minutes(lab.etaSeconds.toLong().coerceAtLeast(0)))
if (AgentHost.state != AgentHost.State.WORKING) return context.getString(R.string.agent_setting_up)
val tool = AgentHost.running()
val elapsed = minutes((SystemClock.elapsedRealtime() - AgentHost.turnStarted) / 1000)
return if (tool != null) "${tool.tool} · ${tool.detail}".take(120) + " · $elapsed" else context.getString(R.string.agent_thinking_for, elapsed)
}
private fun minutes(seconds: Long) = if (seconds < 60) "${seconds.coerceAtLeast(0)}s" else "${seconds / 60}m ${seconds % 60}s"
private fun build(context: Context): Notification {
val manager = context.getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_channel_name),
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
val open = PendingIntent.getActivity(context, 0,
Intent(context, FrontEndActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent"),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val stop = PendingIntent.getService(context, 1, Intent(context, AgentHostService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val lab = AgentHost.lab?.takeIf { it.running }
return Notification.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(context.getString(when {
lab?.prepare == true -> R.string.agent_lab_preparing
lab != null -> R.string.agent_lab_building
else -> R.string.agent_working
}))
.setContentText(describe(context))
.setContentIntent(open)
.addAction(Notification.Action.Builder(null, context.getString(R.string.agent_stop), stop).build())
.setOngoing(true)
.setOnlyAlertOnce(true)
.setShowWhen(false)
.apply { if (lab != null) setProgress(1000, lab.permille, lab.stage != "building") }
.setCategory(Notification.CATEGORY_PROGRESS)
.build()
}
}
}
@@ -0,0 +1,65 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.TimeUnit
/** Runs a guest program without proot (`droiddeckctl native`), for testing the native userland. */
object AgentNative {
private const val OUTPUT_CAP = 256 * 1024
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
val root = LinuxRuntime.rootDir(context)
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
// with the setting off, staging leaves the rootfs as proot wants it
if (!com.droiddeck.launcher.session.SessionPrefs.nativeUserland(context)) NativeGuest.prepare(context, root)
if (!NativeGuest.available(root)) throw AgentException("NATIVE_UNAVAILABLE", "The rootfs has no native hook or glibc loader yet; start a session once")
val argvJson = request.optJSONArray("argv") ?: throw AgentException("INVALID_REQUEST", "argv is required")
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
if (argv.isEmpty()) throw AgentException("INVALID_REQUEST", "argv is empty")
val env = linkedMapOf<String, String>()
request.optJSONObject("env")?.let { obj -> obj.keys().forEach { env[it] = obj.getString(it) } }
val preload = request.optJSONArray("preload")?.let { a -> (0 until a.length()).map { a.getString(it) } } ?: emptyList()
val builder = NativeGuest.builder(root, request.optString("cwd", "/root"), argv, env, preload)
val started = System.nanoTime()
val process = builder.start()
val out = StringBuilder()
val err = StringBuilder()
val readers = listOf(
Thread { drain(process.inputStream, out) },
Thread { drain(process.errorStream, err) },
).onEach { it.isDaemon = true; it.start() }
// written beside the wait: a program that never reads more than a pipe holds would block it
val input = request.optString("stdin").toByteArray()
Thread {
try {
process.outputStream.use { stdin -> if (input.isNotEmpty()) stdin.write(input) }
} catch (_: java.io.IOException) {
}
}.apply { isDaemon = true; start() }
val finished = process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)
if (!finished) process.destroyForcibly().waitFor()
readers.forEach { it.join(2000) }
val code = if (finished) process.exitValue() else -1
return JSONObject().put("ok", true).put("command", "native")
.put("exitCode", code).put("timedOut", !finished)
.put("ms", (System.nanoTime() - started) / 1_000_000)
.put("stdout", JSONObject().put("text", out.toString()))
.put("stderr", JSONObject().put("text", err.toString()))
.put("argv", JSONArray(argv))
}
private fun drain(input: java.io.InputStream, into: StringBuilder) {
val buffer = ByteArray(8192)
val text = java.io.ByteArrayOutputStream()
while (true) {
val n = try { input.read(buffer) } catch (e: java.io.IOException) { -1 }
if (n < 0) break
if (text.size() < OUTPUT_CAP) text.write(buffer, 0, minOf(n, OUTPUT_CAP - text.size()))
}
into.append(text.toString(Charsets.UTF_8.name()))
}
}
@@ -0,0 +1,105 @@
package com.droiddeck.launcher.agent
import android.os.Process
import android.os.SystemClock
import androidx.annotation.VisibleForTesting
import java.io.File
/**
* Linux userland processes, read from /proc: proot runs them as real processes under the app's
* own uid, so the app can list and end them without a shell.
*/
object AgentProcesses {
data class Proc(
val pid: Int, val ppid: Int, val name: String, val args: String,
val seconds: Long, val rssKb: Long, val cpuPercent: Int, val agent: Boolean,
)
private const val HZ = 100L
private var lastTicks = emptyMap<Int, Long>()
private var lastAt = 0L
@VisibleForTesting
internal class Stat(val pid: Int, val ppid: Int, val ticks: Long, val startTicks: Long, val rssPages: Long)
/** Guest processes, those under [turnPid] (the agent's current turn) first. */
@Synchronized
fun snapshot(turnPid: Int): List<Proc> {
val me = Process.myPid()
val uid = Process.myUid()
val stats = HashMap<Int, Stat>()
val args = HashMap<Int, String>()
for (dir in File("/proc").listFiles().orEmpty()) {
val pid = dir.name.toIntOrNull() ?: continue
if (pid == me) continue
val stat = runCatching { parseStat(File(dir, "stat").readText()) }.getOrNull() ?: continue
if (!owned(dir, uid)) continue
stats[pid] = stat
args[pid] = runCatching { File(dir, "cmdline").readBytes().toString(Charsets.UTF_8).trimEnd('\u0000').replace('\u0000', ' ') }.getOrDefault("")
}
val now = SystemClock.elapsedRealtime()
val uptimeTicks = now * HZ / 1000
val elapsed = (now - lastAt).coerceAtLeast(1)
fun isProot(pid: Int) = args[pid].orEmpty().substringBefore(' ').endsWith("proot.so") || args[pid].orEmpty().substringBefore(' ').endsWith("/proot")
fun ancestors(pid: Int) = generateSequence(stats[pid]?.ppid) { stats[it]?.ppid }.takeWhile { it > 1 }.take(64)
val out = stats.values.filter { s ->
!isProot(s.pid) && args[s.pid].orEmpty().isNotEmpty() && ancestors(s.pid).any { isProot(it) }
}.map { s ->
val full = args[s.pid].orEmpty()
val cpu = lastTicks[s.pid]?.let { ((s.ticks - it) * 1000 * 100 / HZ / elapsed).toInt().coerceIn(0, 800) } ?: 0
Proc(
s.pid, s.ppid, full.substringBefore(' ').substringAfterLast('/'), full,
((uptimeTicks - s.startTicks) / HZ).coerceAtLeast(0), s.rssPages * 4, cpu,
turnPid > 0 && ancestors(s.pid).any { it == turnPid },
)
}
lastTicks = stats.mapValues { it.value.ticks }
lastAt = now
return out.sortedWith(compareByDescending<Proc> { it.agent }.thenBy { it.seconds })
}
/** Ends [pid] and everything it started, children first so none is left to be re-parented. */
fun killTree(pid: Int) {
if (pid <= 0) return
val children = HashMap<Int, MutableList<Int>>()
for (dir in File("/proc").listFiles().orEmpty()) {
val child = dir.name.toIntOrNull() ?: continue
val stat = runCatching { parseStat(File(dir, "stat").readText()) }.getOrNull() ?: continue
children.getOrPut(stat.ppid) { mutableListOf() } += child
}
val order = mutableListOf<Int>()
fun walk(p: Int) {
children[p].orEmpty().forEach(::walk)
order += p
}
walk(pid)
order.forEach { runCatching { Process.sendSignal(it, Process.SIGNAL_KILL) } }
}
fun alive(pid: Int) = pid > 0 && File("/proc/$pid").exists()
/** Processes whose command line contains [text], for ending a build the app did not start. */
fun find(text: String): List<Int> = File("/proc").listFiles().orEmpty().mapNotNull { dir ->
val pid = dir.name.toIntOrNull() ?: return@mapNotNull null
if (pid == Process.myPid()) return@mapNotNull null
val args = runCatching { File(dir, "cmdline").readBytes().toString(Charsets.UTF_8).replace('\u0000', ' ') }.getOrDefault("")
pid.takeIf { args.contains(text) && owned(dir, Process.myUid()) }
}
private fun owned(dir: File, uid: Int) = runCatching {
File(dir, "status").useLines { lines -> lines.first { it.startsWith("Uid:") }.split(Regex("\\s+"))[1].toInt() == uid }
}.getOrDefault(false)
/** `/proc/<pid>/stat`: the name in parentheses may hold spaces, so fields count from its end. */
@VisibleForTesting
internal fun parseStat(text: String): Stat {
val pid = text.substringBefore(' ').toInt()
val f = text.substring(text.lastIndexOf(')') + 2).split(' ')
return Stat(pid, f[1].toInt(), f[11].toLong() + f[12].toLong(), f[19].toLong(), f[21].toLong())
}
/** The pid of a [java.lang.Process] the app started. */
fun pidOf(process: java.lang.Process): Int =
runCatching { process.javaClass.getDeclaredField("pid").apply { isAccessible = true }.getInt(process) }.getOrNull()
?: Regex("pid=(\\d+)").find(process.toString())?.groupValues?.get(1)?.toInt() ?: 0
}
@@ -0,0 +1,176 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.concurrent.TimeUnit
/**
* First-run setup for the agent, as steps with a check and an action each. The first three are
* needed to talk to the agent; GitHub and the build tools are only needed to open pull requests
* and to make Lab builds on the device.
*/
object AgentSetup {
enum class Step(val required: Boolean) { CONNECTION(true), INSTALL(true), SIGN_IN(true), GITHUB(false), BUILD_TOOLS(false), PREPARE(false) }
enum class Status { UNKNOWN, DONE, TODO, WORKING, FAILED }
val status = mutableStateMapOf<Step, Status>()
/** The last line of output from the step that is running or just failed. */
val detail = mutableStateMapOf<Step, String>()
var runtimeInstalled by mutableStateOf(true)
private set
val ready: Boolean get() = Step.entries.filter { it.required }.all { status[it] == Status.DONE }
/** A step's action is running; its result belongs to the harness it started for. */
val busy: Boolean get() = status.values.any { it == Status.WORKING }
/** Set once the required steps have all passed, so the chat opens without waiting for the checks. */
fun completed(context: Context) = AgentHost.prefs(context).getBoolean(completedKey(AgentHost.harness), false)
private fun completedKey(harness: AgentHarness) = "setup_completed_${harness.id}"
private val main = Handler(Looper.getMainLooper())
private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git"
private const val CHECKOUT = "/root/DroidDeck"
private val HELPERS = listOf("android-open", "dd-gh-login")
private const val PROBE_TIMEOUT_S = 60L
fun check(context: Context) {
val app = context.applicationContext
runtimeInstalled = LinuxRuntime.isInstalled(app)
if (!runtimeInstalled) return
AgentHost.refresh(app)
val harness = AgentHost.harness
val probes = mutableListOf<Pair<Step, List<String>>>()
for (step in Step.entries) if (status[step] != Status.WORKING) {
when (step) {
Step.INSTALL -> set(step, if (harness.files.all { AgentHost.guestFileExists(app, it) }) Status.DONE else Status.TODO)
Step.BUILD_TOOLS -> set(step, if (buildToolsInstalled(app)) Status.DONE else Status.TODO)
Step.PREPARE -> set(step, if (prepared(app)) Status.DONE else Status.TODO)
// The install brings the userland's adb; until then the app's own pairing is all there is to check.
Step.CONNECTION -> if (!AgentHost.guestFileExists(app, "/usr/bin/adb")) {
detail.remove(step)
Thread({
val live = com.droiddeck.launcher.core.WirelessAdbFix.liveConnectAddress(app) != null
set(step, if (live) Status.DONE else Status.TODO)
}, "agent-connection").start()
} else probes += step to listOf("sh", "-c",
"for i in 1 2 3; do adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " +
"state=\$(adb -s \"\$ADB_SERIAL\" get-state 2>&1); echo \"\$state\"; [ \"\$state\" = device ] && exit 0; sleep 1; done; exit 1")
Step.SIGN_IN -> if (AgentHost.guestFileExists(app, harness.binary)) probes += step to harness.signedIn else set(step, Status.TODO)
Step.GITHUB -> probes += step to listOf("gh", "auth", "status")
}
}
Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start()
}
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
fun run(context: Context, step: Step) {
val app = context.applicationContext
val harness = AgentHost.harness
val command = when (step) {
Step.CONNECTION -> return
Step.INSTALL -> {
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
"apt-get update; apt-get install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
}
Step.SIGN_IN -> harness.signIn
Step.GITHUB -> listOf("dd-gh-login")
Step.BUILD_TOOLS -> listOf("sh", "-c", "set -e; [ -d $CHECKOUT/.git ] || git clone --filter=blob:none $REPO $CHECKOUT; " +
"cd $CHECKOUT; [ -x tools/agent/setup ] || { echo 'This DroidDeck version has no tools/agent/setup yet'; exit 1; }; tools/agent/setup")
Step.PREPARE -> listOf("sh", "-c", "cd $CHECKOUT && DD_LAB_DETACHED=1 dd-lab-build --prepare")
}
set(step, Status.WORKING)
detail.remove(step)
AgentHostService.setupStarted(app)
Thread({
val result = runCatching {
installHelpers(app)
runCatching { harness.prepare(LinuxRuntime.rootDir(app)) }
val child = AgentHost.guest(app, command).start()
child.outputStream.close()
child.inputStream.bufferedReader().forEachLine { line ->
val text = line.trim()
if (text.isNotEmpty() && !noise(text)) main.post { detail[step] = text.take(160) }
}
child.waitFor()
}
main.post {
AgentHostService.setupEnded(app)
if (result.getOrNull() == 0) {
detail.remove(step)
status[step] = Status.UNKNOWN
check(app)
} else {
status[step] = Status.FAILED
if (result.isFailure) detail[step] = result.exceptionOrNull()?.message ?: "failed"
}
}
}, "agent-setup-${step.name.lowercase()}").start()
}
fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git")
/** dd-lab-build compiled this install's commit, so a Lab build compiles only what changed. */
private fun prepared(app: Context) = runCatching {
File(LinuxRuntime.rootDir(app), "root/.cache/dd-lab-build-base").readText().trim()
.startsWith(com.droiddeck.launcher.lab.LabOverlay.apkCommit.take(7))
}.getOrDefault(false)
/** Drops what the checks found, which belonged to the previous harness. */
fun forget() {
status.clear()
detail.clear()
}
private fun probe(app: Context, harness: AgentHarness, step: Step, command: List<String>) {
var output = ""
val ok = runCatching {
val child = AgentHost.guest(app, command, connectAdb = step == Step.CONNECTION).start()
child.outputStream.close()
val reader = Thread({ output = child.inputStream.bufferedReader().readText() }, "agent-check-output").apply { isDaemon = true; start() }
val exited = child.waitFor(PROBE_TIMEOUT_S, TimeUnit.SECONDS)
if (!exited) {
AgentProcesses.killTree(AgentProcesses.pidOf(child))
child.destroyForcibly()
}
reader.join(2_000)
exited && child.exitValue() == 0
}.onFailure { output = it.message.orEmpty() }.getOrDefault(false)
main.post {
if (AgentHost.harness != harness) return@post
if (status[step] != Status.WORKING) status[step] = if (ok) Status.DONE else Status.TODO
val last = output.lines().lastOrNull { it.isNotBlank() && !noise(it.trim()) }?.trim()?.take(160)
when {
ok -> detail.remove(step)
step == Step.CONNECTION -> detail[step] = app.getString(com.droiddeck.launcher.R.string.agent_connection_off)
step.required && last != null -> detail[step] = last
}
if (ready) AgentHost.prefs(app).edit().putBoolean(completedKey(harness), true).apply()
}
}
/** proot warns about its bindings on every start; that says nothing about the step. */
private fun noise(line: String) = line.startsWith("proot warning")
private fun set(step: Step, value: Status) {
if (Looper.myLooper() == Looper.getMainLooper()) status[step] = value else main.post { status[step] = value }
}
/** Written before every step, so the helpers a step relies on are there and match this DroidDeck version. */
private fun installHelpers(app: Context) {
val bin = File(LinuxRuntime.rootDir(app), "root/.local/bin").apply { mkdirs() }
for (name in HELPERS) {
val target = File(bin, name)
app.assets.open("agent/$name").use { input -> target.outputStream().use { input.copyTo(it) } }
target.setExecutable(true, false)
}
}
}
@@ -0,0 +1,95 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.mutableStateMapOf
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
/**
* What the agent adds to the Linux userland, measured and removable piece by piece. Sign-ins
* (~/.claude, ~/.codex, gh's config) are left alone, so removing a CLI and installing it again
* does not sign out.
*/
object AgentStorage {
enum class Item(val paths: List<String>) {
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")),
BUILD_TOOLS(listOf("/root/android-sdk", "/root/aapt2", "/root/x86root", "/root/.gradle")),
SOURCE(listOf("/root/DroidDeck")),
CACHES(listOf("/root/.cache", "/root/.npm")),
}
/** Bytes per item; missing while it is being measured. */
val sizes = mutableStateMapOf<Item, Long>()
val removing = mutableStateMapOf<Item, Boolean>()
private val main = Handler(Looper.getMainLooper())
fun measure(context: Context) {
val root = LinuxRuntime.rootDir(context.applicationContext)
Thread({
for (item in Item.entries) {
val bytes = item.paths.sumOf { size(File(root, it.removePrefix("/")).toPath()) }
main.post { sizes[item] = bytes }
}
}, "agent-storage").start()
}
fun remove(context: Context, item: Item) {
val app = context.applicationContext
val root = LinuxRuntime.rootDir(app)
removing[item] = true
Thread({
for (path in item.paths) runCatching { delete(File(root, path.removePrefix("/")).toPath()) }
main.post {
removing.remove(item)
AgentHost.refresh(app)
AgentSetup.check(app)
measure(app)
}
}, "agent-storage-remove").start()
}
/** Walks without following links, so a link out of the rootfs (into /sdcard, say) counts and removes only itself. */
@VisibleForTesting
internal fun size(path: Path): Long {
if (!Files.exists(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return 0
var total = 0L
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
total += attrs.size()
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, exc: IOException) = FileVisitResult.CONTINUE
})
return total
}
@VisibleForTesting
internal fun delete(path: Path) {
if (!Files.exists(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.deleteIfExists(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
Files.deleteIfExists(dir)
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, exc: IOException): FileVisitResult {
runCatching { Files.deleteIfExists(file) }
return FileVisitResult.CONTINUE
}
})
}
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.agent
import androidx.annotation.VisibleForTesting
import org.json.JSONObject
import java.io.File
/** A Lab build in progress, as dd-lab-build reports it in `~/.cache/dd-lab-build.json`. */
data class LabProgress(
val stage: String, val prepare: Boolean, val permille: Int, val task: String,
val done: Int, val total: Int, val etaSeconds: Int, val elapsedSeconds: Int, val pid: Int,
) {
val running get() = stage in RUNNING
val failed get() = stage == "failed"
companion object {
private val RUNNING = setOf("checking", "fetching", "sdk", "planning", "building", "packaging", "restarting")
private const val PATH = "root/.cache/dd-lab-build.json"
/** A finished build stays on screen this long. */
private const val SHOW_DONE_MS = 60_000L
/** The build, while it runs and shortly after; null when there is none to show. */
fun read(rootfs: File): LabProgress? {
val file = File(rootfs, PATH)
if (!file.isFile) return null
val parsed = parse(runCatching { file.readText() }.getOrNull() ?: return null) ?: return null
val progress = when {
!parsed.running || AgentProcesses.alive(parsed.pid) -> parsed
// The restart ends the app and the script with it, so a restart that got that far succeeded.
parsed.stage == "restarting" -> parsed.copy(stage = "ready")
else -> parsed.copy(stage = "failed", task = "stopped")
}
return progress.takeIf { it.running || System.currentTimeMillis() - file.lastModified() < SHOW_DONE_MS }
}
/** Ends the build and Gradle's daemon, which keeps compiling after its client is gone. */
fun cancel(rootfs: File, progress: LabProgress) {
AgentProcesses.killTree(progress.pid)
AgentProcesses.find("GradleDaemon").forEach(AgentProcesses::killTree)
runCatching {
File(rootfs, PATH).writeText(JSONObject().put("stage", "failed").put("task", "stopped").put("pid", 0).toString())
}
}
@VisibleForTesting
internal fun parse(json: String): LabProgress? = runCatching {
val o = JSONObject(json)
LabProgress(
o.getString("stage"), o.optString("mode") == "prepare", o.optInt("permille"), o.optString("task"),
o.optInt("done"), o.optInt("total"), o.optInt("eta", -1), o.optInt("elapsed"), o.optInt("pid"),
)
}.getOrNull()
}
}
@@ -152,5 +152,7 @@ internal class AddonPack(
@JvmField
val POWERVR = AddonPack("powervr", BuildConfig.PACK_POWERVR_SHA256, BuildConfig.PACK_POWERVR_SIZE,
listOf("runtime.tzst", "version.txt"))
val UBISOFT = AddonPack("ubisoft", BuildConfig.PACK_UBISOFT_SHA256, BuildConfig.PACK_UBISOFT_SIZE,
listOf("droiddeck-upc.exe"))
}
}
@@ -278,6 +278,7 @@ object DeviceReport {
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("native userland (no proot)", SessionPrefs.nativeUserland(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
@@ -41,6 +41,7 @@ object WirelessAdbFix {
writeAtomically(context, key, identity.second)
}
@Synchronized
private fun writeAtomically(context: Context, destination: File, contents: ByteArray) {
val temporary = File(destination.parentFile, "${destination.name}.tmp")
temporary.writeBytes(contents)
@@ -70,6 +71,52 @@ object WirelessAdbFix {
"$host:${saved.port ?: ""}"
}
/**
* The saved pairing's connect address, looked up again when it no longer answers: Wireless
* debugging moves to another port whenever it restarts.
*/
fun liveConnectAddress(context: Context): String? {
val app = context.applicationContext
val saved = savedConnection(app) ?: return null
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
saved.port?.takeIf { answers(saved.host, it) }?.let { return "$host:$it" }
val loopback = runCatching { InetAddress.getByName(saved.host).isLoopbackAddress }.getOrDefault(false)
val port = if (loopback) loopbackAdbPort(app) else findConnectPort(app, saved.host, accept = { answers(saved.host, it) })
port ?: return null
saveConnection(app, saved.host, port)
return "$host:$port"
}
/**
* Wireless debugging's port on this device. Apps can read neither service.adb.tls.port nor the
* socket table, and mDNS often advertises nothing, so the ephemeral range Linux gives adbd is
* scanned on loopback (closed ports refuse at once) and the open ports are tried with our key.
*/
private fun loopbackAdbPort(app: Context): Int? {
val open = java.util.concurrent.ConcurrentLinkedQueue<Int>()
val workers = 32
val range = EPHEMERAL_PORTS
(0 until workers).map { worker ->
Thread {
var port = range.first + worker
while (port <= range.last) {
if (answers(LOOPBACK, port, 150)) open += port
port += workers
}
}.apply { start() }
}.forEach { it.join() }
loadOrCreateIdentity(app)
return open.sorted().firstOrNull { port ->
runCatching { Kadb.create(LOOPBACK, port, 1_000, 3_000).use { it.shell("true").exitCode == 0 } }.getOrDefault(false)
}
}
private val EPHEMERAL_PORTS = 32768..60999
private fun answers(host: String, port: Int, timeoutMs: Int = 500) = runCatching {
java.net.Socket().use { it.connect(java.net.InetSocketAddress(host, port), timeoutMs) }
}.isSuccess
private fun saveConnection(context: Context, host: String, port: Int) {
writeAtomically(
context,
@@ -94,7 +141,8 @@ object WirelessAdbFix {
.invoke(null, "service.adb.tls.port") as? String
}.getOrNull()?.trim()?.toIntOrNull()?.takeIf { it in 1..65535 }
fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12): Int? {
/** [accept] can pass over stale services that still advertise a port Wireless debugging left. */
fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12, accept: (Int) -> Boolean = { true }): Int? {
val manager = context.applicationContext.getSystemService(Context.NSD_SERVICE) as NsdManager
val paired = runCatching { InetAddress.getByName(pairedHost) }.getOrNull() ?: return null
val matches: (InetAddress) -> Boolean =
@@ -122,7 +170,7 @@ object WirelessAdbFix {
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
val address = serviceInfo.host
if (address != null && matches(address) && finished.compareAndSet(false, true)) {
if (address != null && matches(address) && accept(serviceInfo.port) && finished.compareAndSet(false, true)) {
resolvedPort.set(serviceInfo.port)
latch.countDown()
} else {
@@ -417,7 +417,7 @@ object AddedGames {
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null, reuse: Boolean = false) {
run {
val sidecar = StoreGameSidecar.read(folder)
val sidecar = StoreGameSidecar.read(folder)?.let { com.droiddeck.launcher.stores.StoreLaunch.adopt(folder, it) }
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
val ranking = rank(folder, reuse)
val candidates = ranking.exes
@@ -457,7 +457,11 @@ object AddedGames {
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
exeUncertain = sidecar == null && chosen == null && adopted == null && ranking.uncertain,
launchOptions = if (sidecar == null) SessionPrefs.addedGameLaunch(context, folder.path) else "",
launchOptions = when {
sidecar == null -> SessionPrefs.addedGameLaunch(context, folder.path)
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
else -> ""
},
single = single != null))
}
}
@@ -9,7 +9,7 @@ import java.io.File
import java.util.Locale
object WinCompSources {
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER, XBOX }
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER, XBOX, UBISOFT }
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
@@ -83,6 +83,13 @@ object WinCompSources {
}
}
/** The prerequisite installers a Ubisoft manifest lists, with `$INSTALL_DIR` dropped. */
internal fun ubisoftInstallRuns(setup: String?): List<String> {
val runs = setup?.let { runCatching { org.json.JSONObject(it).optJSONArray("installRuns") }.getOrNull() } ?: return emptyList()
return (0 until runs.length()).mapNotNull { runs.optJSONObject(it)?.optString("exe") }
.map { it.replace('\\', '/').removePrefix("\$INSTALL_DIR").trimStart('/') }.filter { it.isNotEmpty() }
}
fun forGame(context: Context, game: Library.SteamGame): List<Finding> {
val folder = game.gameFiles
val out = ArrayList<Finding>()
@@ -112,6 +119,12 @@ object WinCompSources {
if (parts.isEmpty()) out += Finding(null, original, Origin.AMAZON, false)
parts.forEach { out += Finding(it, original, Origin.AMAZON, true) }
}
store == Store.UBISOFT -> ubisoftInstallRuns(sidecar?.extra?.get(com.droiddeck.launcher.stores.ubisoft.UbisoftLaunch.SETUP)).forEach { exe ->
val parts = installer(exe)
val original = exe.substringAfterLast('/')
if (parts.isEmpty()) out += Finding(null, original, Origin.UBISOFT, false)
parts.forEach { out += Finding(it, original, Origin.UBISOFT, true) }
}
else -> {}
}
if (game.library == Library.ADDED && folder != null) SteamMatch.get(context, folder.path)?.let { match ->
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.input
import android.os.Build
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
@@ -7,7 +8,7 @@ import android.view.KeyEvent
/**
* Some firmware turns a mouse's right button into Back. Most report it from the mouse itself; REDMAGIC's
* cast mode injects it from no device and without the virtual-hard-key flag that the navigation bar and
* back gesture set, so that form only counts while a mouse is connected.
* back gesture set, so that form only counts while an external mouse is connected.
*/
class MouseBackInput(private val sendRight: (Boolean) -> Unit, private val mouseAttached: () -> Boolean) {
private val held = mutableSetOf<Int>()
@@ -45,6 +46,21 @@ class MouseBackInput(private val sendRight: (Boolean) -> Unit, private val mouse
}
companion object {
fun isExternalMouse(device: InputDevice?): Boolean {
if (device == null || device.isVirtual || PadBridge.isSystemVirtualInputName(device.name) ||
declaresVirtual(device.name) ||
PadBridge.isFromController(device) ||
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !device.isExternal)) return false
return (device.supportsSource(InputDevice.SOURCE_MOUSE) ||
device.supportsSource(InputDevice.SOURCE_MOUSE_RELATIVE)) &&
!device.supportsSource(InputDevice.SOURCE_TOUCHPAD) &&
!device.supportsSource(InputDevice.SOURCE_TOUCHSCREEN)
}
private val VIRTUAL_NAME = Regex("\\bvirtual\\b", RegexOption.IGNORE_CASE)
fun declaresVirtual(name: String?): Boolean = name != null && VIRTUAL_NAME.containsMatchIn(name)
fun isFromMouse(event: KeyEvent): Boolean =
event.isFromSource(InputDevice.SOURCE_MOUSE) || event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)
@@ -0,0 +1,60 @@
package com.droiddeck.launcher.lab
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.download.StoreDownloadService
/**
* Says what happened to a Lab build when the app starts, so a restart onto a new build does not
* look like a crash, and a build Android or the safety checks turned off is not lost silently.
*/
object LabNotice {
private const val CHANNEL_ID = "lab"
private const val NOTIFICATION_ID = 4120
/** Where a start that just moved a Lab build into use opens; the agent that built it sets it. */
@Volatile var openOnInstall: String = "updates"
fun started(context: Context) {
val app = context.applicationContext
val active = LabOverlay.active
val skipped = LabOverlay.skipped
val current = LabOverlay.current(app)
when {
LabOverlay.promoted && active != null ->
post(app, app.getString(R.string.lab_installed_title), app.getString(R.string.lab_installed_text, active.label), openOnInstall)
skipped == LabOverlay.SKIPPED_APP_IMAGE && current != null ->
post(app, app.getString(R.string.lab_paused_title), app.getString(R.string.lab_paused_text, current.label), "updates")
skipped == LabOverlay.Reason.OTHER_INSTALL.name || skipped == LabOverlay.Reason.DID_NOT_START.name -> {
val reason = if (skipped == LabOverlay.Reason.OTHER_INSTALL.name) R.string.lab_off_other_install else R.string.lab_off_did_not_start
post(app, app.getString(R.string.lab_off_title), app.getString(reason), "updates")
}
}
}
private fun post(app: Context, title: String, text: String, nav: String) {
val manager = app.getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, app.getString(R.string.upd_lab), NotificationManager.IMPORTANCE_DEFAULT))
val open = PendingIntent.getActivity(
app, NOTIFICATION_ID,
Intent(app, FrontEndActivity::class.java).putExtra(StoreDownloadService.EXTRA_NAV, nav)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
val notification = Notification.Builder(app, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(title)
.setContentText(text)
.setStyle(Notification.BigTextStyle().bigText(text))
.setContentIntent(open)
.setAutoCancel(true)
.build()
runCatching { manager.notify(NOTIFICATION_ID, notification) }
}
}
@@ -0,0 +1,276 @@
package com.droiddeck.launcher.lab
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.content.res.loader.ResourcesLoader
import android.content.res.loader.ResourcesProvider
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.BuildConfig
import org.json.JSONObject
import java.io.File
/**
* A Lab build: app code and resources an on-device agent built from this install's own commit,
* loaded over the installed APK at startup so it can be tried without reinstalling or re-signing.
*
* `files/lab/next` holds a build waiting for the next start and `files/lab/active` the one in use,
* each with `overlay.apk` (the build's dex files and linked resources) and `overlay.json`. A build
* that is replaced, turned off or refused moves to `files/lab/builds`, so it can be used again.
*/
object LabOverlay {
data class Info(val label: String, val baseCommit: String, val baseApk: String, val built: Long = 0)
enum class Reason { REPLACED, TURNED_OFF, OTHER_INSTALL, DID_NOT_START, UNREADABLE }
/** A build kept in `files/lab/builds`; [usable] when it was made for this install. */
data class Saved(val dir: File, val info: Info?, val reason: Reason?, val usable: Boolean)
private const val TAG = "LabOverlay"
private const val MAX_FAILED_STARTS = 2
private const val STABLE_AFTER_MS = 10_000L
private const val KEEP_BUILDS = 12
const val SKIPPED_APP_IMAGE = "app image present"
/** The installed APK's commit; this class always comes from the APK, never from a Lab build. */
val apkCommit: String = BuildConfig.SOURCE_COMMIT
@Volatile var active: Info? = null
private set
@Volatile var skipped: String? = null
private set
/** This start moved a newly staged build into use. */
@Volatile var promoted = false
private set
private var loader: Any? = null
@VisibleForTesting
internal var injectDex: (ClassLoader, File) -> Unit = ::prependDex
@VisibleForTesting
internal var openResources: (File) -> Any? = { if (Build.VERSION.SDK_INT >= 30) createLoader(it) else null }
@VisibleForTesting
internal var appImage: (Context) -> Boolean = ::hasAppImage
fun root(context: Context) = File(context.filesDir, "lab")
/** Called from [Application.attachBaseContext], before any class the build may change is loaded. */
fun load(app: Application, mainProcess: Boolean) {
active = null
skipped = null
promoted = false
try {
val root = root(app)
if (mainProcess) promoted = promote(root)
val dir = File(root, "active")
val apk = File(dir, "overlay.apk")
val meta = File(dir, "overlay.json")
if (!apk.isFile || !meta.isFile) return
val info = parse(meta.readText()) ?: return refuse(root, mainProcess, Reason.UNREADABLE)
if (!madeFor(app, info)) return refuse(root, mainProcess, Reason.OTHER_INSTALL)
if (Build.VERSION.SDK_INT < 30) return skip("needs Android 11")
// Classes in an app image are loaded before attachBaseContext and would ignore the overlay;
// dd-lab-build recompiles the app without one (cmd package compile -m verify).
if (appImage(app)) return skip(SKIPPED_APP_IMAGE)
if (mainProcess) {
val starts = failedStarts(root) + 1
if (starts > MAX_FAILED_STARTS) return refuse(root, true, Reason.DID_NOT_START)
File(root, "starts").writeText(starts.toString())
}
apk.setReadOnly()
loader = openResources(apk)
injectDex(app.classLoader, apk)
active = info
addLoader(app.resources)
app.registerActivityLifecycleCallbacks(Callbacks(root, mainProcess))
} catch (e: Throwable) {
Log.w(TAG, "Lab build not loaded", e)
skipped = e.message ?: e.javaClass.simpleName
}
}
/** The APK's path changes with every install and update of the app, so it pins a build to one install. */
fun madeFor(context: Context, info: Info) = info.baseCommit == apkCommit && info.baseApk == context.applicationInfo.sourceDir
/** The build in `active`, whether or not this start loaded it. */
fun current(context: Context): Info? = read(File(root(context), "active"))
/** A build staged for the next start. */
fun pending(context: Context): Info? = read(File(root(context), "next"))
/** Kept builds, newest first. */
fun saved(context: Context): List<Saved> = File(root(context), "builds").listFiles().orEmpty()
.filter { File(it, "overlay.apk").isFile }
.sortedByDescending { it.name.toLongOrNull() ?: 0L }
.map { dir ->
val info = read(dir)
val reason = File(dir, "reason").takeIf { it.isFile }?.readText()?.trim()?.let { r -> Reason.entries.firstOrNull { it.name == r } }
Saved(dir, info, reason, info != null && madeFor(context, info))
}
/** Leaves the Lab build and restarts the app on the installed APK. */
fun turnOff(context: Context) {
val root = root(context)
archive(root, File(root, "active"), Reason.TURNED_OFF)
archive(root, File(root, "next"), Reason.TURNED_OFF)
File(root, "next").deleteRecursively()
File(root, "starts").delete()
restart(context)
}
/** Stages [build] for the next start and keeps a build that was waiting; the caller restarts the app. */
fun stage(context: Context, build: Saved) {
val root = root(context)
val next = File(root, "next")
val waiting = File(root, "next.replaced").apply { deleteRecursively() }
next.renameTo(waiting)
next.deleteRecursively()
File(build.dir, "reason").delete()
if (!build.dir.renameTo(next)) {
waiting.renameTo(next)
error("could not stage ${build.dir.name}")
}
archive(root, waiting, Reason.REPLACED)
waiting.deleteRecursively()
}
fun delete(build: Saved) {
build.dir.deleteRecursively()
}
/**
* Android's background optimization can give the APK an app image again, which keeps a Lab
* build from loading. Recompiling without one needs a shell, which the caller provides.
*/
fun needsRecompile(context: Context) = appImage(context)
fun recompileCommand(context: Context) = "cmd package compile -m verify -f ${context.packageName}"
fun restart(context: Context) {
val launch = context.packageManager.getLaunchIntentForPackage(context.packageName)
?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
if (launch != null) context.startActivity(launch)
Runtime.getRuntime().exit(0)
}
@VisibleForTesting
internal fun parse(json: String): Info? = runCatching {
val o = JSONObject(json)
Info(o.getString("label"), o.getString("baseCommit"), o.getString("baseApk"), o.optLong("built"))
}.getOrNull()
private fun read(dir: File): Info? = File(dir, "overlay.json").takeIf { it.isFile && File(dir, "overlay.apk").isFile }?.let { parse(it.readText()) }
/** Moves `next` into use and keeps the build it replaces. Returns whether there was one to move. */
@VisibleForTesting
internal fun promote(root: File): Boolean {
val next = File(root, "next")
if (!File(next, "overlay.apk").isFile || !File(next, "overlay.json").isFile) return false
val active = File(root, "active")
archive(root, active, Reason.REPLACED)
active.deleteRecursively()
if (!next.renameTo(active)) return false
File(root, "starts").delete()
return true
}
@VisibleForTesting
internal fun archive(root: File, dir: File, reason: Reason) {
if (!File(dir, "overlay.apk").isFile) return
val builds = File(root, "builds").apply { mkdirs() }
var stamp = System.currentTimeMillis()
while (File(builds, stamp.toString()).exists()) stamp++
val target = File(builds, stamp.toString())
if (!dir.renameTo(target)) return
File(target, "reason").writeText(reason.name)
builds.listFiles().orEmpty().sortedByDescending { it.name.toLongOrNull() ?: 0L }.drop(KEEP_BUILDS).forEach { it.deleteRecursively() }
}
@VisibleForTesting
internal fun failedStarts(root: File) = File(root, "starts").takeIf { it.isFile }?.readText()?.trim()?.toIntOrNull() ?: 0
private fun refuse(root: File, mainProcess: Boolean, reason: Reason) {
skipped = reason.name
Log.w(TAG, "Lab build turned off: $reason")
if (!mainProcess) return
archive(root, File(root, "active"), reason)
File(root, "starts").delete()
File(root, "last-off-reason").writeText(reason.name)
}
private fun skip(reason: String) {
skipped = reason
Log.w(TAG, "Lab build not loaded: $reason")
}
private fun hasAppImage(context: Context): Boolean {
val apk = File(context.applicationInfo.sourceDir)
val oat = File(apk.parentFile, "oat")
return oat.listFiles().orEmpty().any { File(it, "${apk.nameWithoutExtension}.art").isFile }
}
@RequiresApi(30)
private fun createLoader(apk: File): ResourcesLoader =
ParcelFileDescriptor.open(apk, ParcelFileDescriptor.MODE_READ_ONLY).use { fd ->
ResourcesLoader().apply { addProvider(ResourcesProvider.loadFromApk(fd)) }
}
/** Gives [resources] the Lab build's resources; contexts made from them inherit it. */
fun addLoader(resources: Resources) {
if (Build.VERSION.SDK_INT < 30) return
val current = loader as? ResourcesLoader ?: return
resources.addLoaders(current)
}
private fun prependDex(classLoader: ClassLoader, apk: File) {
val pathList = field(Class.forName("dalvik.system.BaseDexClassLoader"), "pathList").get(classLoader)!!
val elementsField = field(pathList.javaClass, "dexElements")
@Suppress("UNCHECKED_CAST") val installed = elementsField.get(pathList) as Array<Any?>
val errors = ArrayList<java.io.IOException>()
val made = try {
pathList.javaClass.getDeclaredMethod("makeDexElements", List::class.java, File::class.java, List::class.java, ClassLoader::class.java)
.apply { isAccessible = true }.invoke(null, listOf(apk), null, errors, classLoader)
} catch (_: NoSuchMethodException) {
pathList.javaClass.getDeclaredMethod(
"makeDexElements", List::class.java, File::class.java, List::class.java, ClassLoader::class.java, Boolean::class.javaPrimitiveType,
).apply { isAccessible = true }.invoke(null, listOf(apk), null, errors, classLoader, false)
}
errors.firstOrNull()?.let { throw it }
@Suppress("UNCHECKED_CAST") val added = made as Array<Any?>
if (added.isEmpty()) error("no dex in ${apk.name}")
val merged = java.lang.reflect.Array.newInstance(installed.javaClass.componentType!!, added.size + installed.size)
System.arraycopy(added, 0, merged, 0, added.size)
System.arraycopy(installed, 0, merged, added.size, installed.size)
elementsField.set(pathList, merged)
}
private fun field(type: Class<*>, name: String) = type.getDeclaredField(name).apply { isAccessible = true }
private class Callbacks(private val root: File, private val mainProcess: Boolean) : Application.ActivityLifecycleCallbacks {
private var settled = false
override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) = addLoader(activity.resources)
override fun onActivityResumed(activity: Activity) {
if (settled || !mainProcess) return
settled = true
Handler(Looper.getMainLooper()).postDelayed({ File(root, "starts").delete() }, STABLE_AFTER_MS)
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) = Unit
}
}
@@ -182,6 +182,7 @@ object BwrapSpawner {
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
withoutRootfsSettings(env, rootfs)
val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
@@ -191,6 +192,24 @@ object BwrapSpawner {
return Plan(root, binds, request.optString("cwd", "/").ifEmpty { "/" }, argv, env, envTool ?: "/usr/bin/env")
}
private val ROOTFS_PIPEWIRE = listOf("PIPEWIRE_MODULE_DIR", "SPA_PLUGIN_DIR", "PIPEWIRE_CONFIG_DIR")
/**
* The session's Flatpak passes settings for the session's own root on: the native hook's,
* DroidDeck's PipeWire build, which a runtime does not have (its apps found no PipeWire plugins),
* and the session's video driver for SDL.
*/
internal fun withoutRootfsSettings(env: MutableMap<String, String>, rootfs: String) {
env.keys.removeAll { it.startsWith("DDNATV_") }
for (key in ROOTFS_PIPEWIRE) if (env[key]?.startsWith("/usr/local/lib/droiddeck-pipewire") == true) env.remove(key)
// the session's choice of X11 for SDL, in an app that Flatpak gave Wayland and no X display
if (env["SDL_VIDEODRIVER"] == "x11" && env["DISPLAY"].isNullOrEmpty() && !env["WAYLAND_DISPLAY"].isNullOrEmpty()) env.remove("SDL_VIDEODRIVER")
env["LD_PRELOAD"]?.let { preload ->
val kept = preload.split(':').filter { it.isNotEmpty() && it != rootfs && !it.startsWith("$rootfs/") }
if (kept.isEmpty()) env.remove("LD_PRELOAD") else env["LD_PRELOAD"] = kept.joinToString(":")
}
}
private const val GPU_DIR = "/run/droiddeck-gpu"
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
@@ -347,22 +366,201 @@ object BwrapSpawner {
try { Os.chmod(f.path, mode) } catch (e: Exception) { }
}
private val SANDBOX_LOADERS = listOf("/usr/lib/aarch64-linux-gnu/ld-linux-aarch64.so.1", "/usr/lib/ld-linux-aarch64.so.1",
"/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1")
private val SANDBOX_LIBCS = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/usr/lib/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6")
private val SANDBOX_LIB_DIRS = listOf("/app/lib/aarch64-linux-gnu", "/app/lib", "/usr/lib/aarch64-linux-gnu", "/usr/lib")
private val seccompPatched = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
/**
* The sandbox started by the runtime's own glibc loader with the native hook, which maps the
* sandbox's mounts; null when the runtime cannot load the hook (older glibc), so proot runs it.
*/
private fun nativeLaunch(context: Context, plan: Plan): Pair<List<String>, Map<String, String>>? {
val rootfs = LinuxRuntime.rootDir(context)
val sandbox = plan.root.path
fun host(guest: String) = File(hostPath(plan.binds, sandbox, guest))
if (!hasEnvTool(plan)) {
val program = plan.argv.firstOrNull()?.takeIf { it.startsWith("/") }?.let(::host)?.canonicalFile
?.takeIf { it.isFile && isStaticElf(it) } ?: return null
if (!linkMounts(plan)) return null
return (listOf(program.path) + plan.argv.drop(1)) to plan.env
}
val loader = SANDBOX_LOADERS.map(::host).firstOrNull { it.isFile }?.canonicalFile ?: return null
val libc = SANDBOX_LIBCS.map(::host).firstOrNull { it.isFile }?.canonicalFile ?: return null
val hook = NativeGuest.hook(rootfs)
val need = glibcMinor(hook, GLIBC_NEED) { it.maxOrNull() } ?: return null
val have = glibcMinor(libc, GLIBC_RELEASE) { it.firstOrNull() } ?: return null
if (have < need) {
Log.i(TAG, "native userland: this runtime's glibc 2.$have cannot load the hook (2.$need); proot runs the sandbox")
return null
}
for (file in listOf(loader, libc)) {
val key = "${file.path}:${file.length()}:${file.lastModified()}"
if (key in seccompPatched) continue
// an unpatched loader or libc dies under Android's filter before the hook loads: proot runs it
val patched = runCatching { ElfSeccompPatch.patchFile(file) }
.onFailure { Log.e(TAG, "native userland: could not patch $file for Android's seccomp filter; proot runs the sandbox", it) }
if (patched.isFailure) return null
seccompPatched.add("${file.path}:${file.length()}:${file.lastModified()}")
}
val program = host(plan.envTool).canonicalFile.takeIf { it.isFile } ?: return null
if (!linkMounts(plan)) return null
writeRunpathConf(plan, ::host)
val launch = listOf(loader.path, "--argv0", program.name, program.path, "-i") +
plan.env.map { (k, v) -> "$k=$v" } + plan.argv
val env = linkedMapOf(
"DDNATV_ROOT" to sandbox,
"DDNATV_LINK_ROOT" to rootfs.path,
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
"LD_PRELOAD" to hook.path,
).filterValues { it.isNotEmpty() }
return (NativeGuest.simulator(rootfs)?.let { it + launch } ?: launch) to env
}
private val runpathDirs = java.util.concurrent.ConcurrentHashMap<String, List<String>>()
/**
* ld.so opens a library's absolute RUNPATH (libpulse's pulseaudio/ directory) without the hook,
* on Android's own filesystem, so those directories are listed for the hook in the sandbox's
* ld.so.conf too, as [NativeGuest.syncLibraryDirs] does for the rootfs. A checkout never changes.
*/
private fun writeRunpathConf(plan: Plan, host: (String) -> File) {
val confDir = inRoot(plan.root, "/run/flatpak/ld.so.conf.d")?.takeIf { it.isDirectory } ?: return
val dirs = sortedSetOf<String>()
for (top in listOf("/usr/lib", "/app/lib")) {
val real = host(top).takeIf { it.isDirectory }?.canonicalFile ?: continue
dirs += runpathDirs.getOrPut(real.path) {
real.walkTopDown().maxDepth(4).onEnter { !Files.isSymbolicLink(it.toPath()) }
.filter { it.isFile && ".so" in it.name && !Files.isSymbolicLink(it.toPath()) }
.flatMap { runCatching { ElfRunpath.read(it) }.getOrDefault(emptyList()) }
.filter { it.startsWith("/usr/") || it.startsWith("/app/") || it.startsWith("/lib") }
.distinct().toList()
}
}
if (dirs.isEmpty()) return
runCatching { File(confDir, "runtime-999-droiddeck-runpath.conf").writeText(dirs.joinToString("\n", postfix = "\n")) }
}
/** A runtime extension's apply_extra runs in a sandbox with nothing but the extension itself. */
private fun hasEnvTool(plan: Plan): Boolean =
File(hostPath(plan.binds, plan.root.path, plan.envTool)).let { it.exists() || Files.isSymbolicLink(it.toPath()) }
internal fun isStaticElf(file: File): Boolean = try {
java.io.RandomAccessFile(file, "r").use { f ->
val head = ByteArray(64).also { f.readFully(it) }
if (head[0] != 0x7f.toByte() || head[1] != 'E'.code.toByte() || head[4] != 2.toByte() || head[5] != 1.toByte()) return false
val le = java.nio.ByteBuffer.wrap(head).order(java.nio.ByteOrder.LITTLE_ENDIAN)
val phoff = le.getLong(32)
val phentsize = le.getShort(54).toInt() and 0xffff
val phnum = le.getShort(56).toInt() and 0xffff
val entry = ByteArray(4)
(0 until phnum).none { i ->
f.seek(phoff + i.toLong() * phentsize)
f.readFully(entry)
java.nio.ByteBuffer.wrap(entry).order(java.nio.ByteOrder.LITTLE_ENDIAN).int == 3 // PT_INTERP
}
}
} catch (_: java.io.IOException) {
false
}
/**
* The kernel follows paths the hook does not see (ld.so, symbolic links), so each top-level
* mount of the sandbox is also a link to its source in the sandbox's own root, and the
* sandbox's links with absolute guest targets are made relative, which reaches them through those.
* False when a mount's place could not be made; proot then runs the sandbox, whose mounts hide
* whatever was left at their places.
*/
private fun linkMounts(plan: Plan): Boolean {
val root = plan.root.toPath()
plan.root.walkTopDown().onEnter { !Files.isSymbolicLink(it.toPath()) }.map { it.toPath() }
.filter { Files.isSymbolicLink(it) }.toList().forEach { link ->
runCatching {
val target = Files.readSymbolicLink(link).toString()
if (!target.startsWith("/")) return@runCatching
Files.delete(link)
Files.createSymbolicLink(link, link.parent.relativize(root.resolve(target.removePrefix("/"))))
}
}
// a mount inside another mount (a GL extension at /usr/lib/aarch64-linux-gnu/GL) needs its own
// place: the links of the mounts it is in become directories of links to their entries
val entryLinks = HashSet<java.nio.file.Path>()
for (bind in plan.binds.sortedBy { it.guest.length }) {
if (bind.guest == "/") continue
val at = try {
mountPlace(plan.root, bind.guest, entryLinks)?.also { at ->
val path = at.toPath()
if (path in entryLinks) {
Files.delete(path)
entryLinks.remove(path)
}
}
} catch (e: java.io.IOException) {
Log.e(TAG, "native userland: could not make a place for ${bind.guest}; proot runs the sandbox", e)
return false
} ?: continue
val path = at.toPath()
if (at.exists() || Files.isSymbolicLink(path)) continue
at.parentFile?.mkdirs()
runCatching { Files.createSymbolicLink(path, java.nio.file.Paths.get(bind.host)) }
}
return true
}
private fun mountPlace(root: File, guest: String, entryLinks: MutableSet<java.nio.file.Path>): File? {
val parts = guest.split('/').filter { it.isNotEmpty() }
var f = root
for ((i, part) in parts.withIndex()) {
if (part == "..") return null
f = File(f, part)
val path = f.toPath()
if (i == parts.lastIndex || !Files.isSymbolicLink(path)) continue
val target = Files.readSymbolicLink(path)
// a link of the sandbox's own tree, made relative above, is not a mount
if (!target.isAbsolute) return null
Files.delete(path)
entryLinks.remove(path)
Files.createDirectory(path)
target.toFile().listFiles()?.forEach { entry ->
val link = path.resolve(entry.name)
Files.createSymbolicLink(link, entry.toPath())
entryLinks.add(link)
}
}
return f
}
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
if (verbose != null) { cmd.add(1, "-v"); cmd.add(2, verbose.toString()) }
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
cmd.add(plan.envTool)
cmd.add("-i")
plan.env.forEach { (k, v) -> cmd.add("$k=$v") }
cmd.addAll(plan.argv)
val builder = ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root)
builder.environment().apply {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
val builder = if (native != null) {
ProcessBuilder(native.first).redirectErrorStream(true)
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
} else {
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
if (verbose != null) { cmd.add(1, "-v"); cmd.add(2, verbose.toString()) }
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
val envTool = hasEnvTool(plan)
if (envTool) {
cmd.add(plan.envTool)
cmd.add("-i")
plan.env.forEach { (k, v) -> cmd.add("$k=$v") }
}
cmd.addAll(plan.argv)
ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b ->
b.environment().apply {
clear()
if (!envTool) putAll(plan.env)
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
}
val process = builder.start()
val pid = HostProcess.pidOf(process)
@@ -0,0 +1,72 @@
package com.droiddeck.launcher.runtime
import java.io.File
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** The absolute DT_RUNPATH and DT_RPATH directories of a 64-bit little-endian ELF object. */
object ElfRunpath {
private const val PT_LOAD = 1
private const val PT_DYNAMIC = 2
private const val DT_STRTAB = 5
private const val DT_RPATH = 15
private const val DT_RUNPATH = 29
fun read(file: File): List<String> {
if (file.length() < 64) return emptyList()
RandomAccessFile(file, "r").use { raf ->
val channel = raf.channel
val header = ByteBuffer.allocate(64).order(ByteOrder.LITTLE_ENDIAN)
channel.read(header, 0)
if (header.getInt(0) != 0x464c457f || header.get(4).toInt() != 2 || header.get(5).toInt() != 1) return emptyList()
val phoff = header.getLong(32)
val phentsize = header.getShort(54).toInt() and 0xffff
val phnum = header.getShort(56).toInt() and 0xffff
if (phnum == 0 || phnum > 128 || phentsize < 56) return emptyList()
val table = ByteBuffer.allocate(phentsize * phnum).order(ByteOrder.LITTLE_ENDIAN)
channel.read(table, phoff)
class Load(val vaddr: Long, val offset: Long, val size: Long)
val loads = ArrayList<Load>()
var dynOffset = -1L
var dynSize = 0L
for (i in 0 until phnum) {
val at = i * phentsize
val type = table.getInt(at)
val offset = table.getLong(at + 8)
val vaddr = table.getLong(at + 16)
val filesz = table.getLong(at + 32)
if (type == PT_LOAD) loads.add(Load(vaddr, offset, filesz))
if (type == PT_DYNAMIC) { dynOffset = offset; dynSize = filesz }
}
if (dynOffset < 0 || dynSize <= 0 || dynSize > 1 shl 20) return emptyList()
val dynamic = ByteBuffer.allocate(dynSize.toInt()).order(ByteOrder.LITTLE_ENDIAN)
channel.read(dynamic, dynOffset)
var strtab = -1L
val names = ArrayList<Long>()
var at = 0
while (at + 16 <= dynamic.capacity()) {
val tag = dynamic.getLong(at)
val value = dynamic.getLong(at + 8)
if (tag == 0L) break
if (tag == DT_STRTAB.toLong()) strtab = value
if (tag == DT_RPATH.toLong() || tag == DT_RUNPATH.toLong()) names.add(value)
at += 16
}
if (strtab < 0 || names.isEmpty()) return emptyList()
val strtabOffset = loads.firstOrNull { strtab >= it.vaddr && strtab < it.vaddr + it.size }
?.let { strtab - it.vaddr + it.offset } ?: return emptyList()
val result = ArrayList<String>()
for (name in names) {
val buffer = ByteBuffer.allocate(4096)
val n = channel.read(buffer, strtabOffset + name)
if (n <= 0) continue
val bytes = buffer.array()
var end = 0
while (end < n && bytes[end].toInt() != 0) end++
String(bytes, 0, end, Charsets.UTF_8).split(':').filter { it.startsWith("/") }.forEach { result.add(it.trimEnd('/')) }
}
return result
}
}
}
@@ -0,0 +1,85 @@
package com.droiddeck.launcher.runtime
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Android's app seccomp filter kills a process with SIGSYS for rseq, set_robust_list and clone3. glibc's
* dynamic linker makes the first two before any preloaded library (so before the hook's SIGSYS
* handler) exists, so the call sites in the rootfs's ld.so and libc answer by themselves instead: the
* `svc` after `mov x8, #nr` becomes a no-op for set_robust_list (glibc ignores the result) and
* `mov x0, #-ENOSYS` for rseq and clone3 (glibc falls back from both). Under proot the same
* answers are what proot gives.
*/
object ElfSeccompPatch {
private const val SVC = 0xd4000001.toInt()
private const val NOP = 0xd503201f.toInt()
private const val MOV_X0_ENOSYS = 0x928004a0.toInt()
private const val MOV_X8_SET_ROBUST_LIST = 0xd2800c68.toInt()
private const val MOV_X8_CLONE3 = 0xd2803668.toInt()
private const val MOV_X8_RSEQ = 0xd28024a8.toInt()
private const val WINDOW = 16
/** Patches [data] in place and returns the number of call sites changed. */
fun patch(data: ByteArray): Int {
if (data.size < 64 || data[0] != 0x7f.toByte() || data[1] != 'E'.code.toByte() || data[4].toInt() != 2 || data[5].toInt() != 1) return 0
val buffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
if (buffer.getShort(18).toInt() != 183) return 0
val phoff = buffer.getLong(32).toInt()
val phentsize = buffer.getShort(54).toInt() and 0xffff
val phnum = buffer.getShort(56).toInt() and 0xffff
var patched = 0
for (i in 0 until phnum) {
val at = phoff + i * phentsize
if (at + 56 > data.size) break
if (buffer.getInt(at) != 1 || (buffer.getInt(at + 4) and 1) == 0) continue
val start = ((buffer.getLong(at + 8).toInt()) + 3) and 3.inv()
val end = minOf(data.size, buffer.getLong(at + 8).toInt() + buffer.getLong(at + 32).toInt()) and 3.inv()
var pos = start
while (pos + 4 <= end) {
val replacement = when (buffer.getInt(pos)) {
MOV_X8_SET_ROBUST_LIST -> NOP
MOV_X8_CLONE3, MOV_X8_RSEQ -> MOV_X0_ENOSYS
else -> null
}
if (replacement != null) {
var next = pos + 4
val limit = minOf(end, pos + 4 + WINDOW * 4)
while (next < limit) {
val insn = buffer.getInt(next)
if (insn == SVC) {
buffer.putInt(next, replacement)
patched++
break
}
// A site patched before, or x8 set again: an svc after it is another call's
// (a second run found clone3's thread exit there and turned it into -ENOSYS)
if (insn == MOV_X0_ENOSYS || (insn and 0x1f) == 8) break
next += 4
}
}
pos += 4
}
}
return patched
}
/** Patches the file behind [path] (symlinks followed) if it still has unpatched call sites. */
fun patchFile(path: File): Int {
val target = path.canonicalFile
if (!target.isFile) return 0
val data = target.readBytes()
val count = patch(data)
if (count == 0) return 0
val temp = File(target.parentFile, "." + target.name + ".seccomp")
temp.writeBytes(data)
temp.setExecutable(true, false)
temp.setReadable(true, false)
if (!temp.renameTo(target)) {
temp.delete()
throw java.io.IOException("could not replace ${target.path}")
}
return count
}
}
@@ -35,12 +35,10 @@ object GuestCommand {
SessionFiles.stage(context, root)
LinuxNetworkLinkComponent(context, root).publish()
val runtimeDir = File(context.filesDir, ".flatpak-rt").apply { mkdirs() }
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
if (linkDir != null) cmd.add(1, "--link2symlink")
val binds = LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), extraBinds)
binds.forEach { cmd.add("-b"); cmd.add(it) }
val fastPathKey = if (fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
cmd += listOf(
val native = NativeGuest.forSession(context)
val fastPathKey = if (!native && fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
val guest = mutableListOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
@@ -48,22 +46,31 @@ object GuestCommand {
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
)
DownloadSource.proxyHostPort(context).takeIf { it.isNotEmpty() }?.let { hostPort ->
cmd += listOf(
guest += listOf(
"http_proxy=http://$hostPort", "https_proxy=http://$hostPort",
"HTTP_PROXY=http://$hostPort", "HTTPS_PROXY=http://$hostPort",
"no_proxy=localhost,127.0.0.1,::1", "NO_PROXY=localhost,127.0.0.1,::1",
)
}
fastPathKey?.let { cmd += ProotFastPath.guestEnv(root, binds, it) }
cmd += argv
val builder = ProcessBuilder(cmd).directory(root).redirectErrorStream(true)
builder.environment().apply {
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
fastPathKey?.let { guest += ProotFastPath.guestEnv(root, binds, it) }
guest += argv
val builder = if (native) {
NativeGuest.processBuilder(context, root, binds, guest).redirectErrorStream(true)
} else {
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
if (linkDir != null) cmd.add(1, "--link2symlink")
binds.forEach { cmd.add("-b"); cmd.add(it) }
cmd += guest
ProcessBuilder(cmd).directory(root).redirectErrorStream(true).also { b ->
b.environment().apply {
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
}
if (cancelled?.get() == true) return 130
val process = builder.start()
@@ -155,6 +155,11 @@ public final class LinuxRuntime {
private static volatile List<String> lastBinds;
/** The mounts of a session started without proot, which sandboxes and root helpers see too. */
public static void rememberSessionBinds(List<String> binds) {
lastBinds = binds;
}
public static List<String> lastBinds(Context context) {
List<String> binds = lastBinds;
if (binds != null) return binds;
@@ -306,7 +311,17 @@ public final class LinuxRuntime {
private static boolean unreadablePciDevice() {
File[] devices = new File("/sys/bus/pci/devices").listFiles();
if (devices == null) return false;
if (devices == null) {
// The directory is there but the app may not list it (Android 13 on the AYN Thor): libpci then
// aborts the whole program with "Cannot open /sys/bus/pci/devices", which Chromium's GPU
// initialisation runs into. Not there at all (no PCI bus) is fine as it is.
try {
android.system.Os.stat("/sys/bus/pci/devices");
return true;
} catch (android.system.ErrnoException e) {
return e.errno == android.system.OsConstants.EACCES;
}
}
for (File device : devices) {
if (!new File(device, "vendor").canRead()) return true;
}
@@ -0,0 +1,269 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.nio.file.Files
/**
* Starts guest programs directly on the Android kernel, with no proot: the glibc loader of the
* rootfs runs the program and [HOOK] translates the guest's absolute paths, execs and the system
* calls Android's seccomp policy blocks, from inside the process.
*/
object NativeGuest {
private const val TAG = "NativeGuest"
const val HOOK = "usr/lib/libddnatv-hook.so"
private val LIB_DIRS = listOf("usr/lib", "usr/lib/aarch64-linux-gnu", "usr/local/lib", "usr/lib/systemd")
/** Libraries every native program loads before the hook, as /etc/ld.so.preload does for proot. */
fun preloadList(root: File): List<String> {
val listed = File(root, "etc/droiddeck/native-preload").takeIf { it.isFile }?.readLines().orEmpty()
return listed.map { it.trim() }.filter { it.startsWith("/") && File(root, it.removePrefix("/")).isFile }
}
fun enabled(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
/** The mode the running session started in; null between sessions. */
@Volatile var sessionMode: Boolean? = null
/**
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
* session's own mode while one runs, as the setting can change under it and the rootfs is only
* prepared for native programs at a session's start.
*/
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
/**
* Development switch: etc/droiddeck/seccomp-sim names a helper (a guest path, then its arguments)
* that applies Android's app seccomp filter before the program starts, for devices that run apps
* without one (eng builds, or a permissive SELinux, where zygote skips it). Guest paths among the
* arguments are given as their places in the rootfs, as the helper runs before the hook.
*/
fun simulator(root: File): List<String>? {
val words = File(root, "etc/droiddeck/seccomp-sim").takeIf { it.isFile }?.readText()?.trim()
?.split(Regex("\\s+"))?.filter { it.isNotEmpty() } ?: return null
val helper = words.firstOrNull()?.takeIf { it.startsWith("/") }?.let { File(root, it.removePrefix("/")) }
?.takeIf { it.isFile } ?: return null
return listOf(helper.path) + words.drop(1).map { if (it.startsWith("/")) File(root, it.removePrefix("/")).path else it }
}
fun hook(root: File): File = File(root, HOOK)
fun loader(root: File): File? =
listOf("usr/lib/ld-linux-aarch64.so.1", "lib/ld-linux-aarch64.so.1").map { File(root, it) }.firstOrNull { it.exists() }
fun available(root: File): Boolean = hook(root).isFile && loader(root) != null
fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path }
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
"DDNATV_ROOT" to root.path,
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
)
/**
* The host command line for the guest program at [program] (an absolute guest path to a real
* file, not a symlink).
*/
fun command(root: File, program: String, args: List<String>): List<String> {
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
val host = File(root, program.removePrefix("/"))
val launch = listOf(loader.path, "--argv0", host.name, host.path) + args
return simulator(root)?.let { it + launch } ?: launch
}
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
fun sessionEnvironment(root: File, binds: List<String>, hostname: String? = null): Map<String, String> {
val preload = preloadList(root)
return linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() }
}
/** Where guest directory [cwd] is, through the session's mounts ([binds], "src:dst"); the rootfs if it is nowhere. */
fun workingDirectory(root: File, binds: List<String>, cwd: String): File =
File(BwrapSpawner.hostPath(binds.map { BwrapSpawner.Bind.parse(it) }, root.path, cwd)).takeIf { it.isDirectory } ?: root
/** A process for [guest] (argv) started as proot would with [binds], in guest directory [cwd]. */
fun processBuilder(context: Context, root: File, binds: List<String>, guest: List<String>, cwd: String = "/root"): ProcessBuilder =
ProcessBuilder(command(root, guest.first(), guest.drop(1)))
.directory(workingDirectory(root, binds, cwd))
.also { builder ->
builder.environment().apply {
remove("LD_AUDIT")
putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context)))
}
}
private const val RUNPATH_CONF = "etc/ld.so.conf.d/zz-droiddeck-native.conf"
private val SCAN_DIRS = listOf("usr/lib", "usr/local/lib", "opt")
/**
* ld.so opens the absolute RUNPATH directories of a library itself, with system calls the hook
* cannot translate, so every one of them is also listed in ld.so.conf (which the hook maps).
* Rescanned when dpkg's state or a library directory changes.
*/
fun syncLibraryDirs(root: File) {
val conf = File(root, RUNPATH_CONF)
val signature = (listOf("var/lib/dpkg/status", "usr/lib", "usr/local/lib", "usr/lib/aarch64-linux-gnu")
.joinToString(",") { File(root, it).lastModified().toString() }) + "," + conf.parentFile.list()?.size
val stamp = File(root, "etc/droiddeck/native-runpath-signature")
if (conf.isFile && stamp.isFile && stamp.readText() == signature) return
val dirs = sortedSetOf<String>()
for (name in SCAN_DIRS) File(root, name).walkTopDown().maxDepth(6)
.onEnter { !Files.isSymbolicLink(it.toPath()) }
.filter { it.isFile && !Files.isSymbolicLink(it.toPath()) && ".so" in it.name }
.forEach { file -> runCatching { ElfRunpath.read(file) }.getOrNull()?.let { dirs.addAll(it) } }
val kept = dirs.filter { it.startsWith("/usr") || it.startsWith("/lib") || it.startsWith("/opt") }
conf.parentFile?.mkdirs()
conf.writeText(kept.joinToString("\n", postfix = "\n"))
stamp.parentFile?.mkdirs()
stamp.writeText(signature)
}
/** What a rootfs needs before anything runs in it natively; cheap once done. */
fun prepare(context: Context, root: File) {
val relinked = relinkAbsoluteSymlinks(context, root)
if (relinked > 0) android.util.Log.i(TAG, "native userland: $relinked absolute symlinks made relative")
val patched = patchForSeccomp(root)
if (patched > 0) android.util.Log.i(TAG, "native userland: $patched system call sites in ld.so and libc answer Android's blocked calls")
syncLibraryDirs(root)
}
/** See [ElfSeccompPatch]: the linker and libc must survive Android's seccomp filter before the hook loads. */
fun patchForSeccomp(root: File): Int =
listOf("usr/lib/ld-linux-aarch64.so.1", "usr/lib/aarch64-linux-gnu/ld-linux-aarch64.so.1",
"usr/lib/aarch64-linux-gnu/libc.so.6", "usr/lib/libc.so.6")
.map { File(root, it) }.filter { it.exists() }
.distinctBy { it.canonicalPath }.sumOf { file ->
runCatching { ElfSeccompPatch.patchFile(file) }.getOrElse {
android.util.Log.e(TAG, "native userland: could not patch $file for Android's seccomp filter; programs will die with SIGSYS", it)
0
}
}
private val HOST_LINK_TARGETS = listOf("/proc", "/dev", "/sys", "/sdcard", "/storage", "/data", "/system", "/vendor", "/apex",
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt")
/**
* Symbolic links the kernel follows by itself (ld.so, Steam, anything that skips the hook) read
* their absolute target on Android's own filesystem. The image's links were made for proot,
* which reads the target inside the rootfs, so each is rewritten as a relative link, which
* resolves the same way under proot and without it. Rerun when the runtime changes.
*/
fun relinkAbsoluteSymlinks(context: Context, root: File): Int {
val stamp = File(root, "etc/droiddeck/native-symlinks")
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/2"
if (stamp.isFile && stamp.readText() == version) return 0
val rootPath = root.toPath()
var rewritten = 0
Files.walkFileTree(rootPath, object : java.nio.file.SimpleFileVisitor<java.nio.file.Path>() {
override fun visitFile(file: java.nio.file.Path, attrs: java.nio.file.attribute.BasicFileAttributes): java.nio.file.FileVisitResult {
if (attrs.isSymbolicLink) {
try {
val target = Files.readSymbolicLink(file).toString()
if (target.startsWith("/") && HOST_LINK_TARGETS.none { target == it || target.startsWith("$it/") }
&& !target.startsWith(root.path)) {
val relative = file.parent.relativize(rootPath.resolve(target.removePrefix("/")))
val temp = file.resolveSibling(".relink-" + file.fileName)
Files.deleteIfExists(temp)
Files.createSymbolicLink(temp, relative)
Files.move(temp, file, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
rewritten++
}
} catch (_: java.io.IOException) {
}
}
return java.nio.file.FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException) = java.nio.file.FileVisitResult.CONTINUE
})
stamp.parentFile?.mkdirs()
stamp.writeText(version)
return rewritten
}
/**
* The guest path that host path [target] stands for in a session with [binds] ("src:dst"), or null
* when it is a guest path already: the rootfs, or the longest mount source holding it (the first
* such mount when several share a source).
*/
fun guestLinkTarget(target: String, root: String, binds: List<String>): String? {
if (!target.startsWith("/")) return null
fun under(path: String, dir: String) = path == dir || path.startsWith("$dir/")
var best: Pair<String, String>? = if (under(target, root)) root to "/" else null
for (spec in binds) {
val colon = spec.indexOf(':')
if (colon < 0) continue
val src = spec.substring(0, colon).trimEnd('/')
val dst = spec.substring(colon + 1).trimEnd('/').ifEmpty { "/" }
if (src.isEmpty() || src == dst || !under(target, src)) continue
if (best == null || src.length > best.first.length) best = src to dst
}
val (src, dst) = best ?: return null
val rest = target.removePrefix(src)
return if (rest.isEmpty()) dst else dst.trimEnd('/') + rest
}
/**
* Wine prefixes' drive links (dosdevices) hold guest paths ("s:" -> /mnt/droiddeck-sd), which
* proot follows and the hook follows inside a mount. Earlier native sessions made them point at
* their real places, which proot cannot see: those are given their guest paths back.
*/
fun relinkPrefixDrives(root: File, binds: List<String>): Int {
val compatdata = listOf(File(root, "root/.local/share/Steam/steamapps/compatdata")) + binds.mapNotNull { spec ->
val colon = spec.indexOf(':')
if (colon > 0 && spec.substring(colon + 1).trimEnd('/').endsWith("/steamapps/compatdata")) File(spec.substring(0, colon)) else null
}
var rewritten = 0
for (prefix in compatdata.distinct().flatMap { it.listFiles()?.toList().orEmpty() }) {
val devices = File(prefix, "pfx/dosdevices").toPath()
val links = try {
Files.newDirectoryStream(devices).use { it.toList() }
} catch (e: java.nio.file.NoSuchFileException) {
continue
} catch (e: java.io.IOException) {
android.util.Log.w(TAG, "native userland: could not read the drive links of $prefix", e)
continue
} catch (e: java.nio.file.DirectoryIteratorException) {
android.util.Log.w(TAG, "native userland: could not read the drive links of $prefix", e)
continue
}
for (link in links) {
try {
if (!Files.isSymbolicLink(link)) continue
val guest = guestLinkTarget(Files.readSymbolicLink(link).toString(), root.path, binds) ?: continue
val temp = link.resolveSibling(".relink-" + link.fileName)
Files.deleteIfExists(temp)
Files.createSymbolicLink(temp, java.nio.file.Paths.get(guest))
Files.move(temp, link, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
rewritten++
} catch (_: java.io.IOException) {
}
}
}
return rewritten
}
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
val program = argv.first()
val cmd = command(root, program, argv.drop(1))
val builder = ProcessBuilder(cmd).redirectErrorStream(false)
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
builder.environment().apply {
clear()
putAll(environment(root, preload))
putAll(env)
}
return builder
}
}
@@ -12,15 +12,16 @@ object ProotFastPath {
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
const val MAX_BINDS = 256
fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean =
preference && !noSeccomp && source == LinuxRuntime.PROOT_PACK
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
preference && !noSeccomp && !nativeUserland && source == LinuxRuntime.PROOT_PACK
fun enabled(context: Context): Boolean {
val preference = SessionPrefs.prootFastPath(context)
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
val nativeUserland = SessionPrefs.nativeUserland(context)
val source = LinuxRuntime.prootSource(context)
val on = allows(preference, noSeccomp, source)
if (preference && !noSeccomp && !on)
val on = allows(preference, noSeccomp, source, nativeUserland)
if (preference && !noSeccomp && !nativeUserland && !on)
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
return on
}
@@ -113,20 +113,26 @@ object RootSpawner {
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
if (argv.isEmpty()) throw IOException("no command")
val cwd = request.optString("cwd", "/root").ifEmpty { "/root" }
val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true)
cmd.add(1, "--link2symlink")
LinuxRuntime.lastBinds(context).filterNot { it.startsWith("/proc/self/fd/") }.forEach { cmd.add("-b"); cmd.add(it) }
cmd.add("/usr/bin/env")
cmd.add("-i")
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> cmd.add("$k=${e.getString(k)}") } }
cmd.addAll(argv)
val builder = ProcessBuilder(cmd).directory(root)
builder.environment().apply {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
val binds = LinuxRuntime.lastBinds(context).filterNot { it.startsWith("/proc/self/fd/") }
val guest = mutableListOf("/usr/bin/env", "-i")
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> guest.add("$k=${e.getString(k)}") } }
guest.addAll(argv)
val builder = if (NativeGuest.forSession(context)) {
NativeGuest.processBuilder(context, root, binds, guest, cwd)
} else {
val cmd = LinuxRuntime.prootPrefix(context, root, cwd, true)
cmd.add(1, "--link2symlink")
binds.forEach { cmd.add("-b"); cmd.add(it) }
cmd.addAll(guest)
ProcessBuilder(cmd).directory(root).also { b ->
b.environment().apply {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
}
val streams = listOf(stdio(fds.getOrNull(0), false), stdio(fds.getOrNull(1), true), stdio(fds.getOrNull(2), true))
try {
@@ -39,6 +39,7 @@ object BottomDesktop {
val sessionDir: File,
val generation: Int,
val installed: Boolean,
val nativeUserland: Boolean,
)
@Volatile private var launch: Launch? = null
@@ -89,10 +90,11 @@ object BottomDesktop {
root: File,
sessionDir: File,
generation: Int,
nativeUserland: Boolean,
stillCurrent: () -> Boolean,
) {
val prepared = Launch(ArrayList(guest), ArrayList(binds), sessionRoot, hostEnvironment.copyOf(), root, sessionDir, generation,
DesktopCatalog.desktopInstalled(root))
DesktopCatalog.desktopInstalled(root), nativeUserland)
synchronized(launchLock) { if (stillCurrent()) launch = prepared }
}
@@ -320,9 +322,17 @@ object BottomDesktop {
add("BL_IME_DIR=" + imeDir.path)
add(SCRIPT)
}
val command = LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
val command = if (current.nativeUserland) {
com.droiddeck.launcher.runtime.NativeGuest.command(current.root, guest.first(), guest.drop(1))
} else {
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
}
val environment = if (current.nativeUserland) {
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context))
.map { (k, v) -> "$k=$v" }.toTypedArray()
} else current.hostEnvironment
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
val pid = HostProcess.start(line, current.hostEnvironment, current.root, { status ->
val pid = HostProcess.start(line, environment, current.root, { status ->
main.post {
if (generation != guestGeneration) return@post
Log.i(TAG, "the desktop ended ($status)")
@@ -283,14 +283,20 @@ object ProtonExtras {
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
"/usr/local/bin/droiddeck-proton-extra", "/root/.local/share/Steam", archive.absolutePath,
)
val command = LinuxRuntime.command(context, null, runtimeDir, null, guest)
val process = ProcessBuilder(command)
.directory(root)
.redirectErrorStream(true)
val hostEnv = process.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
val process = if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
} else {
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
.directory(root)
.redirectErrorStream(true)
.also { builder ->
val hostEnv = builder.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
}
}
val child = process.start()
var placed: String? = null
child.inputStream.bufferedReader().useLines { lines ->
@@ -33,6 +33,37 @@ object SessionFiles {
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
)
private const val UBISOFT_SERVICE = "usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe"
/** Fetches the Ubisoft pack and, once it lands, stages the service so a running session gets it without restarting. */
fun ensureUbisoftService(context: Context) {
AddonPack.UBISOFT.ensure(context) { app ->
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).takeIf { it.isDirectory }
?.let { stageUbisoftService(app, it, null) }
}
}
@Synchronized
private fun stageUbisoftService(context: Context, root: File, ledger: StageLedger?) {
val pack = AddonPack.UBISOFT.takeIf { it.installed(context) }?.dir(context) ?: return
val target = File(root, UBISOFT_SERVICE)
if (ledger?.current(UBISOFT_SERVICE, target) == true) return
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
File(pack, "droiddeck-upc.exe").inputStream().use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage the Ubisoft launcher service", e)
} finally {
if (!installed) staged.delete()
}
if (installed) ledger?.staged(UBISOFT_SERVICE, target) else Log.e(TAG, "$UBISOFT_SERVICE NOT staged")
}
fun stage(context: Context, root: File, startsSession: Boolean = false) {
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
@@ -52,6 +83,7 @@ object SessionFiles {
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
"libddnatv-hook.so" to "usr/lib/libddnatv-hook.so",
"libblaudit.so" to "usr/local/lib/libblaudit.so",
"libssbs.so" to "usr/local/lib/libssbs.so",
"usr/local/bin/droiddeck-session" to "usr/local/bin/droiddeck-session",
@@ -251,18 +283,23 @@ object SessionFiles {
}
if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged")
}
stageUbisoftService(context, root, ledger)
ledger.save()
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
val nativeUserland = SessionPrefs.nativeUserland(context)
if (nativeUserland) com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
if (ProotFastPath.enabled(context)) {
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
preload.append(library + "\n")
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
}
val etc = File(root, "etc").apply { mkdirs() }
File(etc, "droiddeck").mkdirs()
FileUtils.writeString(File(etc, "droiddeck/native-preload"), preload.toString())
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
@@ -752,6 +752,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
}
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
@@ -665,6 +665,10 @@ class SessionService : Service() {
FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm"))
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir)
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
synchronized(stopLock) {
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionMode = nativeUserland
}
val fastPathKey = if (ProotFastPath.enabled(this)) {
val prootBinds = LinuxRuntime.binds(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds,
@@ -681,27 +685,42 @@ class SessionService : Service() {
}
} else null
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
)
val hostEnv = HostEnvironment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
if (SessionPrefs.prootNoSeccomp(this)) {
hostEnv["PROOT_NO_SECCOMP"] = "1"
Log.i(TAG, "proot: seccomp acceleration off by request")
val sessionBindSpecs = LinuxRuntime.binds(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds)
val command = if (nativeUserland) {
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
} else {
LinuxRuntime.command(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest)
}
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } }
val prootEnv = HostEnvironment()
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
prootEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
if (SessionPrefs.prootNoSeccomp(this)) {
prootEnv["PROOT_NO_SECCOMP"] = "1"
if (!nativeUserland) Log.i(TAG, "proot: seccomp acceleration off by request")
}
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> prootEnv[k] = v } }
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { hostEnv[key] = it }
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
}
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
if (prootLibs.isNotEmpty()) prootEnv["LD_LIBRARY_PATH"] = prootLibs
val terminalCommand = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
)
val drives = com.droiddeck.launcher.runtime.NativeGuest.relinkPrefixDrives(root, sessionBindSpecs)
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, SessionPrefs.guestHostname(this))
.forEach { (k, v) -> env[k] = v }
} else prootEnv
// The terminal and the bottom desktop run the way the session does: without proot when it does
val terminalCommand = if (nativeUserland) {
com.droiddeck.launcher.runtime.NativeGuest.command(root, shellGuest.first(), shellGuest.drop(1))
} else {
LinuxRuntime.command(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest)
}
val terminalHostEnvironment = LinkedHashMap(System.getenv())
hostEnv.asArray().forEach { entry ->
val separator = entry.indexOf('=')
@@ -711,7 +730,7 @@ class SessionService : Service() {
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
val (fastPathName, _) = ProotFastPath.hostEnv("")
BottomDesktop.prepare(desktopGuest, binds, sessionRoot,
hostEnv.asArray().filterNot { it.startsWith("$fastPathName=") }.toTypedArray(), root, sessionDir, gen,
prootEnv.asArray().filterNot { it.startsWith("$fastPathName=") }.toTypedArray(), root, sessionDir, gen, nativeUserland,
) { gen == sessionGen && SessionState.running }
}
@@ -2023,6 +2042,8 @@ class SessionService : Service() {
if (gen != null && gen != sessionGen) return
cancelQueuedSteamGame()
gameExitWatchToken++
// also when startup stopped before the guest ran
com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null
if (!SessionState.running) return
if (relaunch) SessionState.confirmRelaunchStop()
SessionEvents.record("guest.exited", mapOf("status" to status))
@@ -22,7 +22,7 @@ object SettingsReset {
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
@@ -87,7 +87,7 @@ object CloudSaves {
val item = sidecar.extra["catalogItemId"].orEmpty()
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> ""
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> ""
} ?: return null
p.edit()
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
@@ -148,7 +148,7 @@ object CloudSaves {
val dir = when (store) {
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> null
}
return dir to (if (dir == null) "unresolved" else "ok")
}
@@ -173,7 +173,7 @@ object CloudSaves {
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT -> null
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -13,11 +13,15 @@ internal object LoginFlows {
Store.EPIC -> epicFlow()
Store.AMAZON -> amazonFlow()
Store.GAMEJOLT -> gameJoltFlow(browserUserAgent)
Store.UBISOFT -> ubisoftFlow(browserUserAgent)
Store.EA -> eaFlow(browserUserAgent)
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
}
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
@Volatile var amazonFlow: () -> StoreLoginActivity.Flow? = { null }
@Volatile var ubisoftFlow: (String) -> StoreLoginActivity.Flow? = { null }
@Volatile var eaFlow: (String) -> StoreLoginActivity.Flow? = { null }
@Volatile var gameJoltFlow: (String) -> StoreLoginActivity.Flow? = { null }
private class GogFlow(private val state: String, override val userAgent: String) : StoreLoginActivity.Flow {
@@ -7,7 +7,9 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
XBOX("xbox", "Xbox", "Xbox"),
ITCH("itch", "Itch.io", "Itch.io"),
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
BATTLENET("battlenet", "Battle.net", "Battle.net");
BATTLENET("battlenet", "Battle.net", "Battle.net"),
UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"),
EA("ea", "EA", "EA");
val folder: String get() = if (this == ITCH) "itch" else shortLabel
@@ -3,7 +3,8 @@ package com.droiddeck.launcher.stores
import java.io.File
object StoreExe {
private val SKIP = listOf("redist", "unins", "setup", "crash", "report", "helper", "dotnet", "vcredist", "directx", "eac", "easyanticheat", "battleye", "launcher", "updater", "config")
private val SKIP = listOf("redist", "unins", "setup", "crash", "report", "helper", "dotnet", "vcredist", "directx", "eac", "easyanticheat", "battleye", "launcher", "updater", "config", "installer", "autorun")
private val SKIP_DIRS = setOf("installer_resources", "redist", "_commonredist", "support")
fun pick(folder: File, hint: String?, title: String): String {
val hinted = hint?.takeIf { it.isNotBlank() }?.replace('\\', '/')?.trimStart('/')?.let { File(folder, it) }
@@ -28,7 +29,7 @@ object StoreExe {
if (SKIP.none { lower.contains(it) }) out.add(f)
}
}
for (f in files) if (f.isDirectory && !f.name.startsWith(".")) collect(f, out, depth + 1)
for (f in files) if (f.isDirectory && !f.name.startsWith(".") && f.name.lowercase() !in SKIP_DIRS) collect(f, out, depth + 1)
}
private fun depth(root: File, f: File): Int = relative(root, f).count { it == '/' }
@@ -11,9 +11,14 @@ object StoreLaunch {
const val LAUNCHER = ".droiddeck-launch.bat"
const val EPIC_CODE = ".droiddeck-epic-code"
const val EPIC_ARGS = ".droiddeck-epic-args"
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EA_ENV = ".droiddeck-ea-env"
/** A sleeping stand-in that the launch hook installs; older EA SDKs require a running Origin process. */
const val EA_ORIGIN = "C:\\Program Files (x86)\\Origin\\Origin.exe"
fun writeLauncher(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC
val needs = sidecar.args.isNotEmpty() || sidecar.env.isNotEmpty() || sidecar.store == Store.EPIC || sidecar.store == Store.EA || sidecar.store == Store.UBISOFT
val file = File(folder, LAUNCHER)
if (!needs) { file.delete(); return sidecar.copy(launcher = null) }
file.writeText(launcherText(sidecar))
@@ -49,6 +54,21 @@ object StoreLaunch {
lines += "del \"%~dp0$EPIC_ARGS\""
lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\""
lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%"
} else if (sidecar.store == Store.UBISOFT) {
lines += "if not exist \"%~dp0$UBISOFT_LAUNCH\" goto direct"
lines += "if not exist \"$UBISOFT_SERVICE\" goto direct"
lines += "\"$UBISOFT_SERVICE\" \"%~dp0$UBISOFT_LAUNCH\""
lines += "goto :eof"
lines += ":direct"
lines += run
} else if (sidecar.store == Store.EA) {
lines += "if not exist \"%~dp0$EA_ENV\" goto run"
lines += "for /f \"usebackq tokens=1,* delims==\" %%a in (\"%~dp0$EA_ENV\") do set \"%%a=%%b\""
lines += "del \"%~dp0$EA_ENV\""
lines += ":run"
lines += "if exist \"$EA_ORIGIN\" start \"\" \"$EA_ORIGIN\""
lines += run
lines += "taskkill /f /im Origin.exe >nul 2>&1"
} else {
lines += run
}
@@ -73,6 +93,17 @@ object StoreLaunch {
return Library.addedGame(context, game)
}
/** Gives a Ubisoft game installed before it needed one the launcher that starts the launcher service. */
fun adopt(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
if (sidecar.store != Store.UBISOFT || !sidecar.isInstalled) return sidecar
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
if (sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
val exe = if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
if (exe == sidecar.exe && sidecar.launcher == LAUNCHER &&
runCatching { File(folder, LAUNCHER).readText() }.getOrNull() == launcherText(sidecar)) return sidecar
return runCatching { writeLauncher(folder, sidecar.copy(exe = exe)).also { it.write(folder) } }.getOrDefault(sidecar)
}
fun refreshLauncher(folder: File, sidecar: StoreGameSidecar) {
if (sidecar.launcher != LAUNCHER) return
val file = File(folder, LAUNCHER)
@@ -38,6 +38,7 @@ object StoreLaunchRequests {
fun stop() {
com.droiddeck.launcher.stores.xbox.XboxRuntime.stop()
com.droiddeck.launcher.stores.ea.EaLsx.stop()
synchronized(lock) {
observer?.stopWatching()
observer = null
@@ -58,6 +59,12 @@ object StoreLaunchRequests {
"xbox-renew" -> JSONObject().put("ok", com.droiddeck.launcher.stores.xbox.XboxRuntime.renew(app, request.optString("id"), request.optString("lease")))
"xbox-prepare" -> runCatching { com.droiddeck.launcher.stores.xbox.XboxRuntime.prepare(app, request.getString("id")) }
.getOrElse { JSONObject().put("ok", false).put("reason", "Xbox account service is unavailable. Sign in again and retry.") }
"ea-prepare" -> runCatching { lastLaunched = Store.EA to request.optString("id"); com.droiddeck.launcher.stores.ea.EaLaunch.prepare(app, request) }
.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
"ea-exited" -> {
com.droiddeck.launcher.stores.ea.EaLsx.stop(request.optString("id"))
JSONObject().put("ok", true)
}
"gog-achievements" -> runCatching { com.droiddeck.launcher.stores.gog.GogComet.prepare(app, request.optString("id")) }
.getOrElse { JSONObject().put("ok", false).put("ready", false).put("reason", "service-unavailable") }
"epic-code" -> {
@@ -69,6 +76,15 @@ object StoreLaunchRequests {
JSONObject().put("ok", true).put("code", code.written).put("reason", code.reason)
}
}
"ubisoft-launch" -> {
val id = request.optString("id")
if (id.isEmpty()) JSONObject().put("ok", false).put("reason", "no-id")
else {
lastLaunched = Store.UBISOFT to id
runCatching { com.droiddeck.launcher.stores.ubisoft.UbisoftLaunch.prepare(app, id) }
.getOrElse { JSONObject().put("ok", false).put("reason", it.javaClass.simpleName) }
}
}
"cloud-down" -> {
val store = Store.byId(request.optString("store"))
val id = request.optString("id")
@@ -47,6 +47,9 @@ class StoreLoginActivity : ComponentActivity() {
?.takeIf { "Chrome/" in it }
?: "Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; ${Build.MODEL}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.103 Mobile Safari/537.36"
private const val PAGE_TRIES = 20
private const val PAGE_RETRY_MS = 500L
fun generateState(): String {
val bytes = ByteArray(24)
java.security.SecureRandom().nextBytes(bytes)
@@ -60,6 +63,8 @@ class StoreLoginActivity : ComponentActivity() {
fun isRedirect(url: String): Boolean
fun finish(activity: StoreLoginActivity, view: WebView, url: String): String?
val readsPage: Boolean get() = false
val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()"
fun pageReady(result: String): Boolean = true
fun forgetSignIn(done: () -> Unit) = done()
}
@@ -323,6 +328,14 @@ class StoreLoginActivity : ComponentActivity() {
}
}
private fun readPage(view: WebView, f: Flow, left: Int) {
view.evaluateJavascript(f.pageScript) { json ->
val result = json ?: ""
if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS)
else Thread({ settle(f.finish(this, view, result)) }, "store-login").start()
}
}
private fun complete(view: WebView, url: String) {
if (!captured.compareAndSet(false, true)) return
val f = flow ?: return
@@ -332,11 +345,7 @@ class StoreLoginActivity : ComponentActivity() {
titleText.text = getString(R.string.stores_login_finishing)
if (!f.readsPage) view.stopLoading()
}
if (f.readsPage) {
view.evaluateJavascript("(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()") { json ->
Thread({ settle(f.finish(this, view, json ?: "")) }, "store-login").start()
}
} else Thread({ settle(f.finish(this, view, url)) }, "store-login").start()
if (f.readsPage) readPage(view, f, PAGE_TRIES) else Thread({ settle(f.finish(this, view, url)) }, "store-login").start()
}
private fun settle(problem: String?) {
@@ -55,7 +55,8 @@ object StoreSizes {
Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.ITCH, Store.GAMEJOLT -> {}
Store.GOG, Store.XBOX, Store.BATTLENET -> {}
Store.EA -> com.droiddeck.launcher.stores.ea.EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> {}
}
}
}, pool).exceptionally { error ->
@@ -111,7 +112,8 @@ object StoreSizes {
val bytes = AmazonApiClient.getBytes(AmazonApiClient.appendPath(spec.downloadUrl, "manifest.proto"), token) ?: return 0L
AmazonManifest.parse(bytes).totalInstallSize
}
Store.GOG, Store.XBOX, Store.BATTLENET -> 0L
Store.EA -> com.droiddeck.launcher.stores.ea.EaSizes.size(context, item)
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT -> 0L
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
} }
@@ -0,0 +1,224 @@
package com.droiddeck.launcher.stores.ea
import android.net.Uri
import org.json.JSONArray
import org.json.JSONObject
class EaApiException(val status: Int, message: String) : Exception(message)
object EaApi {
private const val GRAPHQL = "https://service-aggregation-layer.juno.ea.com/graphql"
private const val LOCALE = "DEFAULT"
class Player(val userId: String, val personaId: String, val displayName: String, val eaId: String)
class OwnedProduct(
val offerId: String,
val productId: String,
val name: String,
val slug: String,
val baseSlug: String,
val gameType: String,
val downloadable: Boolean,
val trial: Boolean,
val ownership: List<String>,
)
class Offer(
val offerId: String,
val contentId: String,
val displayName: String,
val displayType: String,
val downloadable: Boolean,
val executePathOverride: String,
val installCheckOverride: String,
val executeParameters: String,
val multiplayerId: String,
val masterTitleId: String,
val gameVersion: String,
val cloudSaves: String,
val locales: List<String>,
)
class Images(val tall: String?, val wide: String?, val logo: String?)
class Build(val buildId: String, val gameVersion: String, val liveDate: String)
private val queries = HashMap<String, String>()
internal fun query(name: String): String = synchronized(queries) {
queries.getOrPut(name) {
val stream = EaApi::class.java.getResourceAsStream("/ea/graphql/$name.gql") ?: throw IllegalStateException("missing query $name")
stream.use { it.readBytes().toString(Charsets.UTF_8) }
}
}
private fun persisted(name: String): String =
JSONObject().put("persistedQuery", JSONObject().put("version", 1).put("sha256Hash", EaCrypto.hex(EaCrypto.sha256(query(name).toByteArray())))).toString()
internal fun call(token: String, name: String, variables: JSONObject): JSONObject {
val headers = mapOf("Authorization" to "Bearer $token", "Accept" to "application/json")
val get = Uri.parse(GRAPHQL).buildUpon()
.appendQueryParameter("extensions", persisted(name))
.appendQueryParameter("operationName", name)
.appendQueryParameter("variables", variables.toString())
.build().toString()
var reply = EaHttp.request(get, headers = headers)
var json = runCatching { JSONObject(reply.text) }.getOrNull()
if (!reply.ok || json == null || json.has("errors")) {
val body = JSONObject()
.put("extensions", JSONObject(persisted(name)))
.put("variables", variables)
.put("operationName", name)
.put("query", query(name))
reply = EaHttp.request(GRAPHQL, "POST", headers + ("Content-Type" to "application/json"), body.toString().toByteArray())
json = runCatching { JSONObject(reply.text) }.getOrNull()
}
if (reply.status == 401) throw EaApiException(401, "EA refused the session")
if (json == null) throw EaApiException(reply.status, "EA gave no answer to $name (${reply.status})")
json.optJSONArray("errors")?.optJSONObject(0)?.let { throw EaApiException(reply.status, "$name: ${it.optString("message")}") }
return json.optJSONObject("data") ?: throw EaApiException(reply.status, "$name returned no data")
}
fun player(token: String): Player {
val me = call(token, "GetUserPlayer", JSONObject()).optJSONObject("me") ?: throw EaApiException(0, "no player")
val p = me.optJSONObject("player")
return Player(
userId = me.optString("pd"),
personaId = p?.optString("psd").orEmpty(),
displayName = p?.optString("displayName").orEmpty(),
eaId = p?.optString("uniqueName").orEmpty().ifEmpty { p?.optString("displayName").orEmpty() },
)
}
internal fun parseOwned(page: JSONObject): Pair<List<OwnedProduct>, String?> {
val owned = page.optJSONObject("me")?.optJSONObject("ownedGameProducts") ?: return emptyList<OwnedProduct>() to null
val items = owned.optJSONArray("items") ?: JSONArray()
val list = (0 until items.length()).mapNotNull { items.optJSONObject(it) }.mapNotNull { o ->
val product = o.optJSONObject("product") ?: return@mapNotNull null
val base = product.optJSONObject("baseItem")
val user = product.optJSONObject("gameProductUser")
val methods = user?.optJSONArray("ownershipMethods")
OwnedProduct(
offerId = o.optString("originOfferId").ifEmpty { return@mapNotNull null },
productId = product.optString("id"),
name = (base?.optString("title")?.takeIf { it.isNotBlank() } ?: product.optString("name")).replace("\n", " ").trim(),
slug = product.optString("gameSlug"),
baseSlug = base?.optString("baseGameSlug").orEmpty().takeIf { it != "null" }.orEmpty(),
gameType = base?.optString("gameType").orEmpty(),
downloadable = product.optBoolean("downloadable", true),
trial = product.optJSONObject("trialDetails")?.optString("trialType").orEmpty().let { it.isNotEmpty() && it != "null" },
ownership = (0 until (methods?.length() ?: 0)).map { methods!!.optString(it) },
)
}
val next = owned.optString("next").takeIf { it.isNotBlank() && it != "null" }
return list to next
}
fun owned(token: String): List<OwnedProduct> {
val out = ArrayList<OwnedProduct>()
var next: String? = "0"
var guard = 0
while (next != null && guard++ < 50) {
val variables = JSONObject()
.put("isMac", false)
.put("limit", 100)
.put("next", next)
.put("type", JSONArray().put("DIGITAL_FULL_GAME").put("PACKAGED_FULL_GAME"))
.put("storefronts", JSONArray().put("EA"))
.put("platforms", JSONArray().put("PC"))
val (items, after) = parseOwned(call(token, "getPreloadedOwnedGames", variables))
out += items
next = after?.takeIf { it != next && items.isNotEmpty() }
}
return out
}
internal fun parseOffers(data: JSONObject): List<Offer> {
val arr = data.optJSONArray("legacyOffers") ?: return emptyList()
return (0 until arr.length()).mapNotNull { arr.optJSONObject(it) }.mapNotNull { o ->
val downloads = o.optJSONArray("downloads")
val version = (0 until (downloads?.length() ?: 0)).mapNotNull { downloads!!.optJSONObject(it) }
.firstOrNull { it.optString("downloadType").equals("LIVE", true) }?.optString("gameVersion")
?: downloads?.optJSONObject(0)?.optString("gameVersion")
val locales = o.optJSONArray("softwareLocales")
fun s(k: String) = o.optString(k).takeIf { it != "null" }.orEmpty()
Offer(
offerId = s("offerId").ifEmpty { return@mapNotNull null },
contentId = s("contentId"),
displayName = s("displayName"),
displayType = s("displayType"),
downloadable = o.optBoolean("isDownloadable", true),
executePathOverride = s("executePathOverride"),
installCheckOverride = s("installCheckOverride"),
executeParameters = s("executeParameters"),
multiplayerId = s("multiplayerId"),
masterTitleId = s("primaryMasterTitleId"),
gameVersion = version.orEmpty().takeIf { it != "null" }.orEmpty(),
cloudSaves = s("cloudSaveConfigurationOverride"),
locales = (0 until (locales?.length() ?: 0)).map { locales!!.optString(it) },
)
}
}
fun offers(token: String, ids: List<String>): List<Offer> = ids.distinct().chunked(50).flatMap { chunk ->
parseOffers(call(token, "getLegacyCatalogDefs", JSONObject().put("offerIds", JSONArray(chunk))))
}
private fun path(o: JSONObject?, vararg keys: String): String? {
var cur = o ?: return null
for (k in keys.dropLast(1)) cur = cur.optJSONObject(k) ?: return null
return cur.optString(keys.last()).takeIf { it.startsWith("http") }
}
internal fun parseImages(data: JSONObject): Images {
val game = data.optJSONObject("game")
val key = game?.optJSONObject("keyArt")
val pack = game?.optJSONObject("packArt")
return Images(
tall = path(pack, "aspect9x16Image", "path") ?: path(key, "aspect9x16Image", "path"),
wide = path(key, "aspect16x9Image", "path") ?: path(key, "largestImage", "path") ?: path(pack, "aspect2x1Image", "path"),
logo = path(game, "primaryLogo", "largestImage", "path") ?: path(game, "primaryLogo", "path"),
)
}
fun images(token: String, slug: String): Images =
parseImages(call(token, "GameImages", JSONObject().put("gameSlug", slug).put("locale", LOCALE)))
fun downloadUrl(token: String, offerId: String, buildId: String? = null): String {
val data = call(token, "downloadUrl", JSONObject().put("offerId", offerId).put("buildId", buildId.orEmpty()))
return data.optJSONObject("downloadUrl")?.optString("url").orEmpty().ifEmpty { throw EaApiException(0, "EA gave no download link") }
}
fun builds(token: String, offerId: String): List<Build> {
val arr = call(token, "availableBuilds", JSONObject().put("offerId", offerId)).optJSONArray("availableBuilds") ?: return emptyList()
return (0 until arr.length()).mapNotNull { arr.optJSONObject(it) }.map {
Build(it.optString("buildId"), it.optString("gameVersion").takeIf { v -> v != "null" }.orEmpty(), it.optString("buildLiveDate"))
}
}
fun legacyEntitlements(token: String): List<JSONObject> {
val out = ArrayList<JSONObject>()
var next: String? = "0"
var guard = 0
while (next != null && guard++ < 50) {
val variables = JSONObject().put("limit", 100).put("next", next).put("storeFronts", JSONArray().put("EA"))
val page = call(token, "getLegacyEntitlements", variables).optJSONObject("me")?.optJSONObject("legacyEntitlements") ?: break
val items = page.optJSONArray("items") ?: JSONArray()
for (i in 0 until items.length()) items.optJSONObject(i)?.let(out::add)
next = page.optString("next").takeIf { it.isNotBlank() && it != "null" && it != next && items.length() > 0 }
}
return out
}
fun entitlements(token: String, group: String): JSONArray {
val variables = JSONObject()
.put("productIds", JSONArray())
.put("includeChildGroups", false)
.put("groupNames", JSONArray().put(group))
.put("entitlementTag", "")
.put("pageSize", 100)
.put("pageNumber", 1)
return call(token, "sdkEntitlements", variables).optJSONObject("me")?.optJSONObject("sdkEntitlements")?.optJSONArray("entitlements") ?: JSONArray()
}
}
@@ -0,0 +1,230 @@
package com.droiddeck.launcher.stores.ea
import android.content.Context
import android.net.Uri
import android.util.Log
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import org.json.JSONObject
import java.security.SecureRandom
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
object EaAuth {
private const val TAG = "EaAuth"
const val CLIENT_ID = "JUNO_PC_CLIENT"
private const val CLIENT_SECRET = "4mRLtYMb6vq9qglomWEaT4ChxsXWcyqbQpuBNfMPOYOiDmYYQmjuaBsF2Zp0RyVeWkfqhE9TuGgAw7te"
const val AUTH_URL = "https://accounts.ea.com/connect/auth"
private const val TOKEN_URL = "https://accounts.ea.com/connect/token"
const val REDIRECT = "qrc:///html/login_successful.html"
private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L
private val refreshLock = Any()
private val random = SecureRandom()
private val PC_SIGN_KEYS = mapOf(
"v1" to "ISa3dpGOc8wW7Adn4auACSQmaccrOyR2".toByteArray(),
"v2" to "nt5FfJbdPzNcl2pkC3zgjO43Knvscxft".toByteArray(),
)
val OPAQUE_SCOPES = listOf(
"basic.commerce.cartv2", "service.atom", "dp.client.default", "signin", "social_recommendation_user",
"basic.optin.write", "basic.commerce.cartv2.write", "basic.billing", "external.social_information_ups_admin",
)
class Account(
val accessToken: String,
val refreshToken: String,
val expiresAt: Long,
val userId: String,
val personaId: String,
val displayName: String,
val eaId: String,
)
class Pending(val url: String, val verifier: String)
internal fun fromJson(o: JSONObject): Account? {
val access = o.optString("access_token").ifEmpty { return null }
return Account(
accessToken = access,
refreshToken = o.optString("refresh_token"),
expiresAt = o.optLong("expires_at"),
userId = o.optString("user_id"),
personaId = o.optString("persona_id"),
displayName = o.optString("display_name"),
eaId = o.optString("ea_id"),
)
}
fun load(context: Context): Account? = StoreAccounts.read(context.applicationContext, Store.EA)?.let(::fromJson)
private fun deviceId(context: Context): String {
val prefs = EaPrefs.get(context)
prefs.getString("device", null)?.let { return it }
val made = EaCrypto.hex(ByteArray(16).also(random::nextBytes))
prefs.edit().putString("device", made).apply()
return made
}
internal fun pcSign(device: String, now: Date = Date(), version: String = if (random.nextBoolean()) "v1" else "v2"): String {
val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(now)
val mid = EaCrypto.fnv1a(("DroidDeck" + device.uppercase() + "DroidDeck").toByteArray()).toString()
val json = "{\"av\":\"v1\",\"bsn\":\"None\",\"gid\":0,\"hsn\":\"None\",\"mid\":\"$mid\",\"msn\":\"${device.uppercase()}\",\"sv\":\"$version\",\"ts\":\"$stamp\"}"
val payload = EaCrypto.base64Url(json.toByteArray())
val signature = EaCrypto.base64Url(EaCrypto.hmacSha256(PC_SIGN_KEYS.getValue(version), payload.toByteArray()))
return "$payload.$signature"
}
internal fun authUrl(
device: String,
responseType: String,
challenge: String? = null,
accessToken: String? = null,
clientId: String = CLIENT_ID,
scopes: List<String> = emptyList(),
tokenFormat: String? = null,
expiresIn: Int? = null,
): String {
val b = Uri.parse(AUTH_URL).buildUpon()
.appendQueryParameter("client_id", clientId)
.appendQueryParameter("sbiod_enabled", "false")
.appendQueryParameter("response_type", responseType)
.appendQueryParameter("locale", "en_US")
.appendQueryParameter("pc_sign", pcSign(device))
.appendQueryParameter("nonce", random.nextInt().toString())
if (scopes.isNotEmpty()) b.appendQueryParameter("scope", scopes.joinToString(" "))
if (challenge != null) {
b.appendQueryParameter("code_challenge_method", "S256")
b.appendQueryParameter("code_challenge", challenge)
}
if (accessToken != null) b.appendQueryParameter("access_token", accessToken)
if (tokenFormat != null) b.appendQueryParameter("token_format", tokenFormat)
if (expiresIn != null) b.appendQueryParameter("expires_in", expiresIn.toString())
return b.build().toString()
}
fun begin(context: Context): Pending {
val verifier = EaCrypto.base64Url(ByteArray(32).also(random::nextBytes))
val challenge = EaCrypto.base64Url(EaCrypto.sha256(verifier.toByteArray()))
return Pending(authUrl(deviceId(context), "code", challenge = challenge), verifier)
}
/** Pulls one parameter out of the redirect EA sends to its desktop client's local page. */
internal fun redirectValue(location: String, name: String): String? {
val normal = location.replace("qrc:///html", "http://127.0.0.1").replace("qrc:/html", "http://127.0.0.1")
val uri = Uri.parse(normal)
uri.getQueryParameter(name)?.let { return it }
val fragment = uri.encodedFragment ?: return null
return Uri.parse("http://x/?$fragment").getQueryParameter(name)
}
private fun tokenCall(values: List<Pair<String, String>>): JSONObject {
val reply = EaHttp.request(
TOKEN_URL, "POST",
mapOf("Content-Type" to "application/x-www-form-urlencoded"),
EaHttp.form(values + listOf("client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET)).toByteArray(),
follow = false,
)
val json = runCatching { JSONObject(reply.text) }.getOrNull()
if (!reply.ok || json == null || json.optString("access_token").isEmpty()) {
throw IllegalStateException("EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}")
}
return json
}
fun exchange(context: Context, code: String, verifier: String) {
val token = tokenCall(
listOf(
"grant_type" to "authorization_code", "code" to code, "code_verifier" to verifier,
"redirect_uri" to REDIRECT, "token_format" to "JWS",
),
)
val access = token.getString("access_token")
val player = runCatching { EaApi.player(access) }.onFailure { Log.w(TAG, "player: ${it.message}") }.getOrNull()
val record = JSONObject()
.put("access_token", access)
.put("refresh_token", token.optString("refresh_token"))
.put("expires_at", System.currentTimeMillis() + token.optLong("expires_in", 3600) * 1000)
.put("user_id", player?.userId.orEmpty())
.put("persona_id", player?.personaId.orEmpty())
.put("display_name", player?.displayName.orEmpty())
.put("ea_id", player?.eaId.orEmpty())
StoreAccounts.write(context.applicationContext, Store.EA, record)
}
private fun fresh(a: Account) = a.expiresAt - System.currentTimeMillis() > REFRESH_MARGIN_MS || a.refreshToken.isEmpty()
private fun refreshLocked(context: Context, a: Account): String? {
if (a.refreshToken.isEmpty()) return null
val token = try {
tokenCall(listOf("grant_type" to "refresh_token", "refresh_token" to a.refreshToken))
} catch (e: Exception) {
Log.w(TAG, "refresh: ${e.message}")
return null
}
val access = token.getString("access_token")
val player = if (load(context)?.userId.isNullOrEmpty()) runCatching { EaApi.player(access) }.getOrNull() else null
return access.takeIf { storeRefreshed(context, access, token.optLong("expires_in", 3600), token.optString("refresh_token"), player) }
}
/** Writes a refreshed token into the saved sign-in, unless sign-out removed it meanwhile. */
internal fun storeRefreshed(context: Context, access: String, expiresIn: Long, refresh: String, player: EaApi.Player? = null): Boolean =
synchronized(refreshLock) {
val app = context.applicationContext
val record = StoreAccounts.read(app, Store.EA) ?: return false
record.put("access_token", access).put("expires_at", System.currentTimeMillis() + expiresIn * 1000)
refresh.takeIf { it.isNotEmpty() }?.let { record.put("refresh_token", it) }
player?.let { record.put("user_id", it.userId).put("persona_id", it.personaId).put("display_name", it.displayName).put("ea_id", it.eaId) }
StoreAccounts.write(app, Store.EA, record)
true
}
fun accessToken(context: Context): String? {
val current = load(context) ?: return null
if (fresh(current)) return current.accessToken
synchronized(refreshLock) {
val again = load(context) ?: return null
if (fresh(again)) return again.accessToken
return refreshLocked(context, again) ?: again.accessToken.takeIf { again.expiresAt > System.currentTimeMillis() }
}
}
fun refreshNow(context: Context, stale: String?): String? = synchronized(refreshLock) {
val current = load(context) ?: return null
if (stale != null && current.accessToken != stale) return current.accessToken
refreshLocked(context, current)
}
/** Asks EA to mint a code or token for another client from the signed-in session, as the EA app does for games. */
fun mint(
context: Context,
clientId: String,
responseType: String,
scopes: List<String> = emptyList(),
tokenFormat: String? = null,
expiresIn: Int? = null,
): String? {
val access = accessToken(context) ?: return null
val url = authUrl(deviceId(context), responseType, accessToken = access, clientId = clientId, scopes = scopes, tokenFormat = tokenFormat, expiresIn = expiresIn)
val reply = runCatching { EaHttp.request(url, follow = false) }.getOrElse {
Log.w(TAG, "mint $clientId: ${it.javaClass.simpleName}")
return null
}
val location = reply.header("Location") ?: run {
Log.w(TAG, "mint $clientId: no redirect (${reply.status})")
return null
}
if (location.startsWith("https://signin.ea.com")) {
Log.w(TAG, "mint $clientId: the session needs a new sign-in")
return null
}
return redirectValue(location, if (responseType == "token") "access_token" else responseType)
}
/** Waits for any refresh in progress, so it cannot write the sign-in back afterwards. */
fun signOut(context: Context) {
synchronized(refreshLock) { StoreAccounts.clear(context.applicationContext, Store.EA) }
}
}
@@ -0,0 +1,131 @@
package com.droiddeck.launcher.stores.ea
import android.content.Context
import android.content.Intent
import android.util.Log
import android.webkit.WebView
import androidx.compose.runtime.mutableStateMapOf
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.LoginFlows
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreBackend
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.WebCookies
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
object EaBackend : StoreBackend {
override val store: Store = Store.EA
@Volatile internal var app: Context? = null
init {
LoginFlows.eaFlow = { ua -> app?.let { EaLogin(EaAuth.begin(it), ua) } }
}
override fun signIn(context: Context) {
app = context.applicationContext
context.startActivity(
Intent(context, StoreLoginActivity::class.java)
.putExtra(StoreLoginActivity.EXTRA_STORE, store.id)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
override fun signOut(context: Context) {
val app = context.applicationContext
EaAuth.signOut(app)
EaLibrary.reset(app)
EaUpdates.available.clear()
runCatching { WebCookies.expire(EaLogin.SIGN_IN_URLS, ".ea.com", listOf("/")) {} }
}
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
this.app = app
Thread({ EaLibrary.sync(app, force) }, "ea-sync").start()
}
override fun loadShelves(context: Context, force: Boolean) {}
override fun install(context: Context, item: CatalogItem, root: java.io.File) {
val app = context.applicationContext
if (!EaNative.ready()) {
StoresState.logLine(EaNative.ENGINE_MISSING)
StoresState.post { StoresState.problems[store] = EaNative.ENGINE_MISSING }
return
}
val folder = StoreInstallRoot.folderFor(app, store, item.id, item.title, root)
val entry = DownloadEntry(store, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
DownloadQueue.enqueue(app, entry) { EaInstaller(app, item, folder) }
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
}
internal class EaLogin(private val pending: EaAuth.Pending, override val userAgent: String) : StoreLoginActivity.Flow {
override val startUrl: String get() = pending.url
override fun isRedirect(url: String): Boolean = url.startsWith("qrc:", ignoreCase = true)
override fun forgetSignIn(done: () -> Unit) {
runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() }
}
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
val code = EaAuth.redirectValue(url, "code") ?: return activity.getString(R.string.stores_login_error_verification)
return try {
EaAuth.exchange(activity, code, pending.verifier)
null
} catch (e: Exception) {
Log.w("EaLogin", "sign-in failed: ${e.message}")
activity.getString(R.string.stores_login_error_generic)
}
}
companion object {
val SIGN_IN_URLS = listOf("https://accounts.ea.com", "https://signin.ea.com", "https://www.ea.com")
}
}
object EaUpdates {
val available = mutableStateMapOf<String, String>()
private val checked = java.util.concurrent.ConcurrentHashMap<String, Long>()
private const val RECHECK_MS = 30 * 60 * 1000L
fun check(context: Context, game: InstalledStoreGame, force: Boolean = false) {
val app = context.applicationContext
val id = game.sidecar.id
val now = System.currentTimeMillis()
if (!force && now - (checked[id] ?: 0L) < RECHECK_MS) return
checked[id] = now
Thread({
val token = EaAuth.accessToken(app)
val offer = token?.let { runCatching { EaApi.offers(it, listOf(id)) }.getOrNull() }?.firstOrNull()
if (offer == null) {
checked.remove(id)
return@Thread
}
val live = offer.gameVersion
val installed = game.sidecar.installVersion
StoresState.post {
if (live.isNotEmpty() && installed.isNotEmpty() && live != installed) available[game.key] = live else available.remove(game.key)
}
}, "ea-update-check").start()
}
fun start(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
val root = game.folder.parentFile?.parentFile ?: return
val known = EaLibrary.game(app, game.sidecar.id)
val item = known?.let { EaLibrary.toCatalogItem(app, it) } ?: CatalogItem(
Store.EA, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover, owned = true, extra = game.sidecar.extra,
)
available.remove(game.key)
StoresState.install(app, item, root)
}
}
@@ -0,0 +1,83 @@
package com.droiddeck.launcher.stores.ea
import java.security.MessageDigest
import java.time.LocalDate
import java.time.ZoneOffset
import javax.crypto.Cipher
import javax.crypto.Mac
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
internal object EaCrypto {
val LSX_DEFAULT_KEY = ByteArray(16) { it.toByte() }
private val OOA_KEY = intArrayOf(65, 50, 114, 45, 208, 130, 239, 176, 220, 100, 87, 197, 118, 104, 202, 9)
.map { it.toByte() }.toByteArray()
private const val PRIME_10K = 104729L
private const val PRIME_20K = 224737L
private const val PRIME_30K = 350377L
fun ecbEncrypt(data: ByteArray, key: ByteArray): ByteArray =
Cipher.getInstance("AES/ECB/PKCS5Padding").run { init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES")); doFinal(data) }
fun ecbDecrypt(data: ByteArray, key: ByteArray): ByteArray =
Cipher.getInstance("AES/ECB/PKCS5Padding").run { init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES")); doFinal(data) }
fun licenseEncrypt(data: ByteArray): ByteArray =
Cipher.getInstance("AES/CBC/PKCS5Padding").run { init(Cipher.ENCRYPT_MODE, SecretKeySpec(OOA_KEY, "AES"), IvParameterSpec(ByteArray(16))); doFinal(data) }
fun licenseDecrypt(data: ByteArray): ByteArray =
Cipher.getInstance("AES/CBC/PKCS5Padding").run { init(Cipher.DECRYPT_MODE, SecretKeySpec(OOA_KEY, "AES"), IvParameterSpec(ByteArray(16))); doFinal(data) }
fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it.toInt() and 0xFF) }
fun unhex(text: String): ByteArray {
val digits = text.lowercase().filter { it in '0'..'9' || it in 'a'..'f' }
if (digits.length % 2 != 0) return ByteArray(0)
return ByteArray(digits.length / 2) { i -> digits.substring(i * 2, i * 2 + 2).toInt(16).toByte() }
}
/** The session key both sides derive after the LSX challenge, from a seed the game picks. */
fun lsxKey(seed: Int): ByteArray {
if (seed == 0) return LSX_DEFAULT_KEY.copyOf()
var state = 7L
fun next(): Int {
state = (state * 214013L + 2531011L) and 0xFFFFFFFFL
return ((state ushr 16) and 0xFFFF).toInt()
}
val start = (next().toLong() + seed) and 0xFFFFFFFFL
state = start
return ByteArray(16) { next().toByte() }
}
fun challengeAnswer(key: String): String = hex(ecbEncrypt(key.toByteArray(Charsets.US_ASCII), LSX_DEFAULT_KEY))
fun challengeSeed(version: String, answer: String): Int? = when (version) {
"2" -> 0
"3" -> (answer[0].code shl 8) or answer[1].code
else -> null
}
/** EA's launch handshake code, which changes every UTC day. */
fun rtpCode(day: LocalDate = LocalDate.now(ZoneOffset.UTC)): Long {
val time = ((PRIME_10K * day.year) xor (day.monthValue * PRIME_20K) xor (day.dayOfMonth * PRIME_30K)) and 0xFFFFFFFFL
return (time xor ((time shl 16) and 0xFFFFFFFFL) xor (time ushr 16)) and 0xFFFFFFFFL
}
fun sha256(data: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(data)
fun sha1(data: ByteArray): ByteArray = MessageDigest.getInstance("SHA-1").digest(data)
fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray =
Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(key, "HmacSHA256")); doFinal(data) }
fun fnv1a(data: ByteArray): ULong {
var hash = 0xcbf29ce484222325UL
for (b in data) hash = (hash xor (b.toUByte().toULong())) * 0x100000001b3UL
return hash
}
fun base64Url(data: ByteArray): String =
java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(data)
}
@@ -0,0 +1,47 @@
package com.droiddeck.launcher.stores.ea
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
internal class EaReply(val status: Int, val body: ByteArray, val headers: Map<String, List<String>>) {
val ok: Boolean get() = status in 200..299
val text: String get() = body.toString(Charsets.UTF_8)
fun header(name: String): String? = headers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value?.firstOrNull()
}
internal object EaHttp {
const val USER_AGENT = "Mozilla/5.0 EA Desktop/13.735.2.6250"
private const val TIMEOUT = 30_000
fun form(values: List<Pair<String, String>>): String =
values.joinToString("&") { (k, v) -> URLEncoder.encode(k, "UTF-8") + "=" + URLEncoder.encode(v, "UTF-8") }
fun request(
url: String,
method: String = "GET",
headers: Map<String, String> = emptyMap(),
body: ByteArray? = null,
follow: Boolean = true,
): EaReply {
val c = URL(url).openConnection() as HttpURLConnection
try {
c.requestMethod = method
c.connectTimeout = TIMEOUT
c.readTimeout = TIMEOUT
c.instanceFollowRedirects = follow
c.setRequestProperty("User-Agent", USER_AGENT)
for ((k, v) in headers) c.setRequestProperty(k, v)
if (body != null) {
c.doOutput = true
c.outputStream.use { it.write(body) }
}
val status = c.responseCode
val stream = if (status >= 400) c.errorStream else c.inputStream
val bytes = stream?.use { it.readBytes() } ?: ByteArray(0)
return EaReply(status, bytes, c.headerFields.filterKeys { it != null })
} finally {
c.disconnect()
}
}
}
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.stores.ea
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreExe
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.amazon.AmazonNative
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
internal class EaInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
override fun run(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_sync_sign_in))
var token = EaAuth.accessToken(app) ?: throw IllegalStateException("Not signed in to EA")
val url = try {
EaApi.downloadUrl(token, item.id)
} catch (e: EaApiException) {
if (e.status != 401) throw IllegalStateException(e.message)
token = EaAuth.refreshNow(app, token) ?: throw IllegalStateException("The EA sign-in has expired")
EaApi.downloadUrl(token, item.id)
}
val game = EaLibrary.game(app, item.id)
val version = runCatching { EaApi.offers(token, listOf(item.id)).firstOrNull()?.gameVersion }.getOrNull().orEmpty()
.ifEmpty { game?.version.orEmpty() }
val cover = item.tallImageUrl ?: item.imageUrl
StoreInstalls.begin(folder, Store.EA, item.id, item.title, cover, item.imageUrl)
if (cancelled.get()) return null
val tier = StoreDownloadTier.current(app)
handle.log("ea: \"${item.title}\" tier=${tier.id} window=${tier.networkWindow}")
val request = JSONObject()
.put("url", url)
.put("gameDir", folder.absolutePath)
.put("maxWorkers", tier.networkWindow.coerceIn(1, 64))
.put("processWorkers", tier.processWorkers)
.put("caBundle", "")
val shown = AtomicLong(-1)
val downloading = AtomicBoolean(false)
val listener = object : AmazonNative.InstallListener {
override fun onStatus(text: String) { handle.stage(DownloadStage.MANIFEST, text) }
override fun onCheck(doneBytes: Long, totalBytes: Long, files: Int, filesTotal: Int) {
handle.stage(DownloadStage.MANIFEST, "Checking files…")
handle.stageProgress(doneBytes, totalBytes, files, filesTotal, bytes = true)
}
override fun onSizes(pendingBytes: Long, totalBytes: Long) { handle.diskSize(totalBytes) }
override fun onProgress(done: Long, total: Long, files: Int, filesTotal: Int) {
if (downloading.compareAndSet(false, true)) handle.stage(DownloadStage.DOWNLOAD)
while (true) {
val before = shown.get()
if (done < before) return
if (shown.compareAndSet(before, done)) break
}
handle.progress(done, total, "Downloading ($files/$filesTotal files)")
}
override fun onLog(line: String) { handle.log("ea: $line") }
override fun beforeReplace(): Boolean = try {
StoreInstalls.markUpdating(folder)
true
} catch (e: Exception) {
handle.log("ea: the install record could not be switched to updating (${e.javaClass.simpleName})")
false
}
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) = Unit
}
val outcome = EaNative.install(request, listener, cancelled)
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "The EA install failed" })
val result = outcome.result ?: JSONObject()
result.optLong("totalBytes").takeIf { it > 0 }?.let { EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply() }
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
val sidecar = sidecarFor(app, item, folder, game, version, cover) { handle.log("ea: $it") }
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
return folder.path
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
}
companion object {
fun locale(context: Context, available: List<String>): String {
val wanted = StoreLanguage.localeFor(null, context)
val exact = "${wanted.language}_${wanted.country}"
return available.firstOrNull { it.equals(exact, true) }
?: available.firstOrNull { it.substringBefore('_').equals(wanted.language, true) }
?: available.firstOrNull { it.equals("en_US", true) }
?: "en_US"
}
internal fun sidecarFor(app: Context, item: CatalogItem, folder: File, game: EaGame?, version: String, cover: String?, log: (String) -> Unit): StoreGameSidecar {
val manifest = EaManifest.read(folder)
if (manifest == null) log("no installerdata.xml in ${folder.name}")
val launcher = manifest?.launcher()
val candidates = listOfNotNull(launcher?.path, game?.executePath?.takeIf { it.isNotEmpty() })
var exe = candidates.firstNotNullOfOrNull { EaPaths.relativeOnDisk(folder, EaPaths.relative(it)) }.orEmpty()
if (exe.isEmpty()) exe = StoreExe.pick(folder, null, item.title)
if (exe.isEmpty()) { log("no exe found; pick one in Steam settings › Added games"); exe = "game.exe" } else log("exe=$exe")
val args = EaPaths.splitArgs(listOf(game?.parameters.orEmpty(), launcher?.parameters.orEmpty()).filter { it.isNotBlank() }.joinToString(" "))
val keys = JSONArray()
listOfNotNull(game?.installCheck, game?.executePath, launcher?.path).mapNotNull { EaPaths.registered(it) }
.distinctBy { it.key.lowercase() + "|" + it.value.lowercase() }
.forEach { keys.put(JSONArray().put(it.key).put(it.value)) }
val extra = linkedMapOf(
"contentId" to (game?.contentId ?: item.extra["contentId"].orEmpty()),
"slug" to (game?.slug ?: item.extra["slug"].orEmpty()),
"multiplayerId" to game?.multiplayerId.orEmpty(),
"masterTitleId" to game?.masterTitleId.orEmpty(),
"locale" to locale(app, game?.locales.orEmpty()),
"registry" to keys.toString(),
"touchup" to manifest?.touchupPath.orEmpty().replace('\\', '/').trimStart('/'),
"touchupArgs" to manifest?.touchupParameters.orEmpty(),
"contentIds" to manifest?.contentIds.orEmpty().joinToString(","),
"displayName" to manifest?.title(locale(app, game?.locales.orEmpty())).orEmpty(),
).filterValues { it.isNotEmpty() }
return StoreGameSidecar(
Store.EA, item.id, item.title, exe = exe, args = args,
installVersion = version.ifEmpty { manifest?.version.orEmpty() }, installedAt = System.currentTimeMillis(),
cover = cover, hero = item.imageUrl, extra = extra, cloud = false, logo = item.logoUrl,
)
}
}
}
@@ -0,0 +1,138 @@
package com.droiddeck.launcher.stores.ea
import android.content.Context
import android.util.Base64
import android.util.Log
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.UUID
object EaLaunch {
private const val TAG = "EaLaunch"
const val ENV_FILE = ".droiddeck-ea-env"
private fun installed(context: Context, id: String): Pair<File, StoreGameSidecar>? =
StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull { f ->
StoreGameSidecar.read(f)?.takeIf { it.store == Store.EA && it.id == id && it.isInstalled }?.let { f to it }
}
internal fun environment(
offerId: String,
contentId: String,
locale: String,
generic: String,
access: String,
opaque: String,
account: EaAuth.Account,
session: String = UUID.randomUUID().toString(),
): LinkedHashMap<String, String> = linkedMapOf(
"EAAuthCode" to "unavailable",
"EAEgsProxyIpcPort" to "0",
"EAEntitlementSource" to "EA",
"EAExternalSource" to "EA",
"EAFreeTrialGame" to "false",
"EAGameLocale" to locale,
"EAGenericAuthToken" to generic,
"EALaunchCode" to "unavailable",
"EALaunchOwner" to "EA",
"EALaunchEAID" to account.eaId.ifEmpty { account.displayName },
"EALaunchEnv" to "production",
"EALaunchOfflineMode" to "false",
"EALsxPort" to EaLsx.PORT.toString(),
"EARtPLaunchCode" to EaCrypto.rtpCode().toString(),
"EASecureLaunchTokenTemp" to account.userId,
"EASteamProxyIpcPort" to "0",
"OriginSessionKey" to session,
"ContentId" to contentId,
"EAOnErrorExitRetCode" to "1",
"EAConnectionId" to offerId,
"EALicenseToken" to offerId,
"EALaunchUserAuthToken" to opaque,
"EAAccessTokenJWS" to access,
)
/** Adds what installs made before the manifest's content ids and title were recorded are missing. */
internal fun backfill(folder: File, sidecar: StoreGameSidecar): StoreGameSidecar {
if (sidecar.extra.containsKey("contentIds") || sidecar.extra.containsKey("displayName")) return sidecar
val manifest = EaManifest.read(folder) ?: return sidecar
val locale = sidecar.extra["locale"].orEmpty().ifEmpty { "en_US" }
val added = mapOf(
"contentIds" to manifest.contentIds.joinToString(","),
"displayName" to manifest.title(locale).orEmpty(),
).filterValues { it.isNotEmpty() }
if (added.isEmpty()) return sidecar
val updated = sidecar.copy(extra = sidecar.extra + added)
runCatching { updated.write(folder) }.onFailure { Log.w(TAG, "sidecar: ${it.javaClass.simpleName}") }
return updated
}
/** Answers the guest's request right before an EA game starts: session, licence and the LSX endpoint. */
fun prepare(context: Context, request: JSONObject): JSONObject {
val app = context.applicationContext
val id = request.optString("id")
val reply = JSONObject().put("ok", false)
val (folder, recorded) = installed(app, id) ?: return reply.put("reason", "not-installed")
val sidecar = backfill(folder, recorded)
runCatching { com.droiddeck.launcher.stores.StoreLaunch.refreshLauncher(folder, sidecar) }
File(folder, ENV_FILE).delete()
val account = EaAuth.load(app) ?: return reply.put("reason", "signed-out")
val access = EaAuth.accessToken(app) ?: return reply.put("reason", "sign-in-expired")
val contentId = sidecar.extra["contentId"].orEmpty()
val locale = sidecar.extra["locale"].orEmpty().ifEmpty { "en_US" }
val core = EaOoa.coreDir(folder, sidecar.exe)
val hashVersion = core?.let(EaOoa::activationVersion) ?: 1
val hardware = request.optJSONObject("hardware")?.let(EaOoa.Hardware::fromJson)?.takeIf { it.complete(hashVersion) }
val legacy = EaOoa.legacyCore(core)
val lifetime = if (legacy) 14400 else 550
val opaque = EaAuth.mint(app, EaAuth.CLIENT_ID, "token", EaAuth.OPAQUE_SCOPES, "OPAQUE", lifetime).orEmpty()
val known = (sidecar.extra["contentIds"].orEmpty().split(',') + sidecar.extra["multiplayerId"].orEmpty()).map { it.trim() }.filter { it.isNotEmpty() }.toSet()
val lsx = EaLsx.start(app, EaLsx.Game(id, contentId, sidecar.title, sidecar.installVersion, locale, hardware, hashVersion, opaque,
System.currentTimeMillis() + (lifetime - 30) * 1000L, known))
val env = environment(id, contentId, locale, if (legacy && opaque.isNotEmpty()) opaque else access, access, opaque, EaAuth.load(app) ?: account)
val tmp = File(folder, "$ENV_FILE.tmp")
tmp.writeText(env.entries.joinToString("\r\n", postfix = "\r\n") { "${it.key}=${it.value}" })
tmp.renameTo(File(folder, ENV_FILE))
val licenses = JSONArray()
val notes = ArrayList<String>()
if (core != null) {
val ids = (listOf(contentId) + sidecar.extra["contentIds"].orEmpty().split(',')).map { it.trim() }.filter { it.isNotEmpty() }.distinct()
if (hardware == null) notes += "no-hardware" else {
val hash = EaOoa.machineHash(hardware, hashVersion)
for (content in ids) {
notes += try {
for ((path, data) in EaOoa.files(core, EaOoa.request(access, content, hash))) {
licenses.put(JSONObject().put("path", path).put("data", Base64.encodeToString(data, Base64.NO_WRAP)))
}
"$content:ok"
} catch (e: Exception) {
Log.w(TAG, "licence $content for $id: ${e.message}")
com.droiddeck.launcher.stores.StoresState.logLine("ea licence $content for $id v$hashVersion legacy=$legacy: ${e.message}")
"$content:refused"
}
}
}
}
if (core != null && notes.isNotEmpty() && notes.none { it.endsWith(":ok") }) runCatching {
val rows = EaApi.legacyEntitlements(access).filter { it.optString("productId") == id }
val types = rows.joinToString(",") { it.optString("entitlementType") + "/" + it.optString("entitlementTag") + "/" + it.optString("status") }
com.droiddeck.launcher.stores.StoresState.logLine("ea $id has no licence; entitlements: ${types.ifEmpty { "none" }}")
}
val licenseNote = if (core == null) "none-needed" else "v$hashVersion " + notes.joinToString(",")
Log.i(TAG, "prepared $id lsx=$lsx legacy=$legacy opaque=${opaque.isNotEmpty()} licence=$licenseNote")
return reply.put("ok", true).put("lsx", lsx).put("license", licenseNote).put("licenses", licenses)
}
}
object EaSizes {
fun size(context: Context, item: com.droiddeck.launcher.stores.CatalogItem): Long {
val token = EaAuth.accessToken(context) ?: return 0L
val url = runCatching { EaApi.downloadUrl(token, item.id) }.getOrNull() ?: return 0L
return EaNative.call("zip.size", JSONObject().put("url", url))?.optLong("totalBytes") ?: 0L
}
}
@@ -0,0 +1,293 @@
package com.droiddeck.launcher.stores.ea
import android.content.Context
import android.content.SharedPreferences
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.StoreShelves
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.mergeItems
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object EaPrefs {
const val FILE = "stores.ea"
fun get(context: Context): SharedPreferences = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
}
data class EaGame(
val offerId: String,
val contentId: String,
val title: String,
val slug: String,
val tall: String = "",
val wide: String = "",
val logo: String = "",
val version: String = "",
val executePath: String = "",
val installCheck: String = "",
val parameters: String = "",
val multiplayerId: String = "",
val masterTitleId: String = "",
val cloudSaves: String = "",
val locales: List<String> = emptyList(),
) {
fun toJson(): JSONObject = JSONObject()
.put("offerId", offerId).put("contentId", contentId).put("title", title).put("slug", slug)
.put("tall", tall).put("wide", wide).put("logo", logo).put("version", version)
.put("executePath", executePath).put("installCheck", installCheck).put("parameters", parameters)
.put("multiplayerId", multiplayerId).put("masterTitleId", masterTitleId).put("cloudSaves", cloudSaves)
.put("locales", JSONArray(locales))
companion object {
fun fromJson(o: JSONObject): EaGame? {
val locales = o.optJSONArray("locales")
return EaGame(
offerId = o.optString("offerId").ifEmpty { return null },
contentId = o.optString("contentId"),
title = o.optString("title"),
slug = o.optString("slug"),
tall = o.optString("tall"),
wide = o.optString("wide"),
logo = o.optString("logo"),
version = o.optString("version"),
executePath = o.optString("executePath"),
installCheck = o.optString("installCheck"),
parameters = o.optString("parameters"),
multiplayerId = o.optString("multiplayerId"),
masterTitleId = o.optString("masterTitleId"),
cloudSaves = o.optString("cloudSaves"),
locales = (0 until (locales?.length() ?: 0)).map { locales!!.optString(it) },
)
}
}
}
object EaLibrary {
private const val KEY_CACHE = "library_cache"
private const val KEY_SYNCED_AT = "library_synced_at"
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
private const val ART_TTL_MS = 7 * 24 * 60 * 60 * 1000L
private const val ART_THREADS = 4
const val STORE_URL = "https://www.ea.com/ea-app/library"
private val gate = SyncGate()
private val generation = java.util.concurrent.atomic.AtomicInteger()
/** Drops the cache and makes any sync already running drop its results, in one step. */
fun reset(context: Context) {
synchronized(cacheLock) {
generation.incrementAndGet()
EaPrefs.get(context).edit().remove(KEY_CACHE).remove(KEY_SYNCED_AT).commit()
}
}
internal fun snapshot(app: Context): Pair<Int, List<EaGame>> = synchronized(cacheLock) { generation.get() to cached(app) }
internal fun storeCache(app: Context, games: List<EaGame>, gen: Int): Boolean = synchronized(cacheLock) {
gen == generation.get() &&
EaPrefs.get(app).edit().putString(KEY_CACHE, JSONArray(games.map { it.toJson() }).toString()).putLong(KEY_SYNCED_AT, System.currentTimeMillis()).commit()
}
private val cacheLock = Any()
private val store = Store.EA
fun cached(context: Context): List<EaGame> {
val text = EaPrefs.get(context).getString(KEY_CACHE, null) ?: return emptyList()
val arr = runCatching { JSONArray(text) }.getOrNull() ?: return emptyList()
return (0 until arr.length()).mapNotNull { arr.optJSONObject(it)?.let(EaGame::fromJson) }
}
fun game(context: Context, offerId: String): EaGame? = cached(context).firstOrNull { it.offerId == offerId }
fun toCatalogItem(context: Context, g: EaGame): CatalogItem {
val prefs = EaPrefs.get(context)
val tall = g.tall.ifEmpty { prefs.getString("poster_${g.offerId}", null).orEmpty() }
return CatalogItem(
store = store,
id = g.offerId,
title = g.title.ifBlank { g.slug },
imageUrl = g.wide.ifEmpty { tall }.ifEmpty { null },
tallImageUrl = tall.ifEmpty { g.wide }.ifEmpty { null },
publisher = "Electronic Arts",
owned = true,
sizeBytes = prefs.getLong("size_${g.offerId}", 0L),
storeUrl = STORE_URL,
extra = mapOf("contentId" to g.contentId, "slug" to g.slug, "version" to g.version),
logoUrl = g.logo.ifEmpty { null },
)
}
/** One entry per game: owned editions of the same base game collapse onto the base offer. */
internal fun pick(owned: List<EaApi.OwnedProduct>, offers: Map<String, EaApi.Offer>): List<Pair<EaApi.OwnedProduct, EaApi.Offer>> {
val usable = owned.filter { o ->
val offer = offers[o.offerId] ?: return@filter false
!o.trial && o.downloadable && offer.downloadable &&
(offer.displayType.isEmpty() || offer.displayType.equals("FullGame", true)) &&
(o.gameType.isEmpty() || o.gameType.equals("BASE_GAME", true))
}
return usable.groupBy { it.baseSlug.ifEmpty { it.slug }.ifEmpty { it.offerId } }.values.map { group ->
val chosen = group.firstOrNull { it.baseSlug.isEmpty() } ?: group.first()
chosen to offers.getValue(chosen.offerId)
}.sortedBy { it.first.name.lowercase() }
}
private fun art(app: Context, token: String, slugs: Collection<String>, gen: Int): Map<String, EaApi.Images> {
val prefs = EaPrefs.get(app)
val now = System.currentTimeMillis()
val out = java.util.concurrent.ConcurrentHashMap<String, EaApi.Images>()
val pool = Executors.newFixedThreadPool(ART_THREADS)
try {
for (slug in slugs.filter { it.isNotEmpty() }) {
if (gen != generation.get()) break
val cached = prefs.getString("art_$slug", null)?.let { runCatching { JSONObject(it) }.getOrNull() }
if (cached != null && now - cached.optLong("at") < ART_TTL_MS) {
out[slug] = EaApi.Images(cached.optString("tall").ifEmpty { null }, cached.optString("wide").ifEmpty { null }, cached.optString("logo").ifEmpty { null })
continue
}
pool.execute {
if (gen != generation.get()) return@execute
val images = runCatching { EaApi.images(token, slug) }.getOrNull() ?: return@execute
out[slug] = images
prefs.edit().putString(
"art_$slug",
JSONObject().put("at", now).put("tall", images.tall.orEmpty()).put("wide", images.wide.orEmpty()).put("logo", images.logo.orEmpty()).toString(),
).apply()
}
}
} finally {
pool.shutdown()
pool.awaitTermination(2, TimeUnit.MINUTES)
}
return out
}
private fun posters(app: Context, games: List<EaGame>, gen: Int) {
val prefs = EaPrefs.get(app)
val todo = games.filter { it.tall.isEmpty() && !prefs.contains("poster_${it.offerId}") }.take(40)
if (todo.isEmpty()) return
val pool = Executors.newFixedThreadPool(ART_THREADS)
try {
for (g in todo) pool.execute {
if (gen != generation.get()) return@execute
prefs.edit().putString("poster_${g.offerId}", runCatching { StoreNet.sgdbPoster(g.title) }.getOrDefault("")).apply()
}
} finally {
pool.shutdown()
pool.awaitTermination(5, TimeUnit.MINUTES)
}
}
private fun publish(app: Context, games: List<EaGame>, gen: Int = generation.get()) {
if (gen != generation.get()) return
val items = games.map { toCatalogItem(app, it) }
StoresState.post {
if (gen != generation.get()) return@post
StoresState.library[store] = mergeItems(StoresState.library[store], items)
val installed = StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id }.toSet()
StoresState.shelves[store] = StoreShelves(trending = items.filterNot { it.id in installed }, art = StoresState.shelves[store]?.art.orEmpty())
}
}
private inline fun <T> withToken(app: Context, token: String, call: (String) -> T): T = try {
call(token)
} catch (e: EaApiException) {
if (e.status != 401) throw e
call(EaAuth.refreshNow(app, token) ?: throw e)
}
fun sync(context: Context, force: Boolean) {
if (!gate.enter()) return
var forced = force
do {
runCatching { syncOnce(context.applicationContext, forced) }
forced = true
} while (gate.leave())
}
private fun syncOnce(app: Context, force: Boolean) {
val (gen, cache) = snapshot(app)
val prefs = EaPrefs.get(app)
val quiet = cache.isNotEmpty() && !force
fun status(id: Int) { if (!quiet) StoresState.post { StoresState.status[store] = app.getString(id) } }
fun problem(text: String?) {
StoresState.post {
StoresState.status.remove(store)
if (text == null) StoresState.problems.remove(store) else StoresState.problems[store] = text
}
}
try {
if (cache.isNotEmpty()) publish(app, cache, gen)
if (!force && cache.isNotEmpty() && System.currentTimeMillis() - prefs.getLong(KEY_SYNCED_AT, 0L) in 0 until THROTTLE_MS) {
return problem(null)
}
status(R.string.stores_sync_sign_in)
val token = EaAuth.accessToken(app) ?: return problem(StoresState.notSignedInLine(store))
status(R.string.stores_sync_game_list)
val owned = withToken(app, token) { EaApi.owned(it) }
val offers = withToken(app, token) { EaApi.offers(it, owned.map { o -> o.offerId }) }.associateBy { it.offerId }
val picked = pick(owned, offers)
StoresState.logLine("ea: ${owned.size} owned products, ${picked.size} games")
for ((o, offer) in picked) StoresState.logLine(
"ea: owned ${o.offerId} content=${offer.contentId} master=${offer.masterTitleId} mp=${offer.multiplayerId} via=${o.ownership.joinToString("+")} type=${o.gameType}")
if (picked.isEmpty()) return problem(if (cache.isEmpty()) app.getString(R.string.stores_sync_no_games, store.label) else null)
if (gen != generation.get()) return
status(R.string.stores_sync_cover_art)
val images = art(app, token, picked.map { it.first.slug }, gen)
val games = picked.map { (o, offer) ->
val img = images[o.slug]
EaGame(
offerId = o.offerId, contentId = offer.contentId, title = o.name.ifBlank { offer.displayName }, slug = o.slug,
tall = img?.tall.orEmpty(), wide = img?.wide.orEmpty(), logo = img?.logo.orEmpty(), version = offer.gameVersion,
executePath = offer.executePathOverride, installCheck = offer.installCheckOverride, parameters = offer.executeParameters,
multiplayerId = offer.multiplayerId, masterTitleId = offer.masterTitleId, cloudSaves = offer.cloudSaves, locales = offer.locales,
)
}
if (!storeCache(app, games, gen)) return
posters(app, games, gen)
if (gen != generation.get()) return
publish(app, games, gen)
problem(null)
} catch (e: EaApiException) {
StoresState.logLine("ea: library sync failed: ${e.message}")
if (e.status == 401) StoresState.markSignInExpired(store)
problem(if (cache.isEmpty()) e.message else null)
} catch (e: Exception) {
StoresState.logLine("ea: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty()}")
problem(if (cache.isEmpty()) e.message ?: app.getString(R.string.stores_sync_failed) else null)
}
}
}
/** One sync at a time; a request made meanwhile makes the running one go round again rather than being lost. */
internal class SyncGate {
private var busy = false
private var again = false
/** True when the caller should run; false when a running sync will pick the request up. */
@Synchronized
fun enter(): Boolean {
if (busy) {
again = true
return false
}
busy = true
return true
}
/** True when another round was requested while running; the caller stays the runner. */
@Synchronized
fun leave(): Boolean {
if (again) {
again = false
return true
}
busy = false
return false
}
}
@@ -0,0 +1,446 @@
package com.droiddeck.launcher.stores.ea
import android.content.Context
import android.util.Log
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.ByteArrayOutputStream
import java.io.OutputStream
import java.io.StringReader
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
/**
* The local SDK endpoint EA games talk to in place of the EA app (LSX: XML over TCP, AES after a
* challenge). It answers for the one game DroidDeck last prepared.
*/
object EaLsx {
private const val TAG = "EaLsx"
const val PORT = 3216
private const val SENDER = "EALS"
private const val CHALLENGE_KEY = "cacf897a20b6d612ad0c05e011df52bb"
private const val CHALLENGE_VERSION = "10,5,30,15625"
private const val LANGUAGES = "ar_SA,de_DE,en_US,es_ES,es_MX,fr_FR,it_IT,ja_JP,ko_KR,pl_PL,pt_BR,ru_RU,zh_CN,zh_TW"
private val SERVICES = listOf(
"EbisuSDK" to "SDK", "EbisuSDK" to "PROFILE", "XMPP" to "PRESENCE", "XMPP" to "FRIENDS", "Commerce" to "COMMERCE",
"EbisuSDK" to "RECENTPLAYER", "EbisuSDK" to "IGO", "EbisuSDK" to "MISC", "EALS" to "LOGIN", "EbisuSDK" to "UTILITY",
"XMPP" to "XMPP", "XMPP" to "CHAT", "EbisuSDK" to "IGO_EVENT", "EALS" to "EALS_EVENTS", "EbisuSDK" to "LOGIN_EVENT",
"XMPP" to "INVITE_EVENT", "EbisuSDK" to "PROFILE_EVENT", "XMPP" to "PRESENCE_EVENT", "XMPP" to "FRIENDS_EVENT",
"Commerce" to "COMMERCE_EVENT", "XMPP" to "CHAT_EVENT", "EbisuSDK" to "DOWNLOAD_EVENT", "EbisuSDK" to "PERMISSION",
"EbisuSDK" to "RESOURCES", "EbisuSDK" to "BLOCKED_USERS", "EbisuSDK" to "BLOCKED_USER_EVENT", "EbisuSDK" to "GET_USERID",
"EbisuSDK" to "ONLINE_STATUS_EVENT", "EbisuSDK" to "ACHIEVEMENT", "EbisuSDK" to "ACHIEVEMENT_EVENT",
"EbisuSDK" to "BROADCAST_EVENT", "PI" to "PROGRESSIVE_INSTALLATION", "PI" to "PROGRESSIVE_INSTALLATION_EVENT",
"EbisuSDK" to "CONTENT",
)
class Game(
val offerId: String,
val contentId: String,
val title: String,
val version: String,
val locale: String,
val hardware: EaOoa.Hardware?,
val hashVersion: Int,
val token: String = "",
val tokenExpiresAt: Long = 0L,
val contentIds: Set<String> = emptySet(),
) {
val validToken: String? get() = token.takeIf { it.isNotEmpty() && System.currentTimeMillis() < tokenExpiresAt }
}
/** The parts of a request a reply depends on. */
class Message(val recipient: String, val id: String, val name: String, val attrs: Map<String, String>, val children: List<Pair<String, String>>)
interface Account {
val userId: String
val personaId: String
val persona: String
fun authCode(clientId: String, scope: String?): String?
fun license(contentId: String, requestTicket: String, ticketEngine: String): String?
fun entitlements(group: String): List<Map<String, String>>
fun token(): String?
}
@Volatile var game: Game? = null
@Volatile private var account: Account? = null
/** The one session of the current launch that may act for the account. */
/** Bumped whenever the launch changes; a connection accepted under an older one is not admitted. */
@Volatile internal var generation = 0
private val holder = java.util.concurrent.atomic.AtomicReference<Any?>(null)
private var server: ServerSocket? = null
private val lock = Any()
private const val MAX_CLIENTS = 8
private val WHITESPACE = Regex("[ \t]+")
fun start(context: Context, game: Game): Boolean {
synchronized(lock) {
closeSessions()
this.game = game
account = AppAccount(context.applicationContext)
runCatching { server?.close() }
return try {
val socket = ServerSocket().apply {
reuseAddress = true
bind(java.net.InetSocketAddress(InetAddress.getByName("127.0.0.1"), PORT), 8)
}
server = socket
Thread({ accept(socket) }, "ea-lsx").apply { isDaemon = true }.start()
Log.i(TAG, "listening on $PORT")
true
} catch (e: Exception) {
Log.w(TAG, "could not listen on $PORT: ${e.javaClass.simpleName}")
false
}
}
}
/** Ends the endpoint; with [offerId], only if it still serves that game, so a late exit cannot stop a newer launch. */
fun stop(offerId: String? = null) {
synchronized(lock) {
if (offerId != null && game?.offerId != offerId) return
runCatching { server?.close() }
server = null
game = null
account = null
closeSessions()
}
}
private fun closeSessions() {
generation++
holder.set(null)
synchronized(sessions) { sessions.forEach { it.trusted = false } }
for (socket in open) runCatching { socket.close() }
open.clear()
}
private val open = java.util.Collections.newSetFromMap(java.util.concurrent.ConcurrentHashMap<Socket, Boolean>())
private const val HANDSHAKE_TIMEOUT_MS = 15_000
private const val UNTRUSTED_IDLE_MS = 10 * 60 * 1000
private fun accept(socket: ServerSocket) {
while (!socket.isClosed) {
val client = runCatching { socket.accept() }.getOrNull() ?: continue
val (owner, unreadable) = ownerUid(client)
val verified = owner?.let { it == android.os.Process.myUid() }
if (verified == false) {
Log.w(TAG, "refused a connection from another app")
runCatching { client.close() }
continue
}
if (unreadable != null) note("peer cannot be identified: $unreadable")
val session = runCatching { Session(client, client.getOutputStream(), verified == true, unreadable != null) }.getOrNull()
val live = session != null && synchronized(lock) { server === socket && admit(session).also { if (it) open += client } }
if (!live) {
runCatching { client.close() }
continue
}
Thread({ try { serve(client, session!!) } finally { synchronized(sessions) { sessions -= session!! }; open -= client } }, "ea-lsx-client").apply { isDaemon = true }.start()
}
}
/**
* The uid owning the connecting socket, or null where SELinux hides /proc/net. The guest runs
* under this app's uid, so any other uid is another app; an unknown owner never gets credentials.
*/
/** The connecting socket's uid, or why Android hid socket ownership from this app (some builds deny /proc/net). */
private fun ownerUid(client: Socket): Pair<Int?, String?> {
val port = client.port
var denied: String? = null
var read = false
for (path in listOf("/proc/net/tcp6", "/proc/net/tcp")) {
val lines = runCatching { java.io.File(path).readLines() }.onFailure { denied = "$path ${it.javaClass.simpleName}" }.getOrNull() ?: continue
read = true
owner(lines, port)?.let { return it to null }
}
return null to if (read) null else denied ?: "no socket table"
}
internal fun owner(lines: List<String>, port: Int): Int? = lines.drop(1).firstNotNullOfOrNull { line ->
val f = line.trim().split(WHITESPACE)
val local = f.getOrNull(1)?.substringAfterLast(':')?.toIntOrNull(16)
val remote = f.getOrNull(2)?.substringAfterLast(':')?.toIntOrNull(16)
if (local == port && remote == PORT) f.getOrNull(7)?.toIntOrNull() else null
}
/**
* Adds [session] unless the cap is reached by sessions that cannot be replaced; otherwise the
* oldest session that never claimed the prepared game (then the oldest untrusted one) makes room.
* Counting and eviction share one lock, so the live total never passes the cap.
*/
internal fun admit(session: Session): Boolean = synchronized(sessions) {
if (sessions.count { !it.evicted } >= MAX_CLIENTS) {
val candidates = sessions.filter { !it.trusted && !it.evicted }
val victim = candidates.firstOrNull { !it.claimed } ?: candidates.firstOrNull() ?: return false
victim.evicted = true
runCatching { victim.socket.close() }
}
sessions += session
true
}
internal val sessions = LinkedHashSet<Session>()
/** Trust and eviction exclude each other: an evicted session never becomes trusted, a trusted one is never evicted. */
internal fun promote(session: Session, matches: Boolean) {
synchronized(sessions) { session.trusted = matches && !session.evicted && session.born == generation && holder.compareAndSet(null, session) }
}
internal class Session(val socket: Socket, val output: OutputStream, val verified: Boolean, val unverifiable: Boolean = false) {
val born = generation
val connectedAt = System.currentTimeMillis()
@Volatile var evicted = false
@Volatile var claimed = false
var key: ByteArray? = null
@Volatile var trusted = false
var pending: ByteArray? = null
/** A peer Android names as another app never gets account data; one Android cannot name is judged by its claim alone. */
val mayTrust get() = (verified || unverifiable) && claimed
@Synchronized
fun send(xml: String) {
val key = this.key
val text = if (key == null) xml else EaCrypto.hex(EaCrypto.ecbEncrypt(xml.toByteArray(), key))
output.write(text.toByteArray())
output.write(0)
output.flush()
}
}
private fun note(line: String) = com.droiddeck.launcher.stores.StoresState.logLine("ea lsx: $line")
private fun serve(client: Socket, session: Session) {
client.tcpNoDelay = true
client.soTimeout = HANDSHAKE_TIMEOUT_MS
val seen = LinkedHashSet<String>()
var why = "closed by the game"
note("game connected")
try {
session.send("<LSX><Event sender=\"$SENDER\"><Challenge build=\"release\" key=\"$CHALLENGE_KEY\" version=\"$CHALLENGE_VERSION\"/></Event></LSX>")
val input = client.getInputStream()
val pending = ByteArrayOutputStream()
val chunk = ByteArray(16 * 1024)
while (true) {
if (session.key == null) {
val left = session.connectedAt + HANDSHAKE_TIMEOUT_MS - System.currentTimeMillis()
if (left <= 0) throw java.net.SocketTimeoutException()
client.soTimeout = left.toInt()
}
val n = input.read(chunk)
if (n < 0) break
pending.write(chunk, 0, n)
for (frame in frames(pending, session.key)) {
for (one in Regex("<LSX>.*?</LSX>", RegexOption.DOT_MATCHES_ALL).findAll(frame)) {
val message = parse(one.value) ?: continue
if (seen.add(message.name)) note("request ${message.name}")
val reply = runCatching { answer(session, message) }
.onFailure { note("${message.name} failed: ${it.javaClass.simpleName}") }.getOrNull()
if (reply != null) session.send("<LSX><Response sender=\"${esc(message.recipient)}\" id=\"${esc(message.id)}\">$reply</Response></LSX>")
session.pending?.let { session.key = it; session.pending = null }
if (session.key != null) {
val idle = if (session.trusted) 0 else UNTRUSTED_IDLE_MS
if (client.soTimeout != idle) client.soTimeout = idle
}
}
}
if (pending.size() > 4 * 1024 * 1024) { why = "message too large"; break }
}
} catch (e: java.net.SocketTimeoutException) {
why = "no trusted handshake in time"
} catch (e: Exception) {
why = e.javaClass.simpleName
} finally {
holder.compareAndSet(session, null)
note("game disconnected ($why)")
runCatching { client.close() }
}
}
/**
* Complete messages in what has arrived so far. Messages normally end in a NUL; one that does
* not counts once it holds a whole `<LSX>` element, plain or decrypted.
*/
private fun frames(pending: ByteArrayOutputStream, key: ByteArray?): List<String> {
val bytes = pending.toByteArray()
val out = ArrayList<String>()
var start = 0
for (i in bytes.indices) {
if (bytes[i].toInt() != 0) continue
if (i > start) decode(String(bytes, start, i - start, Charsets.UTF_8), key)?.let(out::add)
start = i + 1
}
var rest = String(bytes, start, bytes.size - start, Charsets.UTF_8)
if (rest.isNotBlank()) decode(rest, key)?.takeIf { it.contains("</LSX>") }?.let { out += it; rest = "" }
pending.reset()
pending.write(rest.toByteArray(Charsets.UTF_8))
return out
}
private fun decode(frame: String, key: ByteArray?): String? {
val text = frame.trim()
if (text.isEmpty()) return null
if (text.startsWith("<")) return text
val k = key ?: return null
return runCatching { String(EaCrypto.ecbDecrypt(EaCrypto.unhex(text), k)) }.getOrNull()
}
internal fun parse(xml: String): Message? = runCatching {
val parser = XmlPullParserFactory.newInstance().newPullParser()
parser.setInput(StringReader(xml))
var recipient = ""
var id = ""
var name = ""
val attrs = HashMap<String, String>()
val children = ArrayList<Pair<String, String>>()
var depth = 0
var child = ""
while (parser.eventType != XmlPullParser.END_DOCUMENT) {
when (parser.eventType) {
XmlPullParser.START_TAG -> {
depth++
when (depth) {
2 -> if (parser.name == "Request") {
recipient = parser.getAttributeValue(null, "recipient").orEmpty()
id = parser.getAttributeValue(null, "id").orEmpty()
} else return@runCatching null
3 -> {
name = parser.name
for (i in 0 until parser.attributeCount) attrs[parser.getAttributeName(i)] = parser.getAttributeValue(i)
}
4 -> child = parser.name
}
}
XmlPullParser.TEXT -> if (depth == 4) children += child to parser.text.trim()
XmlPullParser.END_TAG -> depth--
}
parser.next()
}
if (name.isEmpty()) null else Message(recipient, id, name, attrs, children)
}.getOrNull()
private fun esc(s: String) = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
private fun tag(name: String, vararg attrs: Pair<String, Any?>, body: String? = null): String {
val a = attrs.filter { it.second != null }.joinToString("") { " ${it.first}=\"${esc(it.second.toString())}\"" }
return if (body == null) "<$name$a/>" else "<$name$a>$body</$name>"
}
private fun now() = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
private fun answer(session: Session, m: Message): String? {
val g = game
val who = account
val person = who?.takeIf { session.trusted }
val locale = g?.locale ?: "en_US"
return when (m.name) {
"ChallengeResponse" -> {
val answer = EaCrypto.challengeAnswer(m.attrs["key"].orEmpty())
val version = m.attrs["version"].orEmpty()
val seed = EaCrypto.challengeSeed(version, answer) ?: 0
val content = m.children.firstOrNull { it.first == "ContentId" }?.second.orEmpty()
session.claimed = g != null && content.isNotEmpty() && (content == g.contentId || content == g.offerId || content in g.contentIds)
val matches = session.mayTrust
promote(session, matches)
note("challenge version '$version' content '$content' ${when { session.trusted -> "matches the prepared game"; matches -> "matches, but another session holds this launch"; !session.verified && !session.unverifiable -> "comes from an unverified peer"; else -> "does not match the prepared game" }}")
session.pending = EaCrypto.lsxKey(seed)
Log.i(TAG, "game connected: ${m.children.firstOrNull { it.first == "Title" }?.second.orEmpty()}")
tag("ChallengeAccepted", "response" to answer)
}
"GetConfig" -> tag("GetConfigResponse", body = SERVICES.joinToString("") { tag("Service", "Name" to it.first, "Facility" to it.second) })
"GetProfile" -> tag(
"GetProfileResponse",
"Persona" to person?.persona.orEmpty(), "SubscriberLevel" to 0, "CommerceCurrency" to "USD", "IsTrialSubscriber" to false,
"Country" to "US", "UserId" to person?.userId.orEmpty(), "GeoCountry" to "US", "AvatarId" to "", "IsSubscriber" to false,
"IsSteamSubscriber" to false, "PersonaId" to person?.personaId.orEmpty(), "IsUnderAge" to false, "UserIndex" to 0,
)
"GetSetting" -> tag("GetSettingResponse", "Setting" to when (m.attrs["SettingId"]) {
"ENVIRONMENT" -> "production"
"LANGUAGE" -> locale
else -> "false"
})
"GetGameInfo" -> tag("GetGameInfoResponse", "GameInfo" to when (m.attrs["GameInfoId"]) {
"FREETRIAL" -> "false"
"LANGUAGES" -> LANGUAGES
"INSTALLED_LANGUAGE" -> locale
"INSTALLED_VERSION", "AVAILABLE_VERSION" -> g?.version.orEmpty()
else -> ""
})
"GetAllGameInfo" -> tag(
"GetAllGameInfoResponse",
"FullGamePurchased" to true, "FullGameReleased" to true, "InstalledVersion" to (g?.version ?: "0"), "MaxGroupSize" to 16,
"Languages" to LANGUAGES, "Expiration" to "0000-00-00T00:00:00", "UpToDate" to true, "HasExpiration" to false,
"EntitlementSource" to "EA", "AvailableVersion" to (g?.version ?: "0"), "DisplayName" to g?.title.orEmpty(),
"FreeTrial" to false, "InstalledLanguage" to locale, "FullGameReleaseDate" to "2000-01-01T00:00:00", "SystemTime" to now(),
)
"GetInternetConnectedState" -> tag("InternetConnectedState", "connected" to 1)
"IsProgressiveInstallationAvailable" -> tag("IsProgressiveInstallationAvailableResponse", "ItemId" to m.attrs["ItemId"].orEmpty(), "Available" to false)
"AreChunksInstalled" -> tag(
"AreChunksInstalledResponse", "ItemId" to m.attrs["ItemId"].orEmpty(), "Installed" to true,
body = m.children.joinToString("") { tag(it.first, body = esc(it.second)) },
)
"GetAuthCode" -> tag("AuthCode", "value" to (who?.takeIf { session.trusted }?.authCode(m.attrs["ClientId"].orEmpty(), m.attrs["Scope"])?.takeIf { session.trusted } ?: "invalid"))
"GetAuthToken" -> tag("AuthToken", "value" to if (!session.trusted) "" else (g?.validToken ?: who?.token().orEmpty()))
"RequestLicense" -> {
val token = who?.takeIf { session.trusted }?.license(g?.contentId.orEmpty(), m.attrs["RequestTicket"].orEmpty(), m.attrs["TicketEngine"].orEmpty())?.takeIf { session.trusted }.orEmpty()
tag("RequestLicenseResponse", "License" to token)
}
"QueryEntitlements" -> {
val group = m.attrs["Group"].orEmpty()
val rows = who?.takeIf { session.trusted }?.entitlements(group).orEmpty()
tag("QueryEntitlementsResponse", body = rows.joinToString("") { e ->
tag(
"Entitlement",
"LastModifiedDate" to "0000-00-00T00:00:00", "EntitlementId" to e["id"], "UseCount" to (e["useCount"] ?: "0"),
"Version" to (e["version"] ?: "0"), "ItemId" to e["productId"], "ResourceId" to "", "GrantDate" to e["grantDate"],
"Group" to group, "EntitlementTag" to e["entitlementTag"], "Type" to e["entitlementType"],
"Expiration" to (e["terminationDate"]?.takeIf { it.isNotEmpty() && it != "null" } ?: "0000-00-00T00:00:00"), "Source" to "",
)
})
}
"GetPresence" -> tag("GetPresenceResponse", "UserId" to person?.userId.orEmpty(), "Presence" to "INGAME")
"QueryPresence" -> tag("QueryPresenceResponse", body = "")
"QueryFriends" -> tag("QueryFriendsResponse", body = "")
"GetBlockList" -> tag("GetBlockListResponse", "Return" to "Success", body = "")
"QueryOffers" -> tag("QueryOffersResponse", body = "")
"QueryImage" -> tag("QueryImageResponse", "Result" to 0, body = "")
"GetVoipStatus" -> tag("GetVoipStatusResponse", "Available" to false, "Active" to false)
"ShowIGOWindow", "SetDownloaderUtilization" -> null
else -> tag("ErrorSuccess", "Code" to 0, "Description" to "")
}
}
private class AppAccount(private val app: Context) : Account {
private val saved get() = EaAuth.load(app)
override val userId: String get() = saved?.userId.orEmpty()
override val personaId: String get() = saved?.personaId.orEmpty()
override val persona: String get() = saved?.eaId?.ifEmpty { null } ?: saved?.displayName.orEmpty()
override fun authCode(clientId: String, scope: String?): String? =
EaAuth.mint(app, clientId, "code", scopes = scope?.split(' ')?.filter { it.isNotBlank() }.orEmpty())
override fun license(contentId: String, requestTicket: String, ticketEngine: String): String? {
val g = game ?: return null
val hw = g.hardware ?: return null
val token = EaAuth.accessToken(app) ?: return null
return runCatching {
EaOoa.request(token, contentId, EaOoa.machineHash(hw, g.hashVersion), requestTicket.ifEmpty { null }, ticketEngine.ifEmpty { null }).gameToken
}.onFailure { Log.w(TAG, "licence: ${it.message}") }.getOrNull()
}
override fun token(): String? = EaAuth.mint(app, EaAuth.CLIENT_ID, "token", EaAuth.OPAQUE_SCOPES, "OPAQUE", 14400)
override fun entitlements(group: String): List<Map<String, String>> {
val token = EaAuth.accessToken(app) ?: return emptyList()
val arr = runCatching { EaApi.entitlements(token, group) }.getOrNull() ?: return emptyList()
return (0 until arr.length()).mapNotNull { arr.optJSONObject(it) }.map { o ->
o.keys().asSequence().associateWith { k -> o.optString(k) }
}
}
}
}
@@ -0,0 +1,134 @@
package com.droiddeck.launcher.stores.ea
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.File
import java.io.StringReader
/** What `__Installer/installerdata.xml` in an EA build says about running and finishing the install. */
class EaManifest(
val version: String,
val launchers: List<Launcher>,
val touchupPath: String,
val touchupParameters: String,
val contentIds: List<String> = emptyList(),
val titles: Map<String, String> = emptyMap(),
) {
fun title(locale: String): String? = titles[locale] ?: titles["en_US"] ?: titles.values.firstOrNull()
class Launcher(val path: String, val parameters: String, val trial: Boolean)
fun launcher(): Launcher? = launchers.firstOrNull { !it.trial } ?: launchers.firstOrNull()
companion object {
const val RELATIVE = "__Installer/installerdata.xml"
fun decode(bytes: ByteArray): String {
val utf16 = bytes.size >= 2 && ((bytes[0] == 0xFF.toByte() && bytes[1] == 0xFE.toByte()) || (bytes[0] == 0xFE.toByte() && bytes[1] == 0xFF.toByte()))
val text = if (utf16) String(bytes, Charsets.UTF_16) else String(bytes, Charsets.UTF_8)
return text.trimStart('')
}
fun read(folder: File): EaManifest? {
val file = File(folder, RELATIVE).takeIf { it.isFile } ?: EaPaths.find(folder, RELATIVE) ?: return null
return runCatching { parse(decode(file.readBytes())) }.getOrNull()
}
fun parse(xml: String): EaManifest {
val parser = XmlPullParserFactory.newInstance().newPullParser()
parser.setInput(StringReader(xml.replace(Regex("^<\\?xml[^>]*\\?>"), "")))
val stack = ArrayList<String>()
var version = ""
val launchers = ArrayList<Launcher>()
var touchupPath = ""
var touchupParams = ""
var path = ""
var params = ""
var trial = false
val contentIds = ArrayList<String>()
val titles = LinkedHashMap<String, String>()
var locale = ""
while (parser.eventType != XmlPullParser.END_DOCUMENT) {
when (parser.eventType) {
XmlPullParser.START_TAG -> {
val name = parser.name
stack += name
if (name.equals("gameVersion", true)) {
version = parser.getAttributeValue(null, "version") ?: version
}
if (name.equals("launcher", true)) { path = ""; params = ""; trial = false }
if (name.equals("localeInfo", true)) locale = parser.getAttributeValue(null, "locale").orEmpty()
}
XmlPullParser.TEXT -> {
val text = parser.text.trim()
val tag = stack.lastOrNull().orEmpty()
val parent = stack.getOrNull(stack.size - 2).orEmpty()
if (text.isNotEmpty()) when {
parent.equals("launcher", true) && tag.equals("filePath", true) -> path = text
parent.equals("launcher", true) && tag.equals("parameters", true) -> params = text
parent.equals("launcher", true) && tag.equals("trial", true) -> trial = text.equals("true", true) || text == "1"
(parent.equals("touchup", true) || parent.equals("executable", true)) && tag.equals("filePath", true) -> touchupPath = text
(parent.equals("touchup", true) || parent.equals("executable", true)) && tag.equals("parameters", true) -> touchupParams = text
parent.equals("contentIDs", true) && tag.equals("contentID", true) -> contentIds += text
parent.equals("localeInfo", true) && tag.equals("title", true) && locale.isNotEmpty() -> titles[locale] = text
}
}
XmlPullParser.END_TAG -> {
if (parser.name.equals("launcher", true) && path.isNotEmpty()) launchers += Launcher(path, params, trial)
stack.removeLastOrNull()
}
}
parser.next()
}
return EaManifest(version, launchers, touchupPath, touchupParams, contentIds, titles)
}
}
}
object EaPaths {
private val KEY = Regex("^\\[([^\\]]+)\\](.*)$")
/** `[HKEY_LOCAL_MACHINE\SOFTWARE\Publisher\Game\Install Dir]bin\game.exe` splits into the registry key, value and relative path. */
class Registered(val key: String, val value: String, val rest: String)
fun registered(path: String): Registered? {
val m = KEY.find(path.trim()) ?: return null
val full = m.groupValues[1]
val cut = full.lastIndexOf('\\').takeIf { it > 0 } ?: return null
return Registered(full.substring(0, cut), full.substring(cut + 1), m.groupValues[2])
}
fun relative(path: String): String {
val rest = registered(path)?.rest ?: path.replace("{installLocation}", "", ignoreCase = true)
return rest.replace('\\', '/').trimStart('/').split('/').filter { it.isNotEmpty() && it != "." }.joinToString("/")
}
/** The real file for a path the manifest may spell in a different case. */
fun find(folder: File, relative: String): File? {
var cur = folder
for (part in relative.replace('\\', '/').split('/').filter { it.isNotEmpty() }) {
val names = cur.listFiles() ?: return null
cur = names.firstOrNull { it.name == part } ?: names.firstOrNull { it.name.equals(part, true) } ?: return null
}
return cur.takeIf { it.exists() && it != folder }
}
fun relativeOnDisk(folder: File, relative: String): String? =
find(folder, relative)?.relativeTo(folder)?.path?.replace(File.separatorChar, '/')
fun splitArgs(text: String): List<String> {
val out = ArrayList<String>()
val cur = StringBuilder()
var quoted = false
var any = false
for (c in text) {
when {
c == '"' -> { quoted = !quoted; any = true }
c.isWhitespace() && !quoted -> { if (any || cur.isNotEmpty()) out += cur.toString(); cur.clear(); any = false }
else -> cur.append(c)
}
}
if (any || cur.isNotEmpty()) out += cur.toString()
return out
}
}
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.stores.ea
import android.util.Log
import com.droiddeck.launcher.stores.StoresNative
import com.droiddeck.launcher.stores.amazon.AmazonNative
import org.json.JSONObject
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object EaNative {
private const val TAG = "EaNative"
const val ENGINE_MISSING = "EA: the store engine is not available"
fun ready(): Boolean = StoresNative.ensureLoaded()
fun call(op: String, request: JSONObject): JSONObject? {
if (!ready()) return null
val text = try { nativeCall(op, request.toString()) } catch (t: Throwable) {
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
null
} ?: return null
return runCatching { JSONObject(text) }.getOrNull()
}
fun install(request: JSONObject, events: AmazonNative.InstallListener, cancelled: AtomicBoolean): AmazonNative.InstallOutcome {
if (!ready()) return AmazonNative.InstallOutcome(false, false, ENGINE_MISSING, null)
val done = CountDownLatch(1)
val holder = arrayOfNulls<AmazonNative.InstallOutcome>(1)
val bridge = object : AmazonNative.InstallListener by events {
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) {
holder[0] = AmazonNative.InstallOutcome(success, cancelled, error, result.takeIf { it.isNotEmpty() }?.let { runCatching { JSONObject(it) }.getOrNull() })
done.countDown()
}
}
val handle = try { nativeInstall(request.toString(), bridge) } catch (t: Throwable) {
return AmazonNative.InstallOutcome(false, false, "The EA install could not start: ${t.javaClass.simpleName}", null)
}
if (handle == 0L) return holder[0] ?: AmazonNative.InstallOutcome(false, false, "The EA install could not start", null)
try {
var forwarded = false
while (true) {
val finished = try { done.await(250, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { cancelled.set(true); false }
if (finished) break
if (!forwarded && cancelled.get()) { nativeCancel(handle); forwarded = true }
}
} finally {
nativeRelease(handle)
}
return holder[0] ?: AmazonNative.InstallOutcome(false, false, "The EA install ended without a result", null)
}
@JvmStatic private external fun nativeCall(op: String, request: String): String?
@JvmStatic private external fun nativeInstall(request: String, listener: AmazonNative.InstallListener): Long
@JvmStatic private external fun nativeCancel(handle: Long)
@JvmStatic private external fun nativeRelease(handle: Long)
}
@@ -0,0 +1,196 @@
package com.droiddeck.launcher.stores.ea
import org.json.JSONObject
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.File
import java.io.StringReader
import java.net.URLEncoder
import java.security.SecureRandom
/** Origin Online Activation: the per-machine licence an EA game's activation layer checks before it runs. */
object EaOoa {
private const val LICENSES = "https://proxy.novafusion.ea.com/licenses"
const val LICENSE_DIR = "ProgramData/Electronic Arts/EA Services/License"
private const val SIGNATURE_SLOT = 65
/**
* What the game sees of the machine inside its Wine prefix: firmware and OS values from Wine's
* WMI, CPU values from CPUID executed as x86 code, since an emulated game sees the emulator's
* CPUID rather than the host CPU WMI describes.
*/
class Hardware(
val boardManufacturer: String,
val boardSerial: String,
val biosManufacturer: String,
val biosSerial: String,
val osInstallDate: String,
val osSerial: String,
val volumeSerial: String,
val gpuPnpId: String,
val cpuVendor: String,
val cpuEdx: String,
val cpuEax: String,
val cpuEcx: String,
val brand: String,
val hostname: String,
) {
/** Whether the probe reported everything the hash of this activation version is built from. */
fun complete(version: Int): Boolean {
val needed = arrayListOf(boardManufacturer, biosManufacturer)
when {
version <= 1 -> needed += listOf(hostname, osInstallDate, osSerial)
version == 2 -> needed += listOf(osInstallDate, osSerial, volumeSerial, cpuVendor, cpuEdx, cpuEcx)
version == 3 -> needed += listOf(volumeSerial, cpuVendor, cpuEdx, cpuEcx)
else -> needed += listOf(volumeSerial, cpuVendor, cpuEdx, cpuEax)
}
return needed.all { it.isNotEmpty() }
}
companion object {
fun fromJson(o: JSONObject): Hardware {
fun s(k: String) = o.optString(k).trim()
return Hardware(
boardManufacturer = s("boardManufacturer"),
boardSerial = s("boardSerial").ifEmpty { "None" },
biosManufacturer = s("biosManufacturer"),
biosSerial = s("biosSerial").ifEmpty { "None" },
osInstallDate = s("osInstallDate"),
osSerial = s("osSerial"),
volumeSerial = s("volumeSerial").replace("-", "").lowercase().let { if (it.isEmpty()) it else it.padStart(8, '0') },
gpuPnpId = s("gpuPnpId").ifEmpty { "None" },
cpuVendor = s("cpuVendor"),
cpuEdx = s("cpuEdx").uppercase(),
cpuEax = s("cpuEax").uppercase(),
cpuEcx = s("cpuEcx").lowercase(),
brand = o.optString("cpuBrand"),
hostname = s("hostname"),
)
}
}
}
fun machineHash(hw: Hardware, version: Int): String {
val edxEax = hw.cpuEdx + hw.cpuEax
val edx = hw.cpuEdx.lowercase()
val shortGpu = hw.gpuPnpId.substringBeforeLast('\\', hw.gpuPnpId)
val parts = arrayListOf(hw.boardManufacturer, hw.boardSerial)
when {
version <= 1 -> parts += listOf(hw.hostname, hw.biosManufacturer, hw.biosSerial, hw.osInstallDate, hw.osSerial)
version == 2 -> parts += listOf(hw.biosManufacturer, hw.biosSerial, hw.osInstallDate, hw.osSerial, hw.volumeSerial, shortGpu, hw.cpuVendor, edx, hw.cpuEcx)
version == 3 -> parts += listOf(hw.biosManufacturer, hw.biosSerial, hw.volumeSerial, shortGpu, hw.cpuVendor, edx, hw.cpuEcx)
else -> parts += listOf(hw.biosManufacturer, hw.biosSerial, hw.volumeSerial, hw.gpuPnpId, hw.cpuVendor, edxEax)
}
val text = StringBuilder(parts.joinToString(";")).append(';')
if (version >= 2) text.append(hw.brand.take(47).padEnd(47, '\u0000')).append(';')
val digest = EaCrypto.sha1(text.toString().toByteArray(Charsets.ISO_8859_1))
return if (version < 4) digest.joinToString("") { Integer.toHexString(it.toInt() and 0xFF) } else EaCrypto.hex(digest)
}
/** Version of the game's activation layer, which decides how the machine hash is built. */
fun activationVersion(core: File): Int {
val dll = listOf("activation.dll", "awc.dll").firstNotNullOfOrNull { EaPaths.find(core, it) } ?: return 1
val (major, minor, patch) = productVersion(dll.readBytes()) ?: return 1
return when {
major >= 5 -> 4
major == 4 && (minor > 7 || (minor == 7 && patch >= 6)) -> 3
major == 4 && minor == 7 -> 2
major == 4 -> 1
else -> 0
}
}
/** The activation layer's folder: `Core` beside the game's exe, where EA ships it, or at the game root. */
fun coreDir(game: File, exe: String): File? {
val exeDir = exe.replace('\\', '/').substringBeforeLast('/', "")
val candidates = listOfNotNull(exeDir.takeIf { it.isNotEmpty() }?.let { "$it/Core" }, "Core")
return candidates.firstNotNullOfOrNull { EaPaths.find(game, it)?.takeIf { f -> f.isDirectory } }
}
/** Games built on the 2012-era EA Core client, which want an opaque token rather than a JWS one. */
fun legacyCore(core: File?): Boolean = core != null && EaPaths.find(core, "EACore.dll") != null
private fun encodedSignature(core: File): Boolean = EaPaths.find(core, "activation.exe") != null
internal fun productVersion(pe: ByteArray): Triple<Int, Int, Int>? {
val magic = byteArrayOf(0xBD.toByte(), 0x04, 0xEF.toByte(), 0xFE.toByte())
var i = 0
while (i + 24 <= pe.size) {
if (pe[i] == magic[0] && pe[i + 1] == magic[1] && pe[i + 2] == magic[2] && pe[i + 3] == magic[3]) {
fun u32(at: Int) = (pe[at].toLong() and 0xFF) or ((pe[at + 1].toLong() and 0xFF) shl 8) or ((pe[at + 2].toLong() and 0xFF) shl 16) or ((pe[at + 3].toLong() and 0xFF) shl 24)
val ms = u32(i + 16)
val ls = u32(i + 20)
return Triple((ms ushr 16).toInt(), (ms and 0xFFFF).toInt(), (ls ushr 16).toInt())
}
i++
}
return null
}
class License(val fields: LinkedHashMap<String, String>, val namespace: String, val signature: String) {
val gameToken: String? get() = fields["GameToken"]?.takeIf { it.isNotEmpty() }
val contentId: String get() = fields["ContentId"].orEmpty()
}
internal fun parseLicense(xml: String, signature: String): License {
val parser = XmlPullParserFactory.newInstance().apply { isNamespaceAware = false }.newPullParser()
parser.setInput(StringReader(xml.replace(Regex("^<\\?xml[^>]*\\?>"), "").trim()))
val fields = LinkedHashMap<String, String>()
var ns = ""
var depth = 0
var tag = ""
while (parser.eventType != XmlPullParser.END_DOCUMENT) {
when (parser.eventType) {
XmlPullParser.START_TAG -> {
depth++
if (depth == 1) ns = parser.getAttributeValue(null, "xmlns").orEmpty() else tag = parser.name
if (depth == 2) fields[tag] = ""
}
XmlPullParser.TEXT -> if (depth == 2) fields[tag] = fields[tag].orEmpty() + parser.text
XmlPullParser.END_TAG -> depth--
}
parser.next()
}
return License(fields, ns, signature)
}
private fun esc(s: String) = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
fun licenseXml(l: License): String {
val order = listOf("CipherKey", "MachineHash", "ContentId", "UserId", "GameToken", "GrantTime", "StartTime", "Nonce")
val body = StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
body.append("<License xmlns=\"").append(esc(l.namespace)).append("\">")
for (k in order) {
val v = l.fields[k] ?: continue
if (k == "GameToken" && v.isEmpty()) continue
body.append('<').append(k).append('>').append(esc(v)).append("</").append(k).append('>')
}
return body.append("</License>").toString()
}
fun licenseBlob(l: License, encoded: Boolean): ByteArray {
val signature = if (encoded) l.signature.toByteArray() else java.util.Base64.getDecoder().decode(l.signature)
val head = ByteArray(SIGNATURE_SLOT)
System.arraycopy(signature, 0, head, 0, signature.size.coerceAtMost(SIGNATURE_SLOT))
return head + EaCrypto.licenseEncrypt(licenseXml(l).toByteArray())
}
fun request(token: String, contentId: String, machineHash: String, requestToken: String? = null, requestType: String? = null): License {
val nonce = EaCrypto.hex(ByteArray(4).also(SecureRandom()::nextBytes))
val params = mutableListOf("contentId" to contentId, "machineHash" to machineHash, "nonce" to nonce, "ea_eadmtoken" to token)
if (requestToken != null) params += "requestToken" to requestToken
if (requestType != null) params += "requestType" to requestType
val url = LICENSES + "?" + params.joinToString("&") { (k, v) -> k + "=" + URLEncoder.encode(v, "UTF-8") }
val reply = EaHttp.request(url, headers = mapOf("X-Requester-Id" to "Origin Online Activation", "User-Agent" to "EACTransaction"))
if (!reply.ok) throw IllegalStateException("EA refused the licence (${reply.status}): ${reply.text.replace(Regex("(eadmToken value=\")[^\"]*"), "$1<redacted>\"").take(600)}")
val signature = reply.header("x-signature") ?: throw IllegalStateException("EA's licence had no signature")
return parseLicense(String(EaCrypto.licenseDecrypt(reply.body), Charsets.UTF_8), signature)
}
/** Licence files for a game about to start, named as the activation layer looks for them. */
fun files(core: File, license: License): List<Pair<String, ByteArray>> {
val blob = licenseBlob(license, encodedSignature(core))
val id = license.contentId
return listOf("$LICENSE_DIR/$id.dlf" to blob, "$LICENSE_DIR/${id}_cached.dlf" to blob)
}
}
@@ -139,15 +139,21 @@ object GogComet {
!File(LinuxRuntime.rootDir(context), BIN.removePrefix("/")).isFile) return reply(false, "not-installed")
val data = File(context.filesDir, "gog-achievements").apply { mkdirs() }
val ready = CountDownLatch(1)
val command = LinuxRuntime.command(context, null, null, Environment.getExternalStorageDirectory(),
listOf("/usr/bin/env", "HOME=/root", "XDG_DATA_HOME=${data.path}/data", "XDG_CONFIG_HOME=${data.path}/config", "COMET_LOG=off", "COMET_ALLOWED_CLIENTS=${policy.path}", BIN, "--credentials-stdin"))
val pb = ProcessBuilder(command).redirectErrorStream(true)
pb.environment().apply {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
val guest = listOf("/usr/bin/env", "HOME=/root", "XDG_DATA_HOME=${data.path}/data", "XDG_CONFIG_HOME=${data.path}/config", "COMET_LOG=off", "COMET_ALLOWED_CLIENTS=${policy.path}", BIN, "--credentials-stdin")
val pb = if (com.droiddeck.launcher.runtime.NativeGuest.forSession(context)) {
val root = LinuxRuntime.rootDir(context)
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
LinuxRuntime.binds(context, null, null, Environment.getExternalStorageDirectory(), null), guest).redirectErrorStream(true)
} else {
ProcessBuilder(LinuxRuntime.command(context, null, null, Environment.getExternalStorageDirectory(), guest)).redirectErrorStream(true).also {
it.environment().apply {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
}
try {
val child = pb.start()
@@ -0,0 +1,74 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONObject
import java.io.File
/**
* Answers Denuvo activations for a running Ubisoft game. droiddeck-upc.exe writes the challenge
* the game's aux DLL sends to `bridge-<product>/denuvo-<id>.req`; the answer goes to `.rsp`.
*/
object UbisoftActivation {
private const val POLL_MS = 250L
private const val IDLE_MS = 60_000L
private val watching = HashMap<Long, Long>()
fun bridge(context: Context, product: Long) = File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/ubisoft/bridge-$product")
/** Starts answering the product's activations; stale requests are cleared before this returns. */
fun watch(app: Context, product: Long) {
val dir = bridge(app, product)
synchronized(watching) {
val running = watching.containsKey(product)
watching[product] = System.currentTimeMillis()
if (running) return
dir.mkdirs()
dir.listFiles()?.forEach { it.delete() }
}
Thread({
var idleSince = 0L
while (true) {
runCatching { dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }?.forEach { answer(app, product, it) } }
.onFailure { StoresState.logLine("Ubisoft: activation for $product: ${it.javaClass.simpleName}") }
val now = System.currentTimeMillis()
if (SessionState.running) idleSince = 0L
else if (idleSince == 0L) idleSince = now
else if (now - idleSince > IDLE_MS) synchronized(watching) {
if (now - (watching[product] ?: 0L) > IDLE_MS) { watching.remove(product); return@Thread }
}
runCatching { Thread.sleep(POLL_MS) }
}
}, "ubisoft-activation-$product").start()
}
private fun answer(app: Context, product: Long, request: File) {
val challenge = runCatching { request.readBytes() }.getOrNull() ?: return
request.delete()
val reply = File(request.parentFile, request.name.removeSuffix(".req") + ".rsp")
val token = activate(app, product, challenge)
val part = File(reply.path + ".part")
part.writeBytes(token ?: ByteArray(0))
part.renameTo(reply)
}
private fun activate(app: Context, product: Long, challenge: ByteArray): ByteArray? {
val s = UbisoftAuth.current(app) ?: return null.also { StoresState.logLine("Ubisoft: activation for $product: signed out") }
val answer = UbisoftNative.call("denuvo", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId)
.put("productId", product).put("challenge", hex(challenge)))
answer?.optString("error")?.takeIf { it.isNotEmpty() }?.let {
StoresState.logLine("Ubisoft: activation for $product: $it")
return null
}
val token = answer?.optString("token")?.takeIf { it.isNotEmpty() }?.let(::unhex)
StoresState.logLine("Ubisoft: activation for $product: ${token?.size ?: 0} B game token")
return token
}
internal fun hex(b: ByteArray): String = b.joinToString("") { "%02x".format(it) }
internal fun unhex(s: String): ByteArray? =
if (s.length % 2 != 0) null else runCatching { ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() } }.getOrNull()
}
@@ -0,0 +1,176 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/** UbiServices sessions: a ticket from Ubisoft's own web sign-in, exchanged for a launcher session that remember-me renews. */
object UbisoftAuth {
private const val TAG = "UbisoftAuth"
const val SESSIONS = "https://public-ubiservices.ubi.com/v3/profiles/sessions"
/** The web app and genome connect.ubisoft.com's sign-in page accepts. */
private const val WEB_APP_ID = "f35adcb5-1911-440c-b1c9-48fdc1701c68"
private const val WEB_GENOME_ID = "5b36b900-65d8-47f3-93c8-86bdaa48ab50"
/** The Ubisoft Connect PC app id; its sessions are accepted by the library GraphQL and Demux. */
const val APP_ID = "f68a4bb5-608a-4ff2-8123-be8ef797e0a6"
private const val REFRESH_MARGIN_MS = 10 * 60 * 1000L
private val lock = Any()
class Session(
val ticket: String,
val sessionId: String,
val profileId: String,
val userId: String,
val name: String,
val expiresAt: Long,
val rememberMe: String,
)
class Reply(val status: Int, val body: String, val headers: Map<String, String>) {
val ok get() = status in 200..299
}
private val loggedIn = "https://connect.ubisoft.com/logged-in.html?appId=$WEB_APP_ID&lang=en-US&genomeId=$WEB_GENOME_ID"
val loginUrl = "https://connect.ubisoft.com/login?appId=$WEB_APP_ID&genomeId=$WEB_GENOME_ID&lang=en-US&nextUrl=" + URLEncoder.encode(loggedIn, "UTF-8")
val SIGN_IN_URLS = listOf("https://connect.ubisoft.com", "https://account.ubisoft.com", "https://ubisoft.com")
fun isLoggedInPage(url: String) = url.startsWith("https://connect.ubisoft.com/logged-in.html")
/** Reads connect.ubisoft.com's stored sign-in; the WebAuth SDK keeps it under keys holding `loginData` and `rememberMe`. */
const val PAGE_SCRIPT = "(function(){try{var o={};for(var i=0;i<localStorage.length;i++){var k=localStorage.key(i);" +
"if(/loginData|rememberMe|lastProfile/i.test(k))o[k]=localStorage.getItem(k);}return JSON.stringify(o);}catch(e){return '';}})()"
internal fun request(url: String, method: String = "GET", authorization: String? = null, sessionId: String? = null, body: String? = null, extra: Map<String, String> = emptyMap()): Reply {
val c = URL(url).openConnection() as HttpURLConnection
c.requestMethod = method
c.connectTimeout = 15_000
c.readTimeout = 25_000
c.setRequestProperty("Ubi-AppId", APP_ID)
c.setRequestProperty("Ubi-RequestedPlatformType", "uplay")
c.setRequestProperty("Content-Type", "application/json")
c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")
authorization?.let { c.setRequestProperty("Authorization", it) }
sessionId?.let { c.setRequestProperty("Ubi-SessionId", it) }
for ((k, v) in extra) c.setRequestProperty(k, v)
try {
if (body != null) {
c.doOutput = true
c.outputStream.use { it.write(body.toByteArray()) }
}
val status = c.responseCode
val text = (if (status in 200..299) c.inputStream else c.errorStream)?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty()
val headers = c.headerFields.filterKeys { it != null }.mapKeys { it.key.lowercase() }.mapValues { it.value.joinToString(",") }
return Reply(status, text, headers)
} finally {
c.disconnect()
}
}
/** POSTs a session request, replaying it once when UbiServices answers with a challenge. */
private fun session(authorization: String): Reply {
val body = JSONObject().put("rememberMe", true).toString()
val first = request(SESSIONS, "POST", authorization, body = body)
val challenge = first.headers["ubi-challenge"] ?: return first
return request(SESSIONS, "POST", authorization, body = body, extra = mapOf("Ubi-Challenge" to challenge))
}
internal fun parseSession(body: String, rememberFallback: String = ""): Session? {
val o = runCatching { JSONObject(body) }.getOrNull() ?: return null
val ticket = o.optString("ticket").takeIf { it.isNotEmpty() && it != "null" } ?: return null
return Session(
ticket = ticket,
sessionId = o.optString("sessionId"),
profileId = o.optString("profileId"),
userId = o.optString("userId"),
name = o.optString("nameOnPlatform"),
expiresAt = parseTime(o.optString("expiration")),
rememberMe = o.optString("rememberMeTicket").takeIf { it.isNotEmpty() && it != "null" } ?: rememberFallback,
)
}
internal fun parseTime(s: String): Long = runCatching { java.time.OffsetDateTime.parse(s).toInstant().toEpochMilli() }
.recoverCatching { java.time.Instant.parse(s).toEpochMilli() }.getOrDefault(System.currentTimeMillis() + 60 * 60 * 1000L)
/** Values the web sign-in stored, found wherever the SDK nests them. */
internal fun webValues(dump: String): Map<String, String> {
val out = HashMap<String, String>()
fun walk(v: Any?) {
when (v) {
is JSONObject -> v.keys().forEach { k ->
val x = v.opt(k)
if (x is String && x.isNotEmpty() && k !in out) {
val nested = if (x.startsWith("{") || x.startsWith("[")) runCatching { org.json.JSONTokener(x).nextValue() }.getOrNull() else null
if (nested != null) walk(nested) else out[k] = x
} else walk(x)
}
is JSONArray -> for (i in 0 until v.length()) walk(v.opt(i))
}
}
val top = runCatching { org.json.JSONTokener(dump).nextValue() }.getOrNull()
walk(if (top is String) runCatching { JSONObject(top) }.getOrNull() else top)
return out
}
/** Turns the page's stored sign-in into a launcher session; returns null on success or a reason. */
fun completeWebSignIn(context: Context, dump: String): String? {
val web = webValues(dump)
val ticket = web["ticket"]
val remember = web["rememberMeTicket"].orEmpty()
val fresh = when {
ticket != null -> session("ubi_v1 t=$ticket").let { r ->
parseSession(r.body, remember) ?: run { Log.w(TAG, "ticket exchange: ${r.status} ${r.body.take(200)}"); null }
}
else -> null
} ?: remember.takeIf { it.isNotEmpty() }?.let { rm -> parseSession(session("rm_v1 t=$rm").body, rm) }
?: return "no ticket"
save(context, fresh)
com.droiddeck.launcher.session.SessionFiles.ensureUbisoftService(context)
return null
}
private fun save(context: Context, s: Session) {
val name = s.name.ifEmpty { profileName(s) }
StoreAccounts.write(context.applicationContext, Store.UBISOFT, JSONObject()
.put("access_token", s.ticket)
.put("session_id", s.sessionId)
.put("profile_id", s.profileId)
.put("user_id", s.userId)
.put("display_name", name)
.put("expires_at", s.expiresAt)
.put("remember_me", s.rememberMe))
}
private fun profileName(s: Session): String = runCatching {
JSONObject(request("https://public-ubiservices.ubi.com/v3/profiles/me", authorization = "ubi_v1 t=${s.ticket}", sessionId = s.sessionId).body).optString("nameOnPlatform")
}.getOrDefault("")
fun load(context: Context): Session? {
val o = StoreAccounts.read(context.applicationContext, Store.UBISOFT) ?: return null
val ticket = o.optString("access_token").takeIf { it.isNotEmpty() } ?: return null
return Session(ticket, o.optString("session_id"), o.optString("profile_id"), o.optString("user_id"), o.optString("display_name"), o.optLong("expires_at"), o.optString("remember_me"))
}
/** A live session, renewed through remember-me shortly before it expires. */
fun current(context: Context): Session? = synchronized(lock) {
val s = load(context) ?: return null
if (s.expiresAt - System.currentTimeMillis() > REFRESH_MARGIN_MS || s.rememberMe.isEmpty()) return s
val renewed = runCatching { session("rm_v1 t=${s.rememberMe}") }.getOrNull()?.let { parseSession(it.body, s.rememberMe) }
if (renewed == null) {
Log.w(TAG, "remember-me renewal failed")
return if (s.expiresAt > System.currentTimeMillis()) s else null
}
save(context, Session(renewed.ticket, renewed.sessionId, renewed.profileId.ifEmpty { s.profileId }, renewed.userId.ifEmpty { s.userId },
renewed.name.ifEmpty { s.name }, renewed.expiresAt, renewed.rememberMe))
load(context)
}
fun signOut(context: Context) = synchronized(lock) { StoreAccounts.clear(context.applicationContext, Store.UBISOFT) }
}
@@ -0,0 +1,246 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import android.content.Intent
import android.util.Log
import android.webkit.WebView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.LoginFlows
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreBackend
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.WebCookies
import org.json.JSONObject
object UbisoftBackend : StoreBackend {
override val store: Store = Store.UBISOFT
init {
LoginFlows.ubisoftFlow = { ua -> UbisoftLogin(ua) }
}
override fun signIn(context: Context) {
context.startActivity(
Intent(context, StoreLoginActivity::class.java)
.putExtra(StoreLoginActivity.EXTRA_STORE, store.id)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
override fun signOut(context: Context) {
UbisoftAuth.signOut(context.applicationContext)
UbisoftLibrary.reset()
runCatching { WebCookies.expire(UbisoftAuth.SIGN_IN_URLS, ".ubisoft.com", listOf("/")) {} }
}
override fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
Thread({ UbisoftLibrary.sync(app, force) }, "ubisoft-sync").start()
}
override fun loadShelves(context: Context, force: Boolean) {}
override fun install(context: Context, item: CatalogItem, root: java.io.File) {
val app = context.applicationContext
item.extra[STEAM_APP]?.takeIf { item.extra["productId"] == null }?.let { steam ->
StoresState.logLine("Ubisoft: ${item.title} is owned on Steam; installing Steam app $steam")
installInSteam(app, steam)
return
}
if (!UbisoftNative.ready()) {
StoresState.logLine(UbisoftNative.ENGINE_MISSING)
StoresState.post { StoresState.problems[store] = UbisoftNative.ENGINE_MISSING }
return
}
val folder = StoreInstallRoot.folderFor(app, store, item.id, item.title, root)
val entry = DownloadEntry(store, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl,
bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
DownloadQueue.enqueue(app, entry) { UbisoftInstaller(app, item, folder) }
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
const val STEAM_APP = "steamAppId"
/** Steam asks to install a game it does not have when told to run it. */
private fun installInSteam(app: Context, steamAppId: String) {
if (com.droiddeck.launcher.session.SessionState.running) {
if (!com.droiddeck.launcher.session.SessionService.launchGame(app, steamAppId)) StoresState.logLine("Ubisoft: Steam is busy; install Steam app $steamAppId there")
return
}
app.startActivity(Intent(app, com.droiddeck.launcher.SessionActivity::class.java)
.putExtra(com.droiddeck.launcher.session.SessionService.EXTRA_STEAM_URL, com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(steamAppId))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
internal class UbisoftLogin(override val userAgent: String) : StoreLoginActivity.Flow {
override val startUrl: String get() = UbisoftAuth.loginUrl
override val readsPage: Boolean get() = true
override val pageScript: String get() = UbisoftAuth.PAGE_SCRIPT
override fun pageReady(result: String): Boolean = result.contains("ticket", ignoreCase = true)
override fun isRedirect(url: String): Boolean = UbisoftAuth.isLoggedInPage(url)
override fun forgetSignIn(done: () -> Unit) {
runCatching { WebCookies.expire(UbisoftAuth.SIGN_IN_URLS, ".ubisoft.com", listOf("/")) { done() } }.onFailure { done() }
}
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? = try {
UbisoftAuth.completeWebSignIn(activity, url)?.let {
Log.w("UbisoftLogin", "sign-in incomplete: $it")
activity.getString(R.string.stores_login_error_verification)
}
} catch (e: Exception) {
Log.w("UbisoftLogin", "sign-in failed: ${e.javaClass.simpleName}")
activity.getString(R.string.stores_login_error_generic)
}
}
object UbisoftLibrary {
private const val GRAPHQL = "https://public-ubiservices.ubi.com/v1/profiles/me/uplay/graphql"
private const val PAGE = 50
private const val QUERY = "query OwnedGames(\$limit: Int, \$offset: Int) { viewer { games(limit: \$limit, offset: \$offset) { totalCount nodes { id spaceId name coverUrl backgroundUrl bannerUrl releaseDate } } } }"
private val generation = java.util.concurrent.atomic.AtomicInteger()
private val running = java.util.concurrent.atomic.AtomicReference<Int?>(null)
/** Forgets the signed-out account: its sync results are dropped and a new account may sync at once. */
fun reset() {
generation.incrementAndGet()
StoresState.post { StoresState.shelves.remove(Store.UBISOFT) }
}
private fun post(gen: Int, block: () -> Unit) = StoresState.post { if (generation.get() == gen) block() }
internal fun parsePage(body: String): Pair<List<CatalogItem>, Int> {
val o = JSONObject(body)
o.optJSONArray("errors")?.optJSONObject(0)?.let { throw IllegalStateException(it.optString("message")) }
val games = o.optJSONObject("data")?.optJSONObject("viewer")?.optJSONObject("games") ?: return emptyList<CatalogItem>() to 0
val nodes = games.optJSONArray("nodes")
val items = (0 until (nodes?.length() ?: 0)).mapNotNull { nodes!!.optJSONObject(it) }.mapNotNull { n ->
val space = n.optString("spaceId").takeIf { it.isNotEmpty() } ?: return@mapNotNull null
fun s(k: String) = n.optString(k).takeIf { it.isNotEmpty() && it != "null" }
CatalogItem(
Store.UBISOFT, space, n.optString("name").trim(), s("backgroundUrl") ?: s("bannerUrl"),
tallImageUrl = s("coverUrl"), releaseDate = s("releaseDate")?.take(10).orEmpty(), owned = true,
extra = mapOf("spaceId" to space, "gameId" to n.optString("id")),
)
}
return items to games.optInt("totalCount", items.size)
}
/** Base games with a manifest, by UbiServices space; add-ons and bundles share spaces with their game. */
internal fun ownedBySpace(owned: JSONObject?): Map<String, JSONObject> {
val list = owned?.optJSONArray("games") ?: return emptyMap()
val games = (0 until list.length()).mapNotNull { list.optJSONObject(it) }
.filter { it.optString("manifest").isNotEmpty() && it.optInt("productType") == 0 && it.optBoolean("owned", true) }
val out = LinkedHashMap<String, JSONObject>()
for (key in listOf("spaceId")) for (g in games) {
val space = g.optString(key).takeIf { it.isNotEmpty() } ?: continue
out.putIfAbsent(space, g)
}
return out
}
private val STEAM_ID = Regex("""^\s*steam_app_id:\s*['"]?(\d+)""", RegexOption.MULTILINE)
private val THIRD_PARTY = Regex("""^\s*third_party_platform:\s*\r?\n\s+name:\s*['"]?Steam\b""", setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE))
/** The Steam app of a product Ubisoft says is owned and installed through Steam. */
internal fun steamApp(configuration: String): String? =
if (THIRD_PARTY.containsMatchIn(configuration)) STEAM_ID.find(configuration)?.groupValues?.get(1) else null
/** Owned games Ubisoft delivers through Steam, by UbiServices space. */
internal fun steamBySpace(owned: JSONObject?): Map<String, String> {
val list = owned?.optJSONArray("games") ?: return emptyMap()
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }
.filter { it.optInt("productType") == 0 && it.optBoolean("owned", true) && it.optString("spaceId").isNotEmpty() }
.mapNotNull { o -> steamApp(o.optString("configuration"))?.let { o.optString("spaceId") to it } }.toMap()
}
private val RELATIVE = Regex("""relative:\s*['"]?([^'"\r\n]+?)['"]?\s*$""", RegexOption.MULTILINE)
private val NAME = Regex("""^\s{1,4}name:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE)
/** The product's name from its configuration, following a localisation key such as `l1` to its default text. */
internal fun title(configuration: String): String? {
val raw = NAME.find(configuration)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() } ?: return null
if (!Regex("""l\d+""").matches(raw)) return raw
val local = configuration.indexOf("localizations:").takeIf { it >= 0 } ?: return raw
return Regex("""^\s+${raw}:\s*['"]?(.+?)['"]?\s*$""", RegexOption.MULTILINE).find(configuration, local)?.groupValues?.get(1)?.trim() ?: raw
}
/** The first launch path under `start_game` in a product's configuration. */
internal fun executable(configuration: String): String? {
val start = configuration.indexOf("start_game").takeIf { it >= 0 } ?: return null
return RELATIVE.find(configuration, start)?.groupValues?.get(1)?.trim()?.takeIf { it.endsWith(".exe", true) }
}
fun sync(app: Context, force: Boolean) {
val gen = generation.get()
if (running.getAndSet(gen) == gen) return
try {
val s = UbisoftAuth.current(app)
if (s == null) {
post(gen) { StoresState.status.remove(Store.UBISOFT); StoresState.problems[Store.UBISOFT] = app.getString(R.string.stores_sync_sign_in) }
return
}
if (StoresState.library[Store.UBISOFT].isNullOrEmpty()) post(gen) { StoresState.status[Store.UBISOFT] = app.getString(R.string.stores_sync_game_list) }
val all = ArrayList<CatalogItem>()
var offset = 0
while (true) {
val body = JSONObject().put("operationName", "OwnedGames").put("query", QUERY)
.put("variables", JSONObject().put("limit", PAGE).put("offset", offset)).toString()
val reply = UbisoftAuth.request(GRAPHQL, "POST", "Ubi_v1 t=${s.ticket}", s.sessionId, body)
if (reply.status == 401) StoresState.markSignInExpired(Store.UBISOFT)
if (!reply.ok) throw IllegalStateException("library ${reply.status}")
val (items, total) = parsePage(reply.body)
all += items
offset += PAGE
if (items.isEmpty() || offset >= total) break
}
val owned = UbisoftNative.call("owned", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId))
owned?.optString("error")?.takeIf { it.isNotEmpty() }?.let { StoresState.logLine("Ubisoft: ownership: $it") }
val bySpace = ownedBySpace(owned)
owned?.takeIf { it.optInt("manifestsAsked") > 0 }?.let {
StoresState.logLine("Ubisoft: latest manifests: ${it.optInt("manifestsFound")} of ${it.optInt("manifestsAsked")} ${it.optString("manifestError")}".trim())
}
fun download(o: JSONObject) = listOfNotNull(
"productId" to o.optLong("productId").toString(),
o.optString("manifest").takeIf { it.isNotEmpty() }?.let { "manifest" to it },
o.optString("appId").takeIf { it.isNotEmpty() }?.let { "appId" to it },
executable(o.optString("configuration"))?.let { "exe" to it },
)
val listed = all.distinctBy { it.id }
val onSteam = steamBySpace(owned)
val matched = listed.map { g -> bySpace[g.id]?.let { g.copy(extra = g.extra + download(it)) } ?: onSteam[g.id]?.let { g.copy(extra = g.extra + (UbisoftBackend.STEAM_APP to it)) } ?: g }
.let { games -> games.filter { g -> g.extra["productId"] == null || games.first { it.extra["productId"] == g.extra["productId"] } === g } }
.let { games -> games.filter { g -> g.extra["productId"] != null || games.none { it !== g && it.title == g.title && it.extra["productId"] != null } } }
val products = matched.mapNotNull { it.extra["productId"] }.toSet()
val unlisted = bySpace.filterKeys { space -> listed.none { it.id == space } }.filterValues { it.optLong("productId").toString() !in products }.mapNotNull { (space, o) ->
val title = title(o.optString("configuration")) ?: return@mapNotNull null
CatalogItem(Store.UBISOFT, space, title, null, owned = true, extra = mapOf("spaceId" to space) + download(o))
}
val games = (matched + unlisted).sortedBy { it.title.lowercase() }
StoresState.logLine("Ubisoft: ${bySpace.size} downloadable products; " +
games.filter { it.extra.containsKey("productId") }.joinToString(", ") { "${it.title}=${it.extra["productId"]}" })
post(gen) {
StoresState.status.remove(Store.UBISOFT)
StoresState.problems.remove(Store.UBISOFT)
StoresState.library[Store.UBISOFT] = games
StoresState.shelves[Store.UBISOFT] = com.droiddeck.launcher.stores.StoreShelves(
trending = games.sortedByDescending { it.extra.containsKey("productId") }, art = games.mapNotNull { it.imageUrl })
}
StoresState.logLine("Ubisoft: ${games.size} owned games; on Steam: " + games.filter { it.extra.containsKey(UbisoftBackend.STEAM_APP) }.joinToString(", ") { "${it.title}=${it.extra[UbisoftBackend.STEAM_APP]}" })
} catch (e: Exception) {
StoresState.logLine("Ubisoft: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(200)}")
post(gen) { StoresState.status.remove(Store.UBISOFT); StoresState.problems[Store.UBISOFT] = app.getString(R.string.stores_sync_failed) }
} finally {
running.compareAndSet(gen, null)
}
}
}
@@ -0,0 +1,18 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/** The one prefix every Ubisoft game runs in, so Ubisoft Connect is installed and signed in once. */
object UbisoftConnect {
const val APP_ID = 2929927072L
fun prefix(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/compatdata/$APP_ID")
fun installed(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher/upc.exe").isFile
fun launchOptions(context: Context): String =
AddedGames.guestPath(context, prefix(context))?.let { "STEAM_COMPAT_DATA_PATH=$it %command%" }.orEmpty()
}
@@ -0,0 +1,104 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreExe
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.amazon.AmazonNative
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONObject
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
internal class UbisoftInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
override fun run(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.MANIFEST, app.getString(R.string.stores_sync_sign_in))
val s = UbisoftAuth.current(app) ?: throw IllegalStateException("Not signed in to Ubisoft")
val product = item.extra["productId"]?.toLongOrNull() ?: throw IllegalStateException("Ubisoft lists no download for ${item.title} on this account")
val cover = item.tallImageUrl ?: item.imageUrl
StoreInstalls.begin(folder, Store.UBISOFT, item.id, item.title, cover, item.imageUrl)
if (cancelled.get()) return null
val locale = StoreLanguage.localeFor(null, app)
val request = JSONObject()
.put("ticket", s.ticket)
.put("sessionId", s.sessionId)
.put("productId", product)
.put("manifest", item.extra["manifest"].orEmpty())
.put("folder", folder.absolutePath)
.put("language", "${locale.language}-${locale.country}")
val shown = AtomicLong(-1)
val downloading = AtomicBoolean(false)
val listener = object : AmazonNative.InstallListener {
override fun onStatus(text: String) { handle.stage(DownloadStage.MANIFEST, text) }
override fun onCheck(doneBytes: Long, totalBytes: Long, files: Int, filesTotal: Int) {
handle.stageProgress(doneBytes, totalBytes, files, filesTotal, bytes = true)
}
override fun onSizes(pendingBytes: Long, totalBytes: Long) { handle.diskSize(totalBytes) }
override fun onProgress(done: Long, total: Long, files: Int, filesTotal: Int) {
if (downloading.compareAndSet(false, true)) handle.stage(DownloadStage.DOWNLOAD)
while (true) {
val before = shown.get()
if (done < before) return
if (shown.compareAndSet(before, done)) break
}
handle.progress(done, total, "Downloading ($files/$filesTotal files)")
}
override fun onLog(line: String) { handle.log(line) }
override fun beforeReplace(): Boolean = true
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) = Unit
}
val outcome = UbisoftNative.install(request, listener, cancelled)
if (outcome.cancelled || cancelled.get() && !outcome.success) return null
if (!outcome.success) throw IllegalStateException(outcome.error.ifEmpty { "The Ubisoft install failed" })
handle.stage(DownloadStage.INSTALL, app.getString(R.string.stores_registering))
val configured = resolve(folder, item.extra["exe"].orEmpty())
val exe = configured ?: StoreExe.pick(folder, null, item.title).ifEmpty { "game.exe" }
handle.log("ubisoft: exe=$exe")
val sidecar = StoreGameSidecar(
Store.UBISOFT, item.id, item.title, exe = exe,
installVersion = item.extra["manifest"].orEmpty(), installedAt = System.currentTimeMillis(),
cover = cover, hero = item.imageUrl, cloud = false,
extra = item.extra.filterKeys { it in KEPT } + listOfNotNull(
outcome.result?.optJSONArray("chunks")?.let { UbisoftLaunch.CHUNKS to it.toString() },
outcome.result?.optJSONObject("setup")?.let { UbisoftLaunch.SETUP to it.toString() },
),
)
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
return folder.path
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
}
internal companion object {
val KEPT = setOf("productId", "spaceId", "manifest", "appId")
/** A configured exe the way Windows finds it: any letter case, else the same file name anywhere in the install. */
fun resolve(folder: File, configured: String): String? {
val rel = configured.replace('\\', '/').trimStart('/').takeIf { it.isNotEmpty() } ?: return null
var at = folder
for (part in rel.split('/')) {
at = at.listFiles()?.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return byName(folder, rel.substringAfterLast('/'))
}
return if (at.isFile) at.relativeTo(folder).invariantSeparatorsPath else byName(folder, rel.substringAfterLast('/'))
}
private fun byName(folder: File, name: String): String? =
folder.walkTopDown().maxDepth(5).firstOrNull { it.isFile && it.name.equals(name, ignoreCase = true) }?.relativeTo(folder)?.invariantSeparatorsPath
}
}
@@ -0,0 +1,86 @@
package com.droiddeck.launcher.stores.ubisoft
import android.content.Context
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
/** What the launcher service hands a starting Ubisoft game: the account, its products and a fresh game ticket. */
object UbisoftLaunch {
private const val ENTITLEMENTS = "https://public-ubiservices.ubi.com/v1/profiles/me/global/ubiconnect/entitlement/api/entitlements"
private const val ME = "https://public-ubiservices.ubi.com/v3/users/me"
fun prepare(app: Context, id: String): JSONObject {
val folder = StoreInstallRoot.gameFolders(app).firstOrNull { f ->
StoreGameSidecar.read(f)?.let { it.store == Store.UBISOFT && it.id == id } == true
} ?: return failure("not-installed")
val sidecar = StoreGameSidecar.read(folder) ?: return failure("not-installed")
val product = sidecar.extra["productId"]?.toLongOrNull() ?: return failure("no-product")
val s = UbisoftAuth.current(app) ?: return failure("signed-out")
val native = UbisoftNative.call("launch", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId).put("productId", product))
?: return failure("engine-missing")
native.optString("error").takeIf { it.isNotEmpty() }?.let {
StoresState.logLine("Ubisoft: launch ticket for $product: $it")
return failure("ticket: $it")
}
val auth = "Ubi_v1 t=${s.ticket}"
val me = runCatching { UbisoftAuth.request(ME, "GET", auth, s.sessionId) }.getOrNull()?.takeIf { it.ok }
?.let { runCatching { JSONObject(it.body) }.getOrNull() }
val account = JSONObject()
.put("userId", s.userId)
.put("username", me?.optString("username")?.takeIf { it.isNotEmpty() } ?: s.name)
.put("nameOnPlatform", me?.optString("nameOnPlatform")?.takeIf { it.isNotEmpty() } ?: s.name)
.put("email", me?.optString("email").orEmpty())
.put("country", me?.optString("country")?.takeIf { it.isNotEmpty() } ?: "US")
val appId = runCatching { UbisoftAuth.request(ENTITLEMENTS, "GET", auth, s.sessionId) }.getOrNull()?.takeIf { it.ok }
?.let { applicationId(it.body, product) } ?: sidecar.extra["appId"].orEmpty()
StoresState.logLine("Ubisoft: launch ticket for $product ready (${native.optJSONArray("owned")?.length() ?: 0} products, appId ${if (appId.isEmpty()) "unknown" else "found"})")
val language = com.droiddeck.launcher.stores.StoreLanguage.localeFor(null, app).let { "${it.language}-${it.country}" }
val cached = sidecar.extra[CHUNKS]?.let { runCatching { JSONArray(it) }.getOrNull() }
var setup = sidecar.extra[SETUP]?.let { runCatching { JSONObject(it) }.getOrNull() }
val chunks = if (cached != null && setup != null) cached else
UbisoftNative.call("chunks", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId).put("productId", product)
.put("manifest", sidecar.extra["manifest"] ?: sidecar.installVersion).put("folder", folder.path).put("language", language))
?.let { r ->
r.optString("error").takeIf { it.isNotEmpty() }?.let { StoresState.logLine("Ubisoft: manifest for $product: $it") }
setup = r.optJSONObject("setup")
r.optJSONArray("chunks")
}?.also { c ->
runCatching {
StoreGameSidecar.read(folder)?.let { sc ->
sc.copy(extra = sc.extra + (CHUNKS to c.toString()) + listOfNotNull(setup?.let { SETUP to it.toString() })).write(folder)
}
com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, Store.UBISOFT, id)
?.let { com.droiddeck.launcher.frontend.AutoComponents.refreshLater(app, it) }
}
} ?: cached
setup?.let { StoresState.logLine("Ubisoft: setup for $product: ${it.toString().take(1500)}") }
UbisoftActivation.watch(app, product)
return JSONObject().put("ok", true)
.put("productId", product)
.put("ticket", native.optString("ticket"))
.put("owned", native.optJSONArray("owned") ?: JSONArray())
.put("products", native.optJSONArray("products") ?: JSONArray())
.put("account", account)
.put("appId", appId)
.put("language", language)
.put("chunks", chunks ?: JSONArray())
.put("registry", setup?.optJSONArray("registry") ?: JSONArray())
}
const val CHUNKS = "chunks"
const val SETUP = "setup"
/** The entitlement's `applicationId` for the product; the list sits under one of a few keys depending on the API version. */
internal fun applicationId(body: String, product: Long): String? {
val root = runCatching { JSONObject(body) }.getOrNull() ?: return null
val list = sequenceOf("items", "entitlements", "products", "games", "results").firstNotNullOfOrNull { root.optJSONArray(it) } ?: return null
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }
.firstOrNull { it.optLong("productId") == product }?.optString("applicationId")?.takeIf { it.isNotEmpty() }
}
private fun failure(reason: String) = JSONObject().put("ok", false).put("reason", reason)
}
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.stores.ubisoft
import android.util.Log
import com.droiddeck.launcher.stores.StoresNative
import com.droiddeck.launcher.stores.amazon.AmazonNative
import org.json.JSONObject
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object UbisoftNative {
private const val TAG = "UbisoftNative"
const val ENGINE_MISSING = "Ubisoft: the store engine is not available"
fun ready(): Boolean = StoresNative.ensureLoaded()
fun call(op: String, request: JSONObject): JSONObject? {
if (!ready()) return null
val text = try { nativeCall(op, request.toString()) } catch (t: Throwable) {
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
null
} ?: return null
return runCatching { JSONObject(text) }.getOrNull()
}
fun install(request: JSONObject, events: AmazonNative.InstallListener, cancelled: AtomicBoolean): AmazonNative.InstallOutcome {
if (!ready()) return AmazonNative.InstallOutcome(false, false, ENGINE_MISSING, null)
val done = CountDownLatch(1)
val holder = arrayOfNulls<AmazonNative.InstallOutcome>(1)
val bridge = object : AmazonNative.InstallListener by events {
override fun onComplete(success: Boolean, cancelled: Boolean, error: String, result: String) {
holder[0] = AmazonNative.InstallOutcome(success, cancelled, error, result.takeIf { it.isNotEmpty() }?.let { runCatching { JSONObject(it) }.getOrNull() })
done.countDown()
}
}
val handle = try { nativeInstall(request.toString(), bridge) } catch (t: Throwable) {
return AmazonNative.InstallOutcome(false, false, "The Ubisoft install could not start: ${t.javaClass.simpleName}", null)
}
if (handle == 0L) return holder[0] ?: AmazonNative.InstallOutcome(false, false, "The Ubisoft install could not start", null)
try {
var forwarded = false
while (true) {
val finished = try { done.await(250, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { cancelled.set(true); false }
if (finished) break
if (!forwarded && cancelled.get()) { nativeCancel(handle); forwarded = true }
}
} finally {
nativeRelease(handle)
}
return holder[0] ?: AmazonNative.InstallOutcome(false, false, "The Ubisoft install ended without a result", null)
}
@JvmStatic private external fun nativeCall(op: String, request: String): String?
@JvmStatic private external fun nativeInstall(request: String, listener: AmazonNative.InstallListener): Long
@JvmStatic private external fun nativeCancel(handle: Long)
@JvmStatic private external fun nativeRelease(handle: Long)
}
@@ -64,15 +64,32 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
if (root <= 0 || pid <= 0) return null
val status = java.io.File("/proc/$pid/status").readLines()
val tracer = status.first { it.startsWith("TracerPid:") }.substringAfter(':').trim().toInt()
val tracerGroup = java.io.File("/proc/$tracer/status").readLines()
.first { it.startsWith("Tgid:") }.substringAfter(':').trim().toInt()
if (tracerGroup != root) return null
if (tracer != 0) {
// under proot, every guest process is traced by the proot the app started
val tracerGroup = java.io.File("/proc/$tracer/status").readLines()
.first { it.startsWith("Tgid:") }.substringAfter(':').trim().toInt()
if (tracerGroup != root) return null
} else if (!descendsFrom(pid, root)) {
// without proot, the process the app started is the backend itself (or its parent)
return null
}
val executable = android.system.Os.stat(binary.path)
if (!mapsBackend(java.io.File("/proc/$pid/maps").readText(), binary.path, executable.st_ino))
return null
return java.io.File("/proc/$pid/stat").readText().substringAfterLast(") ").split(' ')[19] + ":${executable.st_dev}:${executable.st_ino}"
}
private fun descendsFrom(pid: Int, root: Int): Boolean {
var current = pid
repeat(32) {
if (current == root) return true
if (current <= 1) return false
current = java.io.File("/proc/$current/status").readLines()
.firstOrNull { it.startsWith("PPid:") }?.substringAfter(':')?.trim()?.toIntOrNull() ?: return false
}
return false
}
fun signalBackend(signal: Int) {
val process = backend ?: return
if (!process.isAlive) return
@@ -88,7 +88,8 @@ internal object Xodus {
val fastPathPreloaded = runCatching {
File(root, "etc/ld.so.preload").useLines { lines -> lines.any { it.trim() == ProotFastPath.LIBRARY } }
}.getOrDefault(false)
val fastPathKey = if (ProotFastPath.enabled(app) && fastPathPreloaded &&
val native = com.droiddeck.launcher.runtime.NativeGuest.forSession(app)
val fastPathKey = if (!native && ProotFastPath.enabled(app) && fastPathPreloaded &&
File(root, ProotFastPath.LIBRARY.removePrefix("/")).isFile) ProotFastPath.key(root, binds) else null
val guestCommand = mutableListOf(
"/usr/bin/env", "HOME=/root", "XODUS_LOG=off", "RUST_LOG=off",
@@ -98,12 +99,12 @@ internal object Xodus {
guestCommand.addAll(guestCommand.lastIndex, ProotFastPath.guestEnv(root, binds, key))
}
guestCommand.addAll(args)
val command = LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)
val builder = ProcessBuilder(command).directory(LinuxRuntime.rootDir(app))
val builder = if (native) com.droiddeck.launcher.runtime.NativeGuest.processBuilder(app, root, binds, guestCommand)
else ProcessBuilder(LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)).directory(LinuxRuntime.rootDir(app))
if (launchDirectory != null) builder.environment()["TMPDIR"] = launchDirectory.path
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_PORT"] = credentials.port.toString()
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_KEY"] = credentials.key
builder.environment().apply {
if (!native) builder.environment().apply {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
@@ -0,0 +1,307 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.ErrorOutline
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.Psychology
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
@Composable
internal fun AgentEntry(entry: Entry, running: Boolean, last: Boolean = false) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
when (entry) {
is Entry.Asked -> Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (entry.files.isNotEmpty()) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { entry.files.forEach { AttachmentChip(it, null) } }
if (entry.text.isNotEmpty()) SelectionContainer {
Text(entry.text, fontSize = 15.sp, color = pal.onPrimary,
modifier = Modifier.widthIn(max = 560.dp).clip(Shape16).background(pal.primary).padding(horizontal = 14.dp, vertical = 10.dp))
}
}
is Entry.Said -> SelectionContainer { AgentMarkdown(entry.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) }
is Entry.Thought -> AgentThought(entry.text, live = false)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running)
is Entry.Result -> Unit
is Entry.Finished -> if (last && AgentHost.answerless(AgentHost.entries)) AgentNoReply() else AgentTurnEnd(entry)
}
}
@Composable
private fun AgentTurnEnd(entry: Entry.Finished) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val text = when {
entry.stopped -> stringResource(R.string.agent_stopped)
entry.error != null -> stringResource(R.string.agent_failed, entry.error)
else -> entry.usage?.let { u ->
buildList {
if (u.durationMs > 0) add(clock(u.durationMs / 1000))
if (u.costUsd >= 0.005) add("$" + String.format(java.util.Locale.US, "%.2f", u.costUsd))
if (u.inputTokens > 0 || u.outputTokens > 0) add(stringResource(R.string.agent_tokens, tokens(u.inputTokens), tokens(u.outputTokens)))
}.joinToString(" · ")
}
} ?: return
if (text.isEmpty()) return
Text(text, fontSize = 12.sp, color = if (entry.error != null && !entry.stopped) colors.error else pal.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 4.dp))
}
@Composable
private fun AgentNoReply() {
val context = LocalContext.current
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.padding(horizontal = 4.dp)) {
Text(stringResource(R.string.agent_no_reply), fontSize = 13.sp, color = AttentionAmber)
SecondaryButton(stringResource(R.string.agent_retry), compact = true) { AgentHost.retry(context) }
}
}
internal fun tokens(n: Long) = if (n >= 1000) "${n / 1000}k" else n.toString()
@Composable
internal fun AgentThought(text: String, live: Boolean) {
val pal = LocalPalette.current
var open by rememberSaveable(text.take(40)) { mutableStateOf(false) }
Column(Modifier.padding(horizontal = 4.dp).animateContentSize()) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clip(Shape12).clickable { open = !open }.padding(vertical = 4.dp)) {
Icon(Icons.Outlined.Psychology, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
Text(stringResource(if (live) R.string.agent_thinking else R.string.agent_thought), fontSize = 13.sp, color = pal.onSurfaceVariant,
modifier = Modifier.padding(start = 6.dp))
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
if (open || live) Text(
if (open) text else text.takeLast(240), fontSize = 13.sp, fontStyle = FontStyle.Italic, color = pal.onSurfaceVariant, lineHeight = 19.sp,
maxLines = if (open) Int.MAX_VALUE else 3, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 760.dp).padding(start = 22.dp),
)
}
}
@Composable
private fun AgentTodos(list: String) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
Column(
Modifier.widthIn(max = 560.dp).padding(horizontal = 4.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
for (line in list.lines().filter { it.isNotBlank() }) {
val done = line.startsWith("[x]")
val doing = line.startsWith("[~]")
Row(verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(14.dp).clip(Shape12).background(when {
done -> pal.good
doing -> pal.primary
else -> pal.line
}))
Text(line.drop(4), fontSize = 13.sp, color = if (done) pal.onSurfaceVariant else colors.onSurface,
fontWeight = if (doing) FontWeight.SemiBold else null, modifier = Modifier.padding(start = 8.dp))
}
}
}
}
/** A tool call: one line with its status, opening to the full input and output. */
@Composable
private fun AgentToolCall(entry: Entry.Used, running: Boolean) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var open by rememberSaveable(entry.id.ifEmpty { entry.detail }) { mutableStateOf(false) }
Column(
Modifier.fillMaxWidth().padding(horizontal = 4.dp).clip(Shape12).background(pal.surfaceVariant).animateContentSize(),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().clickable { open = !open }.testTag("agent-tool").padding(horizontal = 10.dp, vertical = 8.dp),
) {
Box(Modifier.size(16.dp), contentAlignment = Alignment.Center) {
when {
running -> CircularProgressIndicator(Modifier.size(13.dp), strokeWidth = 2.dp, color = pal.primary)
entry.failed -> Icon(Icons.Outlined.ErrorOutline, null, tint = colors.error, modifier = Modifier.size(16.dp))
entry.output != null -> Icon(Icons.Outlined.CheckCircle, null, tint = pal.good, modifier = Modifier.size(16.dp))
else -> Icon(Icons.Outlined.Close, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
Text(entry.tool, fontSize = 12.5.sp, fontWeight = FontWeight.SemiBold, color = pal.primary, modifier = Modifier.padding(start = 8.dp))
Text(entry.detail, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).padding(start = 8.dp))
Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
if (open) Column(Modifier.padding(start = 10.dp, end = 10.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (entry.input.isNotBlank()) CodeBox(stringResource(R.string.agent_tool_input), entry.input, colors.onSurface)
when {
entry.output == null && running -> Text(stringResource(R.string.agent_tool_running), fontSize = 12.sp, color = pal.onSurfaceVariant)
entry.output == null -> Text(stringResource(R.string.agent_tool_no_result), fontSize = 12.sp, color = pal.onSurfaceVariant)
entry.output.isBlank() -> Text(stringResource(R.string.agent_tool_empty), fontSize = 12.sp, color = pal.onSurfaceVariant)
else -> CodeBox(stringResource(R.string.agent_tool_output), entry.output, if (entry.failed) colors.error else colors.onSurface)
}
}
}
}
@Composable
private fun CodeBox(label: String, text: String, color: Color) {
val pal = LocalPalette.current
Column {
Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = pal.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp))
SelectionContainer {
Text(
text, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = color, lineHeight = 17.sp,
modifier = Modifier.fillMaxWidth().heightIn(max = 360.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface)
.verticalScroll(rememberScrollState()).padding(10.dp),
)
}
}
}
/** An attached file: a thumbnail for images, the name otherwise; [onRemove] adds a remove mark. */
@Composable
internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) {
val context = LocalContext.current
val pal = LocalPalette.current
Box {
if (AgentAttachments.isImage(path)) AsyncImage(
model = AgentAttachments.host(context, path), contentDescription = path.substringAfterLast('/'), contentScale = ContentScale.Crop,
modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant),
) else Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.heightIn(min = 40.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 10.dp, vertical = 8.dp),
) {
Icon(Icons.Outlined.Description, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
Text(path.substringAfterLast('/'), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurface, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 200.dp).padding(start = 6.dp, end = if (onRemove != null) 18.dp else 0.dp))
}
if (onRemove != null) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.align(Alignment.TopEnd).padding(3.dp).size(20.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface).clickable(onClick = onRemove),
) {
Icon(Icons.Outlined.Close, stringResource(R.string.agent_remove_attachment), tint = pal.onSurfaceVariant, modifier = Modifier.size(14.dp))
}
}
}
/** The Markdown agents write: headings, lists, fenced code, `code` and **bold**. */
@Composable
internal fun AgentMarkdown(text: String, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
for (block in markdownBlocks(text)) when (block) {
is MdBlock.Code -> Text(block.text, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface,
modifier = Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(12.dp))
is MdBlock.Line -> Text(
inlineMarkdown(block.text, pal.primary2, pal.surfaceVariant),
fontSize = if (block.heading) 17.sp else 15.sp,
fontWeight = if (block.heading) FontWeight.Bold else null,
lineHeight = 22.sp, color = colors.onSurface,
modifier = if (block.bullet) Modifier.padding(start = 12.dp) else Modifier,
)
}
}
}
internal sealed interface MdBlock {
data class Line(val text: String, val heading: Boolean = false, val bullet: Boolean = false) : MdBlock
data class Code(val text: String) : MdBlock
}
private val HEADING = Regex("^#{1,6}\\s+")
private val BULLET = Regex("^\\s*[-*+]\\s+")
internal fun markdownBlocks(text: String): List<MdBlock> {
val out = mutableListOf<MdBlock>()
val code = StringBuilder()
var inCode = false
for (raw in text.lines()) {
if (raw.trimStart().startsWith("```")) {
if (inCode) {
out += MdBlock.Code(code.toString().trimEnd('\n'))
code.clear()
}
inCode = !inCode
continue
}
if (inCode) {
code.append(raw).append('\n')
continue
}
val line = raw.trimEnd()
if (line.isBlank()) continue
val heading = HEADING.find(line)
val bullet = BULLET.find(line)
out += when {
heading != null -> MdBlock.Line(line.substring(heading.range.last + 1), heading = true)
bullet != null -> MdBlock.Line("• " + line.substring(bullet.range.last + 1), bullet = true)
else -> MdBlock.Line(line)
}
}
if (inCode && code.isNotEmpty()) out += MdBlock.Code(code.toString().trimEnd('\n'))
return out
}
internal fun inlineMarkdown(text: String, codeColor: Color, codeBackground: Color): AnnotatedString = buildAnnotatedString {
var i = 0
while (i < text.length) {
val boldEnd = if (text.startsWith("**", i)) text.indexOf("**", i + 2) else -1
val tickEnd = if (text[i] == '`') text.indexOf('`', i + 1) else -1
when {
boldEnd > i + 2 -> {
withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { append(text, i + 2, boldEnd) }
i = boldEnd + 2
}
tickEnd > i + 1 -> {
withStyle(SpanStyle(fontFamily = FontFamily.Monospace, color = codeColor, background = codeBackground)) { append(text, i + 1, tickEnd) }
i = tickEnd + 1
}
else -> append(text[i++])
}
}
}
@@ -0,0 +1,393 @@
package com.droiddeck.launcher.ui
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.AttachFile
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Memory
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Stop
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentHost.Entry
import com.droiddeck.launcher.agent.AgentSetup
internal enum class AgentPanel { NONE, MODEL, HISTORY, PROCESSES }
/** Slash commands the app handles itself; others go to the CLI, which has its own. */
private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop")
private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init")
@Composable
internal fun AgentPage(modifier: Modifier, inputModifier: Modifier = Modifier, visible: Boolean = true) {
val context = LocalContext.current
remember { AgentHost.refresh(context) }
LaunchedEffect(AgentHost.unseen, visible) { if (visible) AgentHost.seen() }
remember { AgentSetup.check(context) }
var setup by rememberSaveable { mutableStateOf(false) }
val draft = rememberSaveable { mutableStateOf("") }
if (setup || AgentHost.state == AgentHost.State.MISSING || !(AgentSetup.ready || AgentSetup.completed(context))) {
AgentSetupView(modifier, onDone = { setup = false })
return
}
var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) }
Column(modifier.fillMaxSize()) {
AgentHeader(panel, { panel = if (panel == it) AgentPanel.NONE else it }, onSetup = { setup = true })
when (panel) {
AgentPanel.HISTORY -> AgentHistory(Modifier.weight(1f)) { panel = AgentPanel.NONE }
AgentPanel.PROCESSES -> AgentProcessList(Modifier.weight(1f))
else -> {
if (panel == AgentPanel.MODEL) AgentModelPicker()
AgentConversation(Modifier.weight(1f))
AgentStatus()
AgentComposer(draft, inputModifier) { panel = it }
}
}
}
}
@Composable
private fun AgentHeader(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, onSetup: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.rail_agent), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
val model = AgentHost.models(context).firstOrNull { it.id == AgentHost.model }?.label ?: AgentHost.model ?: stringResource(R.string.agent_model_default)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clip(Shape12).clickable { onPanel(AgentPanel.MODEL) }.padding(vertical = 2.dp).testTag("agent-model"),
) {
val parts = listOfNotNull(AgentHost.harness.name, model, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans })
Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant)
Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
}
HeaderAction(Icons.Outlined.History, stringResource(R.string.agent_history), selected = panel == AgentPanel.HISTORY, tag = "agent-history") { onPanel(AgentPanel.HISTORY) }
HeaderAction(Icons.Outlined.Memory, stringResource(R.string.agent_processes), selected = panel == AgentPanel.PROCESSES, tag = "agent-processes") { onPanel(AgentPanel.PROCESSES) }
HeaderAction(Icons.Outlined.Add, stringResource(R.string.agent_new), enabled = !working && AgentHost.entries.isNotEmpty(), tag = "agent-new") {
AgentHost.forget(context)
if (panel != AgentPanel.NONE) onPanel(panel)
}
HeaderAction(Icons.Outlined.Settings, stringResource(R.string.agent_setup_title), enabled = !working, tag = "agent-settings", onClick = onSetup)
}
}
@Composable
internal fun HeaderAction(icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, onClick: () -> Unit) {
val pal = LocalPalette.current
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 8.dp).size(44.dp).clip(Shape12)
.background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
.clickable(enabled = enabled, onClick = onClick)
.then(if (tag != null) Modifier.testTag(tag) else Modifier),
) {
Icon(icon, label, tint = when {
selected -> pal.primary
enabled -> pal.onBackground
else -> pal.onSurfaceVariant.copy(alpha = 0.5f)
}, modifier = Modifier.size(22.dp))
}
}
@Composable
private fun AgentConversation(modifier: Modifier) {
val pal = LocalPalette.current
val list = rememberLazyListState()
val working = AgentHost.state == AgentHost.State.WORKING
val atBottom by remember { derivedStateOf { !list.canScrollForward } }
val items = AgentHost.entries.size + (if (working) 1 else 0)
LaunchedEffect(items) { if (items > 0) list.animateScrollToItem(items - 1) }
LaunchedEffect(AgentHost.live.length / 80, AgentHost.liveThinking.length / 80) {
if (atBottom && items > 0) list.scrollToItem(items - 1, Int.MAX_VALUE / 2)
}
if (AgentHost.entries.isEmpty() && !working) {
Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Icon(Icons.Outlined.AutoAwesome, null, tint = pal.primary, modifier = Modifier.size(40.dp))
Text(stringResource(R.string.agent_empty), fontSize = 15.sp, color = pal.onSurfaceVariant,
textAlign = TextAlign.Center, modifier = Modifier.widthIn(max = 460.dp).padding(top = 12.dp))
}
return
}
val start = AgentHost.entries.indexOfLast { it is Entry.Asked }
LazyColumn(modifier.fillMaxWidth(), state = list, verticalArrangement = Arrangement.spacedBy(10.dp)) {
items(AgentHost.entries.size) { i ->
val entry = AgentHost.entries[i]
AgentEntry(entry, running = working && i > start && entry is Entry.Used && entry.output == null, last = !working && i == AgentHost.entries.lastIndex)
}
if (working) item { AgentLive() }
}
}
/** The reply being written, and what the agent is doing right now. */
@Composable
private fun AgentLive() {
val pal = LocalPalette.current
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (AgentHost.liveThinking.isNotBlank()) AgentThought(AgentHost.liveThinking, live = true)
if (AgentHost.live.isNotBlank()) AgentMarkdown(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp))
val running = AgentHost.running()
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(4.dp)) {
CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp, color = pal.primary)
val elapsed = clock((AgentHost.now - AgentHost.turnStarted) / 1000)
Text(
if (running != null) stringResource(R.string.agent_running, running.tool, elapsed) else stringResource(R.string.agent_thinking_for, elapsed),
fontSize = 13.sp, color = pal.onSurfaceVariant,
)
}
}
}
internal fun clock(seconds: Long): String {
val s = seconds.coerceAtLeast(0)
return when {
s < 60 -> "${s}s"
s < 3600 -> "${s / 60}m ${s % 60}s"
else -> "${s / 3600}h ${s % 3600 / 60}m"
}
}
/** Above the composer: a Lab build's progress, the todo item in progress, and queued messages. */
@Composable
private fun AgentStatus() {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val lab = AgentHost.lab
if (lab != null) {
var armed by remember(lab.pid) { mutableStateOf(false) }
Column(
Modifier.fillMaxWidth().padding(top = 10.dp).clip(Shape14).background(colors.surface).border(1.dp, if (lab.failed) AttentionAmber else pal.line, Shape14)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-lab"),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(
stringResource(if (lab.prepare) R.string.agent_lab_preparing else R.string.agent_lab_building) + " · " + labStage(lab),
fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (lab.failed) AttentionAmber else colors.onBackground,
)
val facts = buildList {
if (lab.running && lab.total > 0) add("${lab.done}/${lab.total}")
add(clock(lab.elapsedSeconds.toLong()))
if (lab.running && lab.etaSeconds >= 0) add(stringResource(R.string.agent_lab_left, clock(lab.etaSeconds.toLong())))
}
Text(facts.joinToString(" · "), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
if (lab.running) SecondaryButton(stringResource(if (armed) R.string.agent_lab_cancel_confirm else R.string.agent_lab_cancel), compact = true) {
if (armed) AgentHost.cancelLabBuild(context) else armed = true
}
}
if (lab.running) {
LinearProgressIndicator(
progress = { lab.permille / 1000f }, color = pal.primary, trackColor = pal.surfaceVariant,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape),
)
if (lab.task.isNotEmpty()) Text(lab.task, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp))
}
}
}
val todos = AgentHost.todos()?.lines()?.filter { it.isNotBlank() }
if (AgentHost.state == AgentHost.State.WORKING && !todos.isNullOrEmpty()) {
val doing = todos.firstOrNull { it.startsWith("[~]") } ?: todos.firstOrNull { it.startsWith("[ ]") }
val done = todos.count { it.startsWith("[x]") }
if (doing != null) Text(
"${doing.drop(4)} · $done/${todos.size}", fontSize = 13.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 8.dp, start = 4.dp),
)
}
for (queued in AgentHost.queue) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(start = 12.dp),
) {
Text(stringResource(R.string.agent_queued, queued.text), fontSize = 13.sp, color = pal.onSurfaceVariant, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).clickable { AgentHost.unqueue(queued) }) {
Icon(Icons.Outlined.Close, stringResource(R.string.agent_unqueue), tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp))
}
}
}
}
@Composable
private fun labStage(lab: com.droiddeck.launcher.agent.LabProgress) = when (lab.stage) {
"building" -> stringResource(R.string.agent_lab_stage_building, lab.permille / 10)
"packaging" -> stringResource(R.string.agent_lab_stage_packaging)
"restarting" -> stringResource(R.string.agent_lab_stage_restarting)
"ready", "prepared" -> stringResource(R.string.agent_lab_stage_ready)
"failed" -> stringResource(R.string.agent_lab_stage_failed, lab.task)
else -> stringResource(R.string.agent_lab_stage_starting)
}
@Composable
private fun AgentComposer(draftState: MutableState<String>, inputModifier: Modifier, onPanel: (AgentPanel) -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var draft by draftState
val working = AgentHost.state == AgentHost.State.WORKING
val send = send@{
val text = draft.trim()
when (text.substringBefore(' ')) {
"/new" -> AgentHost.forget(context)
"/model" -> onPanel(AgentPanel.MODEL)
"/plan" -> AgentHost.choosePlan(context, !AgentHost.plan)
"/history" -> onPanel(AgentPanel.HISTORY)
"/processes" -> onPanel(AgentPanel.PROCESSES)
"/stop" -> AgentHost.stop(context)
else -> {
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
AgentHost.send(context, text, AgentAttachments.pending.toList())
AgentAttachments.pending.clear()
}
}
draft = ""
}
if (draft.startsWith("/") && !draft.contains(' ')) {
val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft }
if (matches.isNotEmpty()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) {
for (command in matches) Text(
command, fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = pal.primary,
modifier = Modifier.clip(Shape12).background(pal.surfaceVariant).clickable { draft = "$command " }.padding(horizontal = 12.dp, vertical = 8.dp),
)
}
}
if (AgentAttachments.pending.isNotEmpty()) Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(top = 10.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) {
for (path in AgentAttachments.pending.toList()) AttachmentChip(path) { AgentAttachments.pending.remove(path) }
}
var focused by remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.Bottom,
modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 16.dp).clip(Shape16).background(colors.surface)
.border(1.dp, if (focused) pal.primary else pal.line, Shape16).padding(start = 6.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
) {
if (LocalActivityResultRegistryOwner.current != null) AttachButton()
Box(Modifier.weight(1f).padding(start = 8.dp, top = 11.dp, bottom = 11.dp)) {
if (draft.isEmpty()) Text(
stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp,
color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
BasicTextField(
draft, { draft = it },
Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }.testTag("agent-input").then(inputModifier),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
cursorBrush = SolidColor(pal.primary),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(onSend = { send() }),
maxLines = 6,
)
}
if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") {
AgentHost.stop(context)
}
val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty()
RoundButton(
Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send),
if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend,
) { send() }
}
}
@Composable
private fun AttachButton() {
val context = LocalContext.current
val pal = LocalPalette.current
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uris.isEmpty()) return@rememberLauncherForActivityResult
val chat = AgentHost.chat
Thread({
val paths = AgentAttachments.copy(context, chat, uris)
android.os.Handler(android.os.Looper.getMainLooper()).post {
if (AgentHost.chat == chat) AgentAttachments.pending.addAll(paths) else AgentAttachments.discard(context, paths)
}
}, "agent-attach").start()
}
RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") {
runCatching { picker.launch(arrayOf("*/*")) }
}
}
@Composable
private fun RoundButton(
icon: ImageVector, label: String, background: androidx.compose.ui.graphics.Color, tint: androidx.compose.ui.graphics.Color,
tag: String, enabled: Boolean = true, onClick: () -> Unit,
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = 6.dp).size(46.dp).clip(CircleShape).background(background)
.clickable(enabled = enabled, onClick = onClick).testTag(tag),
) {
Icon(icon, label, tint = tint, modifier = Modifier.size(22.dp))
}
}
@@ -0,0 +1,182 @@
package com.droiddeck.launcher.ui
import android.text.format.DateUtils
import android.text.format.Formatter
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentChats
import com.droiddeck.launcher.agent.AgentHarness
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentProcesses
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
/** The model and plan mode for the next turns; a conversation keeps going with whatever is chosen. */
@Composable
internal fun AgentModelPicker() {
val context = LocalContext.current
val pal = LocalPalette.current
val models = remember(AgentHost.harness) { AgentHost.models(context) }
Column(Modifier.fillMaxWidth().padding(bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) {
val choices = listOf(AgentHarness.Model("", stringResource(R.string.agent_model_default))) + models
for (choice in choices) {
val id = choice.id.ifEmpty { null }
if (id == AgentHost.model) PrimaryButton(choice.label, compact = true) {}
else SecondaryButton(choice.label, compact = true) { AgentHost.chooseModel(context, id) }
}
}
if (AgentHost.harness.plans) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.agent_plan), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
Text(stringResource(R.string.agent_plan_hint), fontSize = 12.5.sp, color = pal.onSurfaceVariant)
}
ToggleSwitch(AgentHost.plan, label = stringResource(R.string.agent_plan)) { AgentHost.choosePlan(context, it) }
}
}
}
@Composable
internal fun AgentHistory(modifier: Modifier, onOpened: () -> Unit) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var version by remember { mutableIntStateOf(0) }
val chats by produceState(emptyList<AgentChats.Chat>(), version, AgentHost.entries.size) {
value = withContext(Dispatchers.IO) { AgentChats.list(context) }
}
if (chats.isEmpty()) {
Box(modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.agent_history_empty), fontSize = 15.sp, color = pal.onSurfaceVariant)
}
return
}
val working = AgentHost.state == AgentHost.State.WORKING
LazyColumn(modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
items(chats, key = { it.id }) { chat ->
var armed by remember(chat.id) { mutableStateOf(false) }
val current = chat.id == AgentHost.chat
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 62.dp)
.clickable(enabled = !working || current) {
AgentHost.open(context, chat.id)
onOpened()
}
.background(if (current) pal.primary.copy(alpha = 0.12f) else colors.surface)
.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-chat"),
) {
Column(Modifier.weight(1f)) {
Text(chat.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (armed) stringResource(R.string.agent_history_delete_warning)
else AgentHarness.byId(chat.harness).name + " · " + when {
System.currentTimeMillis() - chat.updated < 60_000 -> stringResource(R.string.agent_just_now)
else -> DateUtils.getRelativeTimeSpanString(chat.updated, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString()
},
fontSize = 12.5.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_history_delete), compact = true,
enabled = !(current && working),
) {
if (armed) {
AgentHost.delete(context, chat.id)
version++
} else armed = true
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
}
/** Processes in the Linux userland, the agent's own first, each with a way to end it. */
@Composable
internal fun AgentProcessList(modifier: Modifier) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var refresh by remember { mutableIntStateOf(0) }
var procs by remember { mutableStateOf<List<AgentProcesses.Proc>?>(null) }
LaunchedEffect(refresh) {
while (true) {
procs = withContext(Dispatchers.IO) { AgentProcesses.snapshot(AgentHost.turnPid) }
delay(2_000)
}
}
val list = procs ?: return
if (list.isEmpty()) {
Box(modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.agent_processes_empty), fontSize = 15.sp, color = pal.onSurfaceVariant)
}
return
}
LazyColumn(modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
items(list, key = { it.pid }) { proc ->
var open by remember(proc.pid) { mutableStateOf(false) }
Column(Modifier.fillMaxWidth().clickable { open = !open }.padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-process")) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(proc.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (proc.agent) Text(stringResource(R.string.agent_process_agent), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = pal.primary,
modifier = Modifier.clip(Shape12).background(pal.primary.copy(alpha = 0.15f)).padding(horizontal = 6.dp, vertical = 1.dp))
}
Text(
listOf("pid ${proc.pid}", clock(proc.seconds), Formatter.formatShortFileSize(context, proc.rssKb * 1024), "${proc.cpuPercent}% CPU").joinToString(" · "),
fontSize = 12.5.sp, color = pal.onSurfaceVariant,
)
}
SecondaryButton(stringResource(R.string.agent_process_stop), compact = true) {
AgentProcesses.killTree(proc.pid)
refresh++
}
}
SelectionContainer {
Text(proc.args, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant,
maxLines = if (open) 40 else 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp))
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
}
@@ -0,0 +1,215 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.PairingGuideActivity
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentHarness
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.agent.AgentSetup
import com.droiddeck.launcher.agent.AgentStorage
import android.text.format.Formatter
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import com.droiddeck.launcher.agent.AgentSetup.Status
import com.droiddeck.launcher.agent.AgentSetup.Step
import com.droiddeck.launcher.core.WirelessAdbPairingService
@Composable
internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
LaunchedEffect(AgentHost.harness) {
AgentSetup.check(context)
AgentStorage.measure(context)
}
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
var left = false
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_PAUSE) left = true
if (event == Lifecycle.Event.ON_RESUME && left) {
left = false
AgentSetup.check(context)
}
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(14.dp)) {
Text(stringResource(R.string.agent_setup_title), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
if (!AgentSetup.runtimeInstalled) {
Note(stringResource(R.string.agent_setup_runtime))
return@Column
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
for (harness in AgentHarness.all) {
val chosen = harness == AgentHost.harness
if (chosen) PrimaryButton(harness.name, compact = true) {} else SecondaryButton(harness.name, enabled = !AgentSetup.busy, compact = true) { AgentHost.choose(context, harness) }
}
}
val steps = Step.entries
val done = steps.count { AgentSetup.status[it] == Status.DONE }
val busy = steps.any { AgentSetup.status[it] == Status.WORKING }
var details by rememberSaveable { mutableStateOf(false) }
val summary = if (AgentSetup.ready) buildList {
add(stringResource(R.string.agent_summary_signed_in, AgentHost.harness.name))
if (AgentSetup.status[Step.GITHUB] == Status.DONE) add(stringResource(R.string.agent_step_github))
if (AgentSetup.status[Step.BUILD_TOOLS] == Status.DONE) add(stringResource(R.string.agent_summary_lab))
if (AgentSetup.status[Step.PREPARE] == Status.DONE) add(stringResource(R.string.agent_summary_fast))
}.joinToString(" · ") else steps.firstOrNull { it.required && AgentSetup.status[it] != Status.DONE }?.let { labels(it, AgentHost.harness.name).first }.orEmpty()
ReadinessCard(
done, steps.size, summary, details || !AgentSetup.ready || busy, { details = !details },
title = stringResource(if (AgentSetup.ready) R.string.agent_summary_ready else R.string.agent_summary_not_ready),
ready = AgentSetup.ready,
) {
steps.forEachIndexed { index, step ->
val status = AgentSetup.status[step] ?: Status.UNKNOWN
val (title, hint) = labels(step, AgentHost.harness.name)
val lab = AgentHost.lab?.takeIf { it.prepare && it.running }
val detail = if (step == Step.PREPARE && lab != null)
stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0)))
else AgentSetup.detail[step] ?: hint
CheckRow(
when (status) {
Status.DONE -> CheckState.OK
Status.WORKING, Status.UNKNOWN -> CheckState.BUSY
Status.TODO, Status.FAILED -> CheckState.WARN
},
title, detail, divider = index < steps.lastIndex,
) {
val blocked = (step in setOf(Step.SIGN_IN, Step.GITHUB, Step.BUILD_TOOLS) && AgentSetup.status[Step.INSTALL] != Status.DONE) ||
(step == Step.PREPARE && AgentSetup.status[Step.BUILD_TOOLS] != Status.DONE)
if ((status == Status.TODO || status == Status.FAILED) && !blocked) {
val label = stringResource(if (status == Status.FAILED) R.string.agent_setup_retry else action(step))
val run = { if (step == Step.CONNECTION) pair(context) else AgentSetup.run(context, step) }
if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run)
}
}
}
}
if (AgentSetup.ready || AgentSetup.completed(context)) PrimaryButton(stringResource(R.string.agent_setup_done), main = true, onClick = onDone)
StorageCard()
}
}
@Composable
private fun StorageCard() {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val items = AgentStorage.Item.entries.filter { (AgentStorage.sizes[it] ?: 0L) > 0L }
if (items.isEmpty()) return
val total = items.sumOf { AgentStorage.sizes[it] ?: 0L }
var open by rememberSaveable { mutableStateOf(false) }
Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().heightIn(min = 60.dp).padding(horizontal = 14.dp, vertical = 10.dp)) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.agent_storage_title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(Formatter.formatShortFileSize(context, total), fontSize = 13.sp, color = pal.onSurfaceVariant)
}
SecondaryButton(stringResource(if (open) R.string.common_hide else R.string.setup_details), compact = true) { open = !open }
}
if (open) items.forEachIndexed { index, item ->
if (index == 0) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
var armed by remember(item) { mutableStateOf(false) }
val busy = AgentStorage.removing[item] == true
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 60.dp).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(stringResource(storageTitle(item)), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(
if (armed) stringResource(storageWarning(item)) else Formatter.formatShortFileSize(context, AgentStorage.sizes[item] ?: 0L),
fontSize = 13.sp, color = if (armed) AttentionAmber else pal.onSurfaceVariant,
)
}
SecondaryButton(
stringResource(if (armed) R.string.agent_storage_confirm else R.string.agent_storage_remove),
enabled = !busy && AgentHost.state != AgentHost.State.WORKING, compact = true,
) {
if (armed) {
armed = false
AgentStorage.remove(context, item)
} else armed = true
}
}
if (index < items.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
}
private fun storageTitle(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.CLAUDE_CODE -> R.string.agent_storage_claude
AgentStorage.Item.CODEX -> R.string.agent_storage_codex
AgentStorage.Item.BUILD_TOOLS -> R.string.agent_step_build
AgentStorage.Item.SOURCE -> R.string.agent_storage_source
AgentStorage.Item.CACHES -> R.string.agent_storage_caches
}
private fun storageWarning(item: AgentStorage.Item) = when (item) {
AgentStorage.Item.SOURCE -> R.string.agent_storage_source_warning
AgentStorage.Item.CACHES -> R.string.agent_storage_caches_warning
else -> R.string.agent_storage_reinstall_warning
}
@Composable
private fun labels(step: Step, harness: String): Pair<String, String> = when (step) {
Step.CONNECTION -> stringResource(R.string.agent_step_connection) to stringResource(R.string.agent_step_connection_hint)
Step.INSTALL -> stringResource(R.string.agent_step_install, harness) to stringResource(R.string.agent_step_install_hint)
Step.SIGN_IN -> stringResource(R.string.agent_step_sign_in, harness) to stringResource(R.string.agent_step_sign_in_hint)
Step.GITHUB -> stringResource(R.string.agent_step_github) to stringResource(R.string.agent_step_github_hint)
Step.BUILD_TOOLS -> stringResource(R.string.agent_step_build) to stringResource(R.string.agent_step_build_hint)
Step.PREPARE -> stringResource(R.string.agent_step_prepare) to stringResource(R.string.agent_step_prepare_hint)
}
private fun action(step: Step): Int = when (step) {
Step.CONNECTION -> R.string.agent_action_pair
Step.INSTALL -> R.string.agent_action_install
Step.SIGN_IN, Step.GITHUB -> R.string.agent_action_sign_in
Step.BUILD_TOOLS -> R.string.agent_action_install
Step.PREPARE -> R.string.agent_action_prepare
}
/** The pairing DroidDeck already uses for the phantom process fix; the agent reuses its key. */
private fun pair(context: android.content.Context) {
if (!WirelessAdbPairingService.notificationsEnabled(context)) {
context.startActivity(android.content.Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, context.packageName)
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
return
}
WirelessAdbPairingService.start(context)
PairingGuideActivity.start(context, null, false)
}
@@ -38,7 +38,8 @@ object BuildWatermark {
if (text.length <= TITLE_LIMIT) text else text.take(TITLE_LIMIT - 1).trimEnd() + "…"
fun install(app: Application) {
val lines = lines() ?: return
val lab = com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" }
val lines = (listOfNotNull(lab) + lines().orEmpty()).ifEmpty { return }
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
if (activity is QuestXrActivity) return
@@ -0,0 +1,17 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.ea.EaUpdates
@Composable
internal fun EaUpdateButton(installed: InstalledStoreGame, enabled: Boolean) {
val ctx = LocalContext.current
LaunchedEffect(installed.key, installed.sidecar.installVersion) { EaUpdates.check(ctx, installed) }
if (EaUpdates.available[installed.key] == null) return
SecondaryButton(stringResource(R.string.common_update), enabled = enabled) { EaUpdates.start(ctx, installed) }
}
@@ -270,6 +270,10 @@ private fun Content(
DesktopPage(s, a, modifier, onSelect)
return
}
if (selected == "agent") {
AgentPage(modifier.padding(horizontal = padH).padding(top = padV))
return
}
if (selected == "android-apps" && s.isHomeApp) {
AndroidAppsPage(s, modifier, onAndroidAppClick)
return
@@ -47,6 +47,7 @@ import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.LocalMall
@@ -123,7 +124,9 @@ internal fun BottomBar(
internal fun navigationKeys(s: FrontEndState) = buildList {
add("steam"); add("games")
if (s.gameStoresEnabled) add("stores")
add("desktop"); add("components")
add("desktop")
if (com.droiddeck.launcher.agent.AgentHost.available) add("agent")
add("components")
if (s.isHomeApp) add("android-apps")
add("setup"); add("updates")
}
@@ -156,7 +159,7 @@ internal fun SideRail(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp),
) {
val count = 6 + (if (s.gameStoresEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0)
val count = navigationKeys(s).size
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp)
val shown = Hops.railPreview ?: selected
@@ -197,6 +200,7 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
"stores" -> R.string.rail_stores to Icons.Outlined.LocalMall
"desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows
"components" -> R.string.rail_components to Icons.Outlined.Layers
"agent" -> R.string.rail_agent to Icons.Outlined.AutoAwesome
"android-apps" -> R.string.rail_apps to Icons.Outlined.Apps
"setup" -> R.string.rail_setup to Icons.Outlined.Tune
else -> R.string.rail_updates to Icons.Outlined.SystemUpdate
@@ -84,7 +84,7 @@ import com.droiddeck.launcher.stores.download.StoreDownloadTier
import com.droiddeck.launcher.R
private enum class CheckState { OK, WARN, BUSY }
internal enum class CheckState { OK, WARN, BUSY }
private const val STORAGE_TAB = 3
private const val LAUNCHER_TAB = 2
@@ -97,7 +97,7 @@ private const val GLASSES_TAB = 6
private const val SYNC_TAB = 4
@Composable
private fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
internal fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val tint = when (state) {
@@ -690,10 +690,12 @@ internal fun SetupPanel(
}
@Composable
private fun ReadinessCard(passing: Int, total: Int, line: String, open: Boolean, onDetails: () -> Unit, checks: @Composable () -> Unit) {
internal fun ReadinessCard(
passing: Int, total: Int, line: String, open: Boolean, onDetails: () -> Unit, title: String? = null, ready: Boolean = passing == total,
checks: @Composable () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val ready = passing == total
Column(Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
@@ -709,7 +711,7 @@ private fun ReadinessCard(passing: Int, total: Int, line: String, open: Boolean,
}
Column(Modifier.weight(1f)) {
Text(
stringResource(if (ready) R.string.setup_ready else R.string.setup_not_ready),
title ?: stringResource(if (ready) R.string.setup_ready else R.string.setup_not_ready),
fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
)
if (line.isNotEmpty()) Text(line, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
@@ -430,6 +430,7 @@ internal fun GameActions(
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
}
}
if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
if (store == Store.XBOX && installed != null && id != null) {
@@ -915,7 +916,7 @@ private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions)
@Composable
private fun CloudRows(g: Library.SteamGame) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON && it != Store.EA } ?: return
val id = g.storeId ?: return
val context = LocalContext.current.applicationContext
var busy by remember(g.gameId) { mutableStateOf<String?>(null) }
@@ -0,0 +1,162 @@
package com.droiddeck.launcher.ui
import android.text.format.DateUtils
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Code
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.WirelessAdbFix
import com.droiddeck.launcher.lab.LabOverlay
/**
* Lab builds on this device: the one in use, one waiting for a restart, and the kept ones.
* [onRebuild] offers to build a kept one again for this install, when something can.
*/
@Composable
internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.Info) -> Unit)? = null) {
val context = LocalContext.current
var version by remember { mutableIntStateOf(0) }
var busy by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
val current = remember(version) { LabOverlay.current(context) }
val pending = remember(version) { LabOverlay.pending(context) }
val saved = remember(version) { LabOverlay.saved(context) }
if (current == null && pending == null && saved.isEmpty()) return
val active = LabOverlay.active
val paused = active == null && current != null && LabOverlay.skipped == LabOverlay.SKIPPED_APP_IMAGE
val restartFailed = stringResource(R.string.lab_restart_failed)
val canRestart = !busy && !sessionRunning
/** Android may have given the APK an app image again, which a Lab build cannot load over. */
fun restart() {
busy = true
error = null
Thread({
val result = runCatching {
if (LabOverlay.needsRecompile(context)) WirelessAdbFix.shell(context, LabOverlay.recompileCommand(context))
}
android.os.Handler(android.os.Looper.getMainLooper()).post {
busy = false
if (result.isSuccess) LabOverlay.restart(context)
else error = restartFailed.format(result.exceptionOrNull()?.message.orEmpty())
}
}, "lab-restart").start()
}
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {
Text(
stringResource(R.string.lab_builds).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp),
)
Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
val rows = mutableListOf<@Composable () -> Unit>()
if (current != null) rows += {
BuildRow(
current, true,
when {
active != null -> stringResource(R.string.lab_in_use)
paused -> stringResource(R.string.lab_paused_row)
else -> stringResource(R.string.lab_not_loaded, LabOverlay.skipped.orEmpty())
},
warn = active == null,
) {
if (paused) PrimaryButton(stringResource(R.string.lab_restart), compact = true, enabled = canRestart) { restart() }
SecondaryButton(stringResource(R.string.lab_turn_off), compact = true, enabled = canRestart) { LabOverlay.turnOff(context) }
}
}
if (pending != null) rows += {
BuildRow(pending, false, stringResource(R.string.lab_waiting), warn = false) {
PrimaryButton(stringResource(R.string.lab_restart), compact = true, enabled = canRestart) { restart() }
}
}
for (build in saved) rows += {
var armed by remember(build.dir) { mutableStateOf(false) }
val info = build.info
BuildRow(
info, false,
when {
armed -> stringResource(R.string.lab_delete_warning)
!build.usable -> stringResource(R.string.lab_other_install)
build.reason == LabOverlay.Reason.DID_NOT_START -> stringResource(R.string.lab_off_did_not_start)
else -> stringResource(R.string.lab_kept)
},
warn = armed || !build.usable || build.reason == LabOverlay.Reason.DID_NOT_START,
) {
if (!build.usable && !armed && info != null && onRebuild != null) SecondaryButton(stringResource(R.string.lab_rebuild), compact = true, enabled = !busy) {
onRebuild(info)
}
if (build.usable && !armed) SecondaryButton(stringResource(R.string.lab_use), compact = true, enabled = canRestart) {
runCatching { LabOverlay.stage(context, build) }
.onSuccess { version++; restart() }
.onFailure { error = it.message }
}
SecondaryButton(stringResource(if (armed) R.string.lab_delete_confirm else R.string.lab_delete), compact = true, enabled = !busy) {
if (armed) {
LabOverlay.delete(build)
version++
} else armed = true
}
}
}
rows.forEachIndexed { index, row ->
row()
if (index < rows.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
error?.let { Text(it, fontSize = 12.5.sp, color = AttentionAmber, modifier = Modifier.padding(start = 2.dp, top = 8.dp)) }
}
}
@Composable
private fun BuildRow(info: LabOverlay.Info?, current: Boolean, status: String, warn: Boolean, actions: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 60.dp).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(34.dp).clip(Shape12)
.background(if (current) pal.signal.copy(alpha = 0.18f) else colors.surfaceVariant)) {
Icon(Icons.Outlined.Code, null, tint = if (current) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
Column(Modifier.weight(1f)) {
Text(info?.label ?: "?", fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis)
val built = info?.built?.takeIf { it > 0 }?.let { DateUtils.getRelativeTimeSpanString(it * 1000, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString() }
Text(listOfNotNull(status, built).joinToString(" · "), fontSize = 12.5.sp, color = if (warn) AttentionAmber else colors.onSurfaceVariant,
maxLines = 2, overflow = TextOverflow.Ellipsis)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { actions() }
}
}
@@ -742,7 +742,7 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?, showDownlo
}
}
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available } == true ||
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available || it in com.droiddeck.launcher.stores.ea.EaUpdates.available } == true ||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
@Composable
@@ -53,6 +53,7 @@ fun PerformancePage(
ramCapAvailable: Boolean,
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
cursorComposite: Boolean,
guestHostname: String,
phantomWarning: String?,
@@ -72,6 +73,7 @@ fun PerformancePage(
onVramCapMb: (Int) -> Unit,
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
onClientCore: (Int, Boolean) -> Unit,
@@ -187,9 +189,18 @@ fun PerformancePage(
)
ToggleRow(
host, "fastpath", stringResource(R.string.perf_fastpath),
if (prootNoSeccomp) stringResource(R.string.perf_fastpath_needs_seccomp)
else stringResource(R.string.perf_fastpath_hint),
prootFastPath && !prootNoSeccomp, enabled = !prootNoSeccomp, onChange = onProotFastPath,
when {
nativeUserland -> stringResource(R.string.perf_fastpath_needs_proot)
prootNoSeccomp -> stringResource(R.string.perf_fastpath_needs_seccomp)
else -> stringResource(R.string.perf_fastpath_hint)
},
prootFastPath && !prootNoSeccomp && !nativeUserland, enabled = !prootNoSeccomp && !nativeUserland,
onChange = onProotFastPath,
)
ToggleRow(
host, "nativeuserland", stringResource(R.string.perf_native_userland),
stringResource(R.string.perf_native_userland_hint),
nativeUserland, onChange = onNativeUserland,
)
ToggleRow(
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
@@ -9,12 +9,16 @@ internal enum class SessionDrawerPage(val firstControl: String) {
EFFECTS("look"),
VR("steamvr"),
GAMES("anisotropy"),
AGENT("agent-input"),
SESSION("suspend"),
}
internal fun sessionDrawerPages(hasSecondScreen: Boolean, hasGlasses: Boolean = false): List<SessionDrawerPage> =
internal fun sessionDrawerPages(
hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentHost.installed,
): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter {
(hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES)
(hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES) &&
(hasAgent || it != SessionDrawerPage.AGENT)
}
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
@@ -43,6 +43,7 @@ import androidx.compose.material.icons.outlined.PowerSettingsNew
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.AutoAwesome
import androidx.compose.material.icons.outlined.ScreenShare
import androidx.compose.material.icons.outlined.Pause
import androidx.compose.material.icons.outlined.PictureInPictureAlt
@@ -172,6 +173,7 @@ private val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.VR -> R.string.vr_title
SessionDrawerPage.EFFECTS -> R.string.drawer_page_effects
SessionDrawerPage.GAMES -> R.string.game_settings_title
SessionDrawerPage.AGENT -> R.string.rail_agent
SessionDrawerPage.SESSION -> R.string.mode_session
}
@@ -184,6 +186,7 @@ private val SessionDrawerPage.icon get() = when (this) {
SessionDrawerPage.VR -> VrHeadsetIcon
SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
SessionDrawerPage.AGENT -> Icons.Outlined.AutoAwesome
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
}
@@ -550,7 +553,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
glassesPages, glassesTab, modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
tabModifier = { key -> focus.track(page, "glasses-tab-$key").testTag("glasses-tab-$key") },
) { selectedGlassesTab = it }
Column(
// The agent's chat scrolls itself and keeps its composer at the bottom, so it takes the height left.
if (page == SessionDrawerPage.AGENT) AgentPage(
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
inputModifier = focus.track(page, "agent-input"),
visible = open,
) else Column(
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)),
) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) {
when (page) {
@@ -762,6 +770,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
track = { key -> focus.track(page, key) },
)
}
SessionDrawerPage.AGENT -> Unit
SessionDrawerPage.SESSION -> {
if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps)) {
SettingsRow(stringResource(R.string.drawer_launch_app), null) {
@@ -33,6 +33,8 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
Store.GAMEJOLT.id -> SourceColours(Color(0xFF232E00), Color(0xFFE3FF66), Color(0xFFCCFF00))
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
Store.UBISOFT.id -> SourceColours(Color(0xFF0B1E44), Color(0xFFA8C6FF), Color(0xFF2E7DFF))
Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
@@ -48,6 +50,8 @@ internal fun sourceLabel(source: String): String = when (source) {
Store.ITCH.id -> Store.ITCH.label
Store.GAMEJOLT.id -> Store.GAMEJOLT.label
Store.BATTLENET.id -> Store.BATTLENET.label
Store.UBISOFT.id -> Store.UBISOFT.shortLabel
Store.EA.id -> Store.EA.label
else -> stringResource(R.string.source_added)
}
@@ -1157,6 +1157,8 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
Store.GAMEJOLT -> Color(0xFFCCFF00) to Color(0xFFA3CC00)
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
Store.UBISOFT -> Color(0xFF2E7DFF) to Color(0xFF1A5BD6)
Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030)
null -> return base
}
val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White
@@ -120,11 +120,11 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
StatusPanel(s, u, ua, me)
Box(Modifier.height(18.dp))
ChannelLabel()
ChannelPicker(u, ua)
ChannelPicker(u, ua, s.sessionRunning)
} else {
ChannelLabel()
Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) {
Box(Modifier.weight(1f)) { ChannelPicker(u, ua) }
Box(Modifier.weight(1f)) { ChannelPicker(u, ua, s.sessionRunning) }
Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) }
}
}
@@ -262,7 +262,7 @@ private fun ChannelLabel() {
}
@Composable
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions, sessionRunning: Boolean) {
val colors = MaterialTheme.colorScheme
val catalog = u.catalog
val tests = catalog?.tests.orEmpty()
@@ -285,6 +285,15 @@ private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
tests.forEach { t -> TestRow(t, u.follow.pr == t.pr) { ua.onFollow(Follow(Channel.TEST, t.pr)) } }
}
}
val context = androidx.compose.ui.platform.LocalContext.current
val agentReady = com.droiddeck.launcher.agent.AgentHost.installed &&
(com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context))
LabBuilds(sessionRunning, onRebuild = if (agentReady) { info ->
com.droiddeck.launcher.agent.AgentHost.send(context, context.getString(R.string.agent_rebuild_lab, info.label))
context.startActivity(android.content.Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent")
.addFlags(android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
} else null)
}
}
@@ -56,7 +56,7 @@ import java.io.File
private fun installable(name: String, all: Map<String, WinComponents.Component>): String = WinComponents.installable(name, all)
@Composable
private fun originName(origin: String): String = if (origin == WinCompSources.Origin.XBOX.name) "Xbox" else stringResource(
private fun originName(origin: String): String = if (origin == WinCompSources.Origin.XBOX.name) "Xbox" else if (origin == WinCompSources.Origin.UBISOFT.name) "Ubisoft Connect" else stringResource(
when (origin) {
WinCompSources.Origin.GOG.name -> R.string.wincomp_src_gog
WinCompSources.Origin.EPIC.name -> R.string.wincomp_src_epic
@@ -71,6 +71,7 @@ private fun autoReason(r: WinComponents.AutoReason): String = when (r.kind) {
WinCompSources.Origin.GOG.name -> stringResource(R.string.wincomp_auto_gog)
WinCompSources.Origin.EPIC.name -> stringResource(R.string.wincomp_auto_epic)
WinCompSources.Origin.AMAZON.name -> stringResource(R.string.wincomp_auto_amazon)
WinCompSources.Origin.UBISOFT.name -> "From Ubisoft's install steps for this game"
WinCompSources.Origin.XBOX.name -> "Xbox games install it with the game (${r.args.getOrElse(0) { "VC14" }})"
else -> ""
}
Loaded 100 of 210 files, more files were not shown because too many files have changed in this diff. Show more