Merge remote-tracking branch 'droiddeck/main' into maint/appimage-x64-wayland-runtime

This commit is contained in:
maxjivi05 committed 2026-11-14 18:22:26 -05:00
commit 0d6c18b300
562 files changed
+71029 -1963

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
+29 -4
View File
@@ -127,6 +127,7 @@ jobs:
name: xbox-arm64
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
retention-days: 14
overwrite: true
- uses: actions/upload-artifact@v4
with:
name: xbox-corresponding-source
@@ -135,6 +136,7 @@ jobs:
app/build/xbox/runtime/*-source.tar.xz
if-no-files-found: error
retention-days: 14
overwrite: true
components-runner:
needs: source
@@ -195,6 +197,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
@@ -329,6 +332,7 @@ jobs:
if-no-files-found: error
compression-level: 0
retention-days: 14
overwrite: true
build-runner:
needs: [components]
@@ -555,6 +559,18 @@ 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
- name: Rockstar launcher service (32-bit and 64-bit)
run: |
set -euo pipefail
command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; }
bash tools/rockstar-launcher/build.sh
- uses: actions/download-artifact@v4
with:
name: xbox-arm64
@@ -610,12 +626,11 @@ jobs:
- name: Check out MaliBridge
run: git submodule update --init external/MaliBridge
- name: Fetch the Mali (Venus) component (tools/venus/release.env)
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
. tools/venus/release.env
gh release download "${VENUS_TAG}" -R "${VENUS_REPO}" -p venus.tzst -O venus.tzst
curl -fsSL --retry 5 --retry-all-errors --retry-delay 10 -o venus.tzst \
"https://github.com/${VENUS_REPO}/releases/download/${VENUS_TAG}/venus.tzst"
echo "${VENUS_SHA256} venus.tzst" | sha256sum -c -
tar --use-compress-program=unzstd -xf venus.tzst -C app/src/main
test -f app/src/main/jniLibs/arm64-v8a/libvirgl_test_server.so
@@ -652,6 +667,7 @@ jobs:
name: stores-cargo-lock
path: app/src/main/rust/stores/Cargo.lock
if-no-files-found: ignore
overwrite: true
- name: Unit tests
id: unit-tests
@@ -675,6 +691,7 @@ jobs:
app/build/reports/tests/testReleaseUnitTest/
if-no-files-found: ignore
retention-days: 14
overwrite: true
- name: Sign with the testkey (v1 + v2 + v3)
run: |
@@ -712,6 +729,7 @@ jobs:
if-no-files-found: error
retention-days: 30
compression-level: 0
overwrite: true
- uses: actions/upload-artifact@v4
with:
@@ -720,6 +738,7 @@ jobs:
if-no-files-found: error
retention-days: 30
compression-level: 0
overwrite: true
- name: Report on the pull request
if: always() && github.event_name == 'pull_request'
@@ -791,6 +810,11 @@ jobs:
set -o pipefail
cd app/src/main/rust/stores
cargo test --locked 2>&1 | tail -60
- name: Windows launcher service host unit tests
timeout-minutes: 10
run: |
cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml
cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml
python-tests:
name: Python and native regression tests
@@ -891,6 +915,7 @@ jobs:
uses: ./.github/workflows/scan.yml
with:
artifact: droiddeck-signed
variant: standard
secrets: inherit
packs:
@@ -912,7 +937,7 @@ jobs:
pull-requests: read
env:
CI_REPO: Droid-Deck/DroidDeck-CI
KEEP: 10
KEEP_DAYS: 14
steps:
- uses: actions/checkout@v4
with:
+141
View File
@@ -0,0 +1,141 @@
name: PR Rebuild On Version Bump
run-name: rebuild test builds below versionCode on main
on:
push:
branches: [main]
paths: [app/build.gradle]
workflow_dispatch:
permissions:
actions: write
contents: read
issues: write
pull-requests: read
concurrency:
group: pr-rebuild-on-version
cancel-in-progress: false
queue: max
jobs:
rebuild:
runs-on: ubuntu-24.04
timeout-minutes: 180
steps:
- uses: actions/checkout@v4
with:
ref: main
fetch-depth: 2
persist-credentials: false
- name: Rebuild open PRs whose test build Android would refuse over main
env:
GH_TOKEN: ${{ github.token }}
EVENT_NAME: ${{ github.event_name }}
BEFORE: ${{ github.event.before }}
PUSHED_AT: ${{ github.event.repository.pushed_at }}
run: |
set -euo pipefail
code() { sed -n 's/^[[:space:]]*versionCode[[:space:]][[:space:]]*\([0-9][0-9]*\)[[:space:]]*$/\1/p'; }
now=$(code < app/build.gradle)
[[ "$now" =~ ^[0-9]+$ ]] || { echo "::error::No numeric versionCode on main"; exit 1; }
if [ "$EVENT_NAME" = push ]; then
was=$(git show "$BEFORE:app/build.gradle" 2>/dev/null | code || true)
if [[ "$was" =~ ^[0-9]+$ ]] && [ "$was" -ge "$now" ]; then
echo "versionCode stayed at $now"
exit 0
fi
fi
# This run is created right after the push, so a PR build that started earlier may have pinned the old main.
bumped=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" --jq .created_at)
# A build can finish between the push and this run's creation; the push event carries the push time.
if [[ "${PUSHED_AT:-}" =~ ^[0-9]+$ ]]; then
pushed=$(date -u -d "@$PUSHED_AT" +%Y-%m-%dT%H:%M:%SZ)
[[ "$pushed" < "$bumped" ]] && bumped=$pushed
else
pushed=$(date -u -d "$bumped - 10 minutes" +%Y-%m-%dT%H:%M:%SZ)
fi
note() {
local number=$1
local marker="<!-- droiddeck-rebuild-$now -->"
gh api "repos/$GITHUB_REPOSITORY/issues/$number/comments?per_page=100" --jq '.[].body' | grep -qF "$marker" && return 0
gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$number/comments" -f body="$marker
Main is now at versionCode $now, so this PR's test build no longer installs over current DroidDeck, and its last build is too old for GitHub to re-run. Push a commit or merge main to get a new test build." >/dev/null
}
latest() {
gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build.yml/runs?event=pull_request&head_sha=$1&per_page=20" \
--jq '[.workflow_runs[] | select(.head_sha == "'"$1"'")] | sort_by(.created_at) | last // empty | [.id, .status, (.run_started_at // .created_at), .created_at, .updated_at] | @tsv'
}
consider() {
local number=$1 head=$2 built=$3 id status started created updated
IFS=$'\t' read -r id status started created updated <<<"$4"
if [[ "$started" > "$bumped" ]]; then
echo "PR #$number: build $id started after the bump"
elif ! gh api "repos/$GITHUB_REPOSITORY/pulls/$number" |
jq -e --arg head "$head" '.state == "open" and .draft == false and .base.ref == "main" and .head.sha == $head' >/dev/null; then
echo "PR #$number: moved on since the scan, its own build covers it"
elif gh run rerun "$id" -R "$GITHUB_REPOSITORY"; then
echo "PR #$number: rebuilding ${head:0:7} on main (versionCode $built -> $now)"
else
echo "::warning::PR #$number: could not rerun build $id"
# GitHub only re-runs a workflow within 30 days of its first run.
if [[ "$created" < "$(date -u -d '-30 days' +%Y-%m-%dT%H:%M:%SZ)" ]]; then
note "$number" || echo "::warning::PR #$number: could not leave a note"
fi
fi
}
pending=()
declare -A seen=()
candidates() {
gh api --paginate "repos/Droid-Deck/DroidDeck-CI/releases?per_page=100" \
--jq '.[] | select(.tag_name | test("^pr-[0-9]+$")) | [(.tag_name | ltrimstr("pr-")), ((.body // "") | capture("(?m)^VersionCode: (?<v>[0-9]+)").v // "0")] | @tsv'
# The latest build of every open PR: one that started before the bump and was still running at it
# may have pinned the old main. This also covers a PR's first build and fork builds.
gh api --paginate -X GET "repos/$GITHUB_REPOSITORY/pulls" -f state=open -f base=main -f per_page=100 \
--jq '.[] | select(.draft | not) | [(.number | tostring), .head.sha] | @tsv' |
while IFS=$'\t' read -r number sha; do
run=$(latest "$sha")
[ -n "$run" ] || continue
IFS=$'\t' read -r _ status started _ updated <<<"$run"
if [[ "$started" < "$bumped" ]] && { [ "$status" != completed ] || [[ ! "$updated" < "$pushed" ]]; }; then
printf '%s\t?\n' "$number"
fi
done
}
found=$(mktemp)
candidates > "$found"
while IFS=$'\t' read -r number built; do
[ "$built" = "?" ] || [ "$built" -lt "$now" ] || continue
[ -z "${seen[$number]:-}" ] || continue
seen[$number]=1
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$number") || continue
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null || continue
head=$(jq -r .head.sha <<<"$pr")
run=$(latest "$head")
if [ -z "$run" ]; then
echo "PR #$number: no build of ${head:0:7} to rerun"
elif [ "$(cut -f2 <<<"$run")" = completed ]; then
consider "$number" "$head" "$built" "$run"
else
pending+=("$number $head $built")
fi
done < "$found"
# Builds still running are polled together so one slow build cannot hold up the rest.
deadline=$((SECONDS + 150 * 60))
while [ ${#pending[@]} -gt 0 ] && [ "$SECONDS" -lt "$deadline" ]; do
sleep 60
left=()
for item in "${pending[@]}"; do
read -r number head built <<<"$item"
run=$(latest "$head")
if [ -n "$run" ] && [ "$(cut -f2 <<<"$run")" = completed ]; then
consider "$number" "$head" "$built" "$run"
else
left+=("$item")
fi
done
pending=(${left[@]+"${left[@]}"})
done
for item in ${pending[@]+"${pending[@]}"}; do
echo "::warning::PR #${item%% *}: its build did not finish in time"
done
+6
View File
@@ -55,3 +55,9 @@ jobs:
fi
done
exit "$failed"
catalog:
needs: sweep
if: ${{ always() }}
uses: ./.github/workflows/update-catalog.yml
secrets: inherit
+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)
+5 -1
View File
@@ -7,6 +7,10 @@ on:
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
@@ -27,7 +31,7 @@ jobs:
- uses: actions/download-artifact@v4
with:
pattern: ${{ inputs.artifact }}-*
pattern: ${{ inputs.artifact }}-${{ inputs.variant }}
merge-multiple: true
path: scan
+1
View File
@@ -36,3 +36,4 @@ __pycache__/
app/src/main/assets/directaudio/
app/src/main/assets/hybris/
/tools/vr/out/
app/src/main/resources/rockstar/helpers/
+10
View File
@@ -1,3 +1,13 @@
# Rules
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
# Working on the device
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
- Uncommitted changes in the tree may not be yours. Read `git diff` before committing them and tell the user what they do.
- If `dd-lab-build` says "could not read DroidDeck's state", loopback adb is down and `$ADB_SERIAL` is stale. Run `adb devices`; the port changes whenever wireless debugging is toggled. Ask the user to turn it on rather than retrying.
- A build that "did not start" can be adb, not the app. Read `~/.cache/dd-lab-build.json` and `.log` for the real reason; they can be stale from an earlier build, so compare their times with `date`.
- Run `dd-lab-build` with `run_in_background` and read its output file. A foreground `sleep` is blocked; wait with Monitor and an until-loop.
- The build restarts DroidDeck and ends your process. A turn that ends this way is not a failure.
+3 -1
View File
@@ -25,7 +25,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
<p align="center"><img src="docs/media/steam-to-desktop.gif" width="100%" alt="On a Retroid Pocket Duo: Play Steam from the DroidDeck launcher, open Pac-Man in Steam Big Picture and play it, exit the game, then Switch to Desktop from the Power menu"></p>
> DroidDeck has no website. Only download it from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
> The official website is [droid-deck.dev](https://droid-deck.dev). Only download DroidDeck from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
<p align="center">
<img src="docs/releases/media/0.6.7/library.gif" width="49%" alt="The Library switching source chips, changing the card size and opening the Filter menu">
@@ -92,7 +92,9 @@ 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.
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
- 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.
+13 -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")
@@ -141,6 +141,7 @@ android {
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
buildConfigField "String", "UPDATE_CATALOG_BRANCH", "\"${(System.getenv("DROIDDECK_UPDATE_CATALOG_BRANCH") ?: "main").with { it ==~ /[A-Za-z0-9._-]+/ ? it : "main" }}\""
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
buildConfigField "String", "SGDB_API_KEY", "\"${System.getenv("SGDB_API_KEY") ?: project.findProperty("sgdbApiKey") ?: ""}\""
buildConfigField "String", "DESKTOP_KDE_TAG", "\"${desktopKde.DESKTOP_KDE_TAG}\""
@@ -205,7 +206,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 {
@@ -277,6 +278,8 @@ def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
dependsOn(stageSessionScripts)
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
from(rootProject.file('tools/linuxfs/innoextract'))
from(rootProject.file('tools')) { include 'droiddeckctl', 'adb_device.py', 'proot_profile.py'; into('agent/ctl') }
from(rootProject.file('docs/agent-control.md')) { into('agent/ctl') }
from(layout.buildDirectory.dir('prepared-assets'))
into(runtimeAssetsDir)
}
@@ -380,6 +383,11 @@ dependencies {
implementation 'androidx.activity:activity-compose:1.8.2'
implementation 'androidx.compose.material:material-icons-extended'
implementation 'io.coil-kt:coil-compose:2.6.0'
implementation 'io.noties.markwon:core:4.6.2'
implementation 'io.noties.markwon:ext-strikethrough:4.6.2'
implementation 'io.noties.markwon:ext-tables:4.6.2'
implementation 'io.noties.markwon:ext-tasklist:4.6.2'
implementation 'com.atlassian.commonmark:commonmark-ext-autolink:0.13.0'
implementation 'com.caverock:androidsvg-aar:1.4'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
implementation 'com.flyfishxu:kadb-android:1.2.1'
@@ -387,11 +395,14 @@ dependencies {
implementation 'androidx.camera:camera-camera2:1.4.2'
implementation 'androidx.camera:camera-lifecycle:1.4.2'
implementation 'androidx.webkit:webkit:1.12.1'
implementation 'androidx.palette:palette:1.0.0'
implementation 'io.github.webrtc-sdk:android:125.6422.07'
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
exclude group: 'com.google.auto.value', module: 'auto-value'
}
implementation 'com.google.zxing:core:3.5.3'
implementation 'androidx.media3:media3-exoplayer:1.3.1'
implementation 'androidx.media3:media3-session:1.3.1'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.16.1'
+33
View File
@@ -18,8 +18,15 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SECONDARY_HOME" />
</intent>
<intent>
<action android:name="org.adw.launcher.THEMES" />
</intent>
<intent>
<action android:name="com.novalauncher.THEME" />
</intent>
</queries>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.REORDER_TASKS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
@@ -111,6 +118,17 @@
</intent-filter>
</activity>
<activity
android:name=".DeviceCodeActivity"
android:exported="false"
android:launchMode="singleTask"
android:taskAffinity="${applicationId}.devicecode"
android:excludeFromRecents="true"
android:supportsPictureInPicture="true"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
android:theme="@style/AppTheme" />
<activity
android:name=".PairingGuideActivity"
android:exported="false"
@@ -134,6 +152,7 @@
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.CAR_LAUNCHER" />
<data android:scheme="droiddeck" android:host="game" />
<data android:scheme="droiddeck" android:host="soundtrack" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" />
@@ -258,6 +277,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 +322,11 @@
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=".update.UpdateWatch"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false" />
<service
android:name=".session.SessionService"
android:exported="false"
@@ -325,6 +350,14 @@
android:name=".sync.SyncthingService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<service
android:name=".playback.SoundtrackService"
android:exported="true"
android:foregroundServiceType="mediaPlayback">
<intent-filter>
<action android:name="androidx.media3.session.MediaSessionService" />
</intent-filter>
</service>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.logs"
+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
+52
View File
@@ -0,0 +1,52 @@
#!/bin/bash
# Starts GitHub's device login, floats its code over Android's browser and opens the approval page.
url=https://github.com/login/device
inbox=${DD_AGENT_INBOX:-}
# DroidDeck takes $inbox/device-code within a few seconds when it can float the code.
float_code() {
[ -n "$inbox" ] && [ -d "$inbox" ] || return 1
rm -f "$inbox/device-code.result"
printf '%s %s\n' "$1" "$url" > "$inbox/device-code.part" && mv -f "$inbox/device-code.part" "$inbox/device-code" || return 1
i=0
while [ $i -lt 40 ] && [ -e "$inbox/device-code" ]; do
sleep 0.2
i=$((i + 1))
done
if [ -e "$inbox/device-code" ]; then
rm -f "$inbox/device-code"
return 1
fi
# DroidDeck writes "ok" or "failed" once it has tried to open the page; no answer counts as failed.
i=0
while [ $i -lt 50 ] && [ ! -e "$inbox/device-code.result" ]; do
sleep 0.2
i=$((i + 1))
done
result=$(cat "$inbox/device-code.result" 2>/dev/null)
rm -f "$inbox/device-code.result"
[ "$result" = ok ]
}
coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; }
gh_pid=$GH_PID
exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}"
shown=
while IFS= read -r line <&"$ghout"; do
code=$(grep -oE '[A-Z0-9]{4}-[A-Z0-9]{4}' <<<"$line" | head -1)
# gh's own prompts would push the code out of the one line the setup card shows.
case "$line" in
*"one-time code"* | *"Press Enter"* | *"Open this URL"*) ;;
*) printf '%s\n' "$line" ;;
esac
if [ -n "$code" ] && [ -z "$shown" ]; then
shown=1
echo >&"$ghin"
printf 'GitHub device code: %s · github.com/login/device\n' "$code"
float_code "$code" || android-open "$url"
fi
done
wait "$gh_pid"
status=$?
[ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code"
exit $status
+2
View File
@@ -0,0 +1,2 @@
#!/bin/sh
exec python3 /root/.local/share/droiddeck/ctl/droiddeckctl "$@"
Binary file not shown.
+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) {
@@ -1,5 +1,6 @@
add_library(droiddeckwayland SHARED
src/compositor.c
src/clock_domain.c
src/vk_present.c
src/effects_chain.c
src/cardboard.c
@@ -0,0 +1,72 @@
#define _GNU_SOURCE
#include "clock_domain.h"
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
static const int64_t *g_shift;
static pthread_mutex_t g_control_lock = PTHREAD_MUTEX_INITIALIZER;
static dev_t g_device;
static ino_t g_inode;
void droiddeck_clock_domain_set_control(const char *path) {
int fd;
struct stat st;
pthread_mutex_lock(&g_control_lock);
if (!path || !*path) {
const int64_t *previous = g_shift;
g_shift = NULL;
if (previous) munmap((void *)previous, sizeof(*previous));
pthread_mutex_unlock(&g_control_lock);
return;
}
fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0 || fstat(fd, &st) != 0 || st.st_size < (off_t)sizeof(int64_t)) {
if (fd >= 0) close(fd);
pthread_mutex_unlock(&g_control_lock);
return;
}
if (g_shift && st.st_dev == g_device && st.st_ino == g_inode) {
close(fd);
pthread_mutex_unlock(&g_control_lock);
return;
}
const int64_t *shift = mmap(NULL, sizeof(*shift), PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (shift != MAP_FAILED) {
g_device = st.st_dev;
g_inode = st.st_ino;
const int64_t *previous = g_shift;
g_shift = shift;
if (previous) munmap((void *)previous, sizeof(*previous));
}
pthread_mutex_unlock(&g_control_lock);
}
static int64_t shift_ns(void) {
pthread_mutex_lock(&g_control_lock);
const int64_t *mapping = g_shift;
int64_t shift = mapping ? __atomic_load_n(mapping, __ATOMIC_RELAXED) : 0;
pthread_mutex_unlock(&g_control_lock);
return shift > 0 ? shift : 0;
}
int64_t droiddeck_clock_domain_adjust_ns(int64_t value) {
int64_t shift = shift_ns();
return value > shift ? value - shift : 0;
}
int64_t droiddeck_clock_domain_now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return droiddeck_clock_domain_adjust_ns((int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec);
}
uint32_t droiddeck_clock_domain_now_ms(void) {
return (uint32_t)(droiddeck_clock_domain_now_ns() / 1000000LL);
}
@@ -0,0 +1,11 @@
#ifndef DROIDDECK_CLOCK_DOMAIN_H
#define DROIDDECK_CLOCK_DOMAIN_H
#include <stdint.h>
void droiddeck_clock_domain_set_control(const char *path);
int64_t droiddeck_clock_domain_now_ns(void);
uint32_t droiddeck_clock_domain_now_ms(void);
int64_t droiddeck_clock_domain_adjust_ns(int64_t value);
#endif
@@ -36,6 +36,7 @@
#include "droiddeck_ext.h"
#include "droiddeck_color.h"
#include "compositor_internal.h"
#include "clock_domain.h"
#define WLOGI(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", __VA_ARGS__)
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", __VA_ARGS__)
@@ -727,9 +728,7 @@ static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) {
static void fire_frames(struct wl_list *frames) {
struct wl_resource *cb, *tmp;
uint32_t t;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
t = (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
t = droiddeck_clock_domain_now_ms();
wl_resource_for_each_safe(cb, tmp, frames) {
wl_callback_send_done(cb, t);
wl_resource_destroy(cb);
@@ -1061,6 +1060,7 @@ static int64_t presented_ns(int64_t render_ns) {
static void feedback_present_all(struct wl_list *list, int64_t t) {
struct wl_resource *fb, *tmp;
t = droiddeck_clock_domain_adjust_ns(t);
uint64_t sec = (uint64_t)(t / 1000000000LL);
uint32_t nsec = (uint32_t)(t % 1000000000LL);
wl_resource_for_each_safe(fb, tmp, list) {
@@ -2493,8 +2493,7 @@ static void on_vsync(int64_t frame_time_ns) {
static uint32_t now_ms(void) {
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
return droiddeck_clock_domain_now_ms();
}
static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint32_t serial,
@@ -3114,12 +3113,10 @@ static void relative_pointers_pointer_gone(struct wl_resource *pointer) {
static int send_relative_motion(struct wl_client *client, double dx, double dy) {
struct relative_pointer *rp;
struct timespec ts;
uint64_t ut;
int sent = 0;
if (dx == 0 && dy == 0) return 0;
clock_gettime(CLOCK_MONOTONIC, &ts);
ut = (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)ts.tv_nsec / 1000;
ut = (uint64_t)(droiddeck_clock_domain_now_ns() / 1000);
wl_list_for_each(rp, &g_relative_pointers, link) {
if (!rp->pointer || wl_resource_get_client(rp->pointer) != client) continue;
zwp_relative_pointer_v1_send_relative_motion(rp->resource, (uint32_t)(ut >> 32), (uint32_t)ut,
@@ -33,7 +33,9 @@ static PFN_vkGetInstanceProcAddr g_gipa;
static VkPhysicalDevice g_pd;
static VkQueue g_queue;
static uint32_t g_qfam;
static int g_dev_ready, g_dev_lost, g_features_enabled;
static _Atomic int g_dev_ready, g_dev_lost;
static int g_features_enabled;
static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok;
static VkPhysicalDeviceMemoryProperties g_memprops;
static struct {
PFN_vkCreateImage CreateImage;
@@ -141,9 +143,12 @@ static void mark_failed(int kind) {
}
int vkp_framegen_problem(void) {
if (!g_dev_ready) return -1;
if (!atomic_load(&g_dev_ready)) return -1;
int kind = atomic_load(&g_kind);
if (!fge_caps_ok(kind)) return 1;
int caps_ok = kind == VKP_FG_ENGINE_DDFG
? atomic_load(&g_caps_ddfg_ok)
: atomic_load(&g_caps_lsfg_ok);
if (!caps_ok) return 1;
if (start_failed_for(kind)) return 2;
if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2;
return 0;
@@ -179,13 +184,17 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f
#undef R
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled);
g_dev_ready = vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier;
atomic_store(&g_caps_lsfg_ok, fge_caps_ok(VKP_FG_ENGINE_LSFG));
atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG));
atomic_store(&g_dev_lost, 0);
atomic_store(&g_dev_ready,
vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier);
FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s",
fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(),
fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable");
}
void vkp_framegen_device_lost(void) { g_dev_lost = 1; }
void vkp_framegen_device_lost(void) { atomic_store(&g_dev_lost, 1); }
static void destroy_ring(void) {
@@ -244,7 +253,12 @@ static int ensure_ring(uint32_t w, uint32_t h, VkFormat fmt, uint32_t n) {
static int engine_usable(void) {
int kind = atomic_load(&g_kind);
return g_dev_ready && !g_dev_lost && fge_caps_ok(kind) && !start_failed_for(kind);
int ready = atomic_load(&g_dev_ready);
int lost = atomic_load(&g_dev_lost);
int caps_ok = kind == VKP_FG_ENGINE_DDFG
? atomic_load(&g_caps_ddfg_ok)
: atomic_load(&g_caps_lsfg_ok);
return ready && !lost && caps_ok && !start_failed_for(kind);
}
int vkp_framegen_format_ok(VkFormat fmt) {
@@ -50,6 +50,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenCapsReason(J
return (*env)->NewStringUTF(env, r ? r : "");
}
JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenActive(JNIEnv *env, jclass clazz) {
(void)env; (void)clazz;
return vkp_framegen_active() ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT jfloatArray JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameGenStats(JNIEnv *env, jclass clazz) {
(void)clazz;
@@ -18,6 +18,7 @@
#include "cardboard.h"
#include "droiddeck_color.h"
#include "gpu_clock_pin.h"
#include "clock_domain.h"
extern int droiddeck_wayland_run(void);
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
@@ -354,6 +355,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeVsync(JNIEnv *env, j
droiddeck_wayland_vsync((int64_t)frameTimeNanos);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetClockControl(JNIEnv *env, jclass clazz, jstring path) {
const char *value = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL;
droiddeck_clock_domain_set_control(value);
if (value) (*env)->ReleaseStringUTFChars(env, path, value);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv *env, jclass clazz, jboolean hide) {
g_hide_shell = hide ? 1 : 0;
@@ -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,11 +42,18 @@ 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)
com.droiddeck.launcher.agent.AgentTab.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) 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)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.update.AppUpdates.init(this)
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
com.droiddeck.launcher.core.DownloadSource.init(this)
prefetchAddonPacks()
GpuClockPin.clearLeftover(this)
@@ -61,6 +71,10 @@ 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)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend)
}
private fun prefetchAddonPacks() {
@@ -74,6 +88,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()
@@ -0,0 +1,167 @@
package com.droiddeck.launcher
import android.app.ActivityOptions
import android.app.PictureInPictureParams
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Bundle
import android.util.Rational
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
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.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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.core.AppLanguage
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.FitText
import com.droiddeck.launcher.ui.LocalPalette
import com.droiddeck.launcher.ui.PrimaryButton
import com.droiddeck.launcher.ui.SecondaryButton
import java.lang.ref.WeakReference
/** Floats a sign-in code over the browser page that asks for it. */
class DeviceCodeActivity : ComponentActivity() {
private var code by mutableStateOf("")
private var url = ""
private var display: Int? = null
private var inPip by mutableStateOf(false)
private var openPending = false
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
current = WeakReference(this)
read(intent)
openPending = savedInstanceState == null
setContent { DroidDeckTheme { Float() } }
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
read(intent)
openPending = true
}
override fun onDestroy() {
if (current?.get() === this) current = null
super.onDestroy()
}
override fun onResume() {
super.onResume()
if (!openPending) return
if (isInPictureInPictureMode) {
openPage()
return
}
enterPip()
if (!inPip) {
openPage()
finish()
}
}
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
inPip = isInPictureInPictureMode
if (isInPictureInPictureMode && openPending) openPage()
}
private fun read(intent: Intent) {
code = intent.getStringExtra(EXTRA_CODE).orEmpty()
url = intent.getStringExtra(EXTRA_URL).orEmpty()
display = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it > 0 }
copy()
}
private fun copy() {
runCatching { getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("GitHub", code)) }
}
private fun enterPip() {
inPip = runCatching {
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(16, 9)).build())
}.getOrDefault(false)
}
private fun openPage() {
openPending = false
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val at = display
val opened = runCatching {
if (at == null) startActivity(intent)
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(at).toBundle())
}.recoverCatching { startActivity(intent) }.isSuccess
com.droiddeck.launcher.agent.AgentHost.deviceCodeOpened(applicationContext, opened)
}
@androidx.compose.runtime.Composable
private fun Float() {
val colors = MaterialTheme.colorScheme
val accent = LocalPalette.current.signal
BackHandler(enabled = !inPip) { enterPip() }
Box(Modifier.fillMaxSize().background(colors.background), contentAlignment = Alignment.Center) {
Column(
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(if (inPip) 8.dp else 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(if (inPip) 2.dp else 16.dp),
) {
Text(stringResource(R.string.agent_step_github), style = MaterialTheme.typography.labelLarge, color = colors.onSurfaceVariant)
FitText(code, maxSize = if (inPip) 40.sp else 56.sp, fontWeight = FontWeight.Bold, color = accent,
modifier = Modifier.fillMaxWidth())
Text(Uri.parse(url).let { it.host + it.path }, style = MaterialTheme.typography.labelMedium, color = colors.onSurfaceVariant, maxLines = 1)
if (!inPip) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
PrimaryButton(stringResource(R.string.fm_copy), onClick = ::copy)
SecondaryButton(stringResource(R.string.common_close), onClick = ::finish)
}
}
}
}
companion object {
private const val EXTRA_CODE = "code"
private const val EXTRA_URL = "url"
private const val EXTRA_DISPLAY = "display"
private var current: WeakReference<DeviceCodeActivity>? = null
/** False when this device cannot float a window, so the caller opens the page itself. */
fun show(context: Context, code: String, url: String, display: Int): Boolean {
if (!PairingGuideActivity.canFloat(context)) return false
val intent = Intent(context, DeviceCodeActivity::class.java)
.putExtra(EXTRA_CODE, code).putExtra(EXTRA_URL, url).putExtra(EXTRA_DISPLAY, display)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return runCatching {
if (display > 0) context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
else context.startActivity(intent)
}.isSuccess
}
fun close() {
current?.get()?.finish()
}
}
}
@@ -84,7 +84,7 @@ import com.droiddeck.launcher.session.SteamLibraries
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
class FrontEndActivity : ComponentActivity() {
class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPetHost {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -179,12 +179,14 @@ class FrontEndActivity : ComponentActivity() {
private var syncFallback by mutableStateOf(true)
private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var ramCapMb by mutableStateOf(0)
private var zramClient by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
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)
@@ -195,6 +197,7 @@ class FrontEndActivity : ComponentActivity() {
private var stretch16x9 by mutableStateOf(false)
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM)
private var launcherFullscreen by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
@@ -204,6 +207,10 @@ class FrontEndActivity : ComponentActivity() {
private var lowStorageWarning by mutableStateOf(true)
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true)
private var soundtracksEnabled by mutableStateOf(true)
private var soundtracksIngame by mutableStateOf(false)
private var soundtracks by mutableStateOf<List<Library.SteamGame>>(emptyList())
private var soundtracksLoaded by mutableStateOf(false)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf<String?>(null)
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
@@ -225,6 +232,11 @@ class FrontEndActivity : ComponentActivity() {
refreshWifiDiscovery()
}
}
private val dateReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
refreshAndroidApps()
}
}
private val mediaRefresh = Runnable {
refresh()
refreshAddedGames()
@@ -592,6 +604,7 @@ class FrontEndActivity : ComponentActivity() {
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
private var graphicsLogs by mutableStateOf(false)
private var buildWatermark by mutableStateOf(true)
private var steamGpuDrawing by mutableStateOf(false)
private var bridgeFellBack by mutableStateOf(false)
private var bridgeFellBackMemory by mutableStateOf(false)
@@ -777,6 +790,11 @@ class FrontEndActivity : ComponentActivity() {
private var shortcutPicker by mutableStateOf(false)
private var shortcutLibraryScanning by mutableStateOf(false)
@Volatile private var libraryScanGeneration = 0
private class SoundtrackRemoval(val op: Int, var scan: Int, var settled: Boolean)
private val soundtrackRemovals = HashMap<String, SoundtrackRemoval>()
private var soundtrackOp = 0
private var soundtrackAddScan = -1
private val soundtrackWork = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-work").apply { isDaemon = true } }
@Volatile private var lastComponentRestore = 0L
@Volatile private var componentRestoreRetry = false
private val componentRestoreLock = Any()
@@ -827,6 +845,10 @@ class FrontEndActivity : ComponentActivity() {
private fun readGameIntent(request: Intent) {
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
if (navRequest == com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS) {
homeAppSelected = HomeApp.isHomeScreenEnabled(this) && HomeApp.isDefault(this)
if (!homeAppSelected) navRequest = null
}
shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT
if (shortcutPicker) {
steamGames = emptyList()
@@ -835,6 +857,15 @@ class FrontEndActivity : ComponentActivity() {
pendingGameLink = null
gameLinkReading = false
gameLinkTried = false
soundtrackLaunch = false
val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request)
if (soundtrackId != null) {
soundtrackLaunch = true
navRequest = if (SessionPrefs.soundtracksEnabled(this)) "sound:$soundtrackId" else "app:$soundtrackId"
request.data = null
request.action = Intent.ACTION_MAIN
return
}
if (GameLaunchIntent.accepts(request.action)) {
gameLinkReading = true
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
@@ -858,12 +889,15 @@ class FrontEndActivity : ComponentActivity() {
}
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean {
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
if (pkgStage != null) {
onHandled()
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome)
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
onHandled()
if (SessionState.running) {
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
@@ -907,12 +941,13 @@ class FrontEndActivity : ComponentActivity() {
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
}
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean {
val app = applicationContext
Thread({
val added = if (game.library == Library.ADDED) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
ui.post {
onHandled()
if (isDestroyed) return@post
if (command == null) {
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
@@ -1104,6 +1139,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.AgentTab.visible) navRequest = "agent"
gameSyncFolder = GameFileSync.folder(this)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
@@ -1118,6 +1155,7 @@ class FrontEndActivity : ComponentActivity() {
orientation = SessionPrefs.orientation(this)
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this)
@@ -1129,6 +1167,8 @@ class FrontEndActivity : ComponentActivity() {
LauncherIcon.repair(this, intent?.component)
launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
soundtracksEnabled = SessionPrefs.soundtracksEnabled(this)
soundtracksIngame = SessionPrefs.soundtracksIngame(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
storesShowMature = SessionPrefs.storesShowMature(this)
storesSort = SessionPrefs.storesSort(this)
@@ -1175,6 +1215,7 @@ class FrontEndActivity : ComponentActivity() {
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
graphicsLogs = graphicsLogs, steamGpuDrawing = steamGpuDrawing, bridgeFellBack = bridgeFellBack, bridgeFellBackMemory = bridgeFellBackMemory,
buildWatermark = buildWatermark,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
tpUbwcMode = drivers.tpUbwcModeForDevice(), tpUbwcRestartRequired = drivers.tpUbwcRestartRequired(), canRestartApp = !runtimeChangesBlocked(),
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
@@ -1213,6 +1254,7 @@ class FrontEndActivity : ComponentActivity() {
showPhantomGate = showPhantomGate,
orientation = orientation,
launcherOrientation = launcherOrientation,
homePage = homePage,
launcherFullscreen = launcherFullscreen,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
@@ -1222,6 +1264,10 @@ class FrontEndActivity : ComponentActivity() {
lowStorageWarning = lowStorageWarning,
launcherIcon = launcherIcon,
gameStoresEnabled = gameStoresEnabled,
soundtracksEnabled = soundtracksEnabled,
soundtracksIngame = soundtracksIngame,
soundtracks = soundtracks,
soundtracksLoaded = soundtracksLoaded,
gameStoresSpeedTier = gameStoresSpeedTier,
navigate = navRequest,
addedGamesArt = addedGamesArt,
@@ -1270,7 +1316,10 @@ class FrontEndActivity : ComponentActivity() {
},
onEpicLauncher = { openEpicLauncher() },
onUninstallEpicLauncher = { uninstallEpicLauncher() },
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
onGameShortcut = { g ->
if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.pin(this, g)
else com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g)
},
onExportGameFile = { g -> pickGameExport(g) },
onSyncGameFiles = { pickGameExport(null) },
onAddGameExe = { path -> addGameExe(path) },
@@ -1295,8 +1344,9 @@ class FrontEndActivity : ComponentActivity() {
}, "game-file-stop-sync").start()
},
onCopyGameLink = { g ->
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
ClipData.newPlainText(g.name, com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)))
val link = if (g.soundtrack) com.droiddeck.launcher.frontend.SoundtrackShortcuts.uri(g.appId)
else com.droiddeck.launcher.frontend.GameLaunchLink.uri(g.gameIdString)
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText(g.name, link))
android.widget.Toast.makeText(this, R.string.game_link_copied, android.widget.Toast.LENGTH_SHORT).show()
},
onDesktop = {
@@ -1321,6 +1371,7 @@ class FrontEndActivity : ComponentActivity() {
},
onRom = { g ->
val e = emulatorList.first { it.id == g.emulatorId }
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, e.program)
@@ -1413,6 +1464,11 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this))
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
},
onBuildWatermark = {
SessionPrefs.setBuildWatermarkEnabled(this, !SessionPrefs.buildWatermarkEnabled(this))
buildWatermark = SessionPrefs.buildWatermarkEnabled(this)
com.droiddeck.launcher.ui.BuildWatermark.refresh(this)
},
onVacDiagnostics = {
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
@@ -1484,6 +1540,15 @@ class FrontEndActivity : ComponentActivity() {
},
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
onSoundtracksEnabled = { on -> SessionPrefs.setSoundtracksEnabled(this, on); soundtracksEnabled = on },
onSoundtracksIngame = { on ->
SessionPrefs.setSoundtracksIngame(this, on)
soundtracksIngame = on
com.droiddeck.launcher.playback.SoundtrackController.setIngame(this, on)
},
onSoundtrackAdded = { folder -> addSoundtrack(folder) },
onSoundtracksChanged = { refreshAddedSoundtracks() },
onSoundtrackRemoved = { g -> removeSoundtrack(g) },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
onLauncherIcon = { style -> switchLauncherIcon(style) },
onLanguage = { tag ->
@@ -1505,6 +1570,10 @@ class FrontEndActivity : ComponentActivity() {
launcherOrientation = value
requestedOrientation = value
},
onHomePage = { value ->
com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value)
homePage = value
},
onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on
@@ -1573,6 +1642,7 @@ class FrontEndActivity : ComponentActivity() {
refreshHomeAppState()
}
},
onAppIconsChanged = { refreshAndroidApps() },
onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) },
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this, inverted)
@@ -1755,6 +1825,8 @@ class FrontEndActivity : ComponentActivity() {
}, "finish-abandoned").start()
}
override val petBlocked: Boolean get() = false
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
@@ -1770,7 +1842,10 @@ class FrontEndActivity : ComponentActivity() {
startSteamAtStartupIfEnabled()
}
private var soundtrackLaunch = false
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
if (soundtrackLaunch) return
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
if (isFinishing || isDestroyed) return
when (SessionPrefs.startupSession(this)) {
@@ -1848,6 +1923,7 @@ class FrontEndActivity : ComponentActivity() {
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
if (compatLaunch != null) {
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
@@ -1897,6 +1973,7 @@ class FrontEndActivity : ComponentActivity() {
orientation = SessionPrefs.orientation(this)
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
SteamIntegration.syncShortcutsListing(this)
refreshWifiDiscovery()
com.droiddeck.launcher.stores.StoresState.refresh(this)
@@ -1950,6 +2027,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION))
registerReceiver(dateReceiver, android.content.IntentFilter(Intent.ACTION_DATE_CHANGED))
registerReceiver(mediaReceiver, android.content.IntentFilter().apply {
for (action in listOf(Intent.ACTION_MEDIA_MOUNTED, Intent.ACTION_MEDIA_UNMOUNTED, Intent.ACTION_MEDIA_REMOVED,
Intent.ACTION_MEDIA_EJECT, Intent.ACTION_MEDIA_BAD_REMOVAL)) addAction(action)
@@ -1995,8 +2073,8 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch }
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
done()
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done)
else done()
}
}
}
@@ -2016,6 +2094,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onStop() {
if (!homeChoiceOpen) HomeApp.releaseUnusedHomeEntry(this)
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(dateReceiver)
unregisterReceiver(mediaReceiver)
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
HomeWidgets.stopListening(this)
@@ -2546,7 +2625,7 @@ class FrontEndActivity : ComponentActivity() {
private fun PerformanceHost() {
PerformancePage(
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores,
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, paceCores = paceCores,
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
fastSync = fastSync,
syncFallback = syncFallback,
@@ -2557,9 +2636,10 @@ 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 },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
onGlThread = { on -> SessionPrefs.setGlThread(this, on); glThread = on },
@@ -2575,6 +2655,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 ->
@@ -2610,15 +2691,89 @@ class FrontEndActivity : ComponentActivity() {
val version = (steamArtRefreshes[appId] ?: 0) + 1
steamArtRefreshes[appId] = version
Thread({
val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this).firstOrNull { it.appId == appId } ?: return@Thread
val fresh = com.droiddeck.launcher.frontend.Library.steamGames(this, soundtracks = true).firstOrNull { it.appId == appId } ?: return@Thread
ui.post {
if (steamArtRefreshes[appId] != version) return@post
steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
if (fresh.soundtrack) soundtracks = soundtracks.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
else steamGames = steamGames.map { if (it.appId == appId && it.library != Library.ADDED) fresh else it }
}
}, "steam-art-update").start()
}
private fun addSoundtrack(folder: java.io.File) {
val op = ++soundtrackOp
soundtrackAddScan = libraryScanGeneration
soundtrackWork.execute {
val added = com.droiddeck.launcher.frontend.AddedSoundtracks.add(this, folder)
val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
ui.post {
if (added) {
soundtrackRemovals[folder.path]?.takeIf { it.op < op }?.let {
soundtrackRemovals.remove(folder.path)
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(folder.path))
}
val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] }?.let { it.op > op } == true }
soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible
} else android.widget.Toast.makeText(this, R.string.soundtracks_add_empty, android.widget.Toast.LENGTH_SHORT).show()
}
}
}
private fun refreshAddedSoundtracks() {
val op = soundtrackOp
soundtrackWork.execute {
val list = com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
ui.post {
if (op != soundtrackOp) return@post
val visible = list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null }
soundtracks = soundtracks.filter { it.library != Library.ADDED } + visible
}
}
}
private fun removeSoundtrack(g: Library.SteamGame) {
val path = g.gameFiles?.path
val added = g.library == Library.ADDED
val target = if (added) null else com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
com.droiddeck.launcher.playback.SoundtrackController.stopIf(this, g.gameFiles)
val marker = SoundtrackRemoval(++soundtrackOp, libraryScanGeneration, added)
path?.let { soundtrackRemovals[it] = marker }
if (target == null) {
soundtracks = soundtracks.filterNot { it.appId == g.appId && it.library == Library.ADDED }
soundtrackWork.execute {
val removed = com.droiddeck.launcher.frontend.AddedSoundtracks.remove(this, path.orEmpty())
val list = if (removed) emptyList() else com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
if (!removed) ui.post {
if (path != null && soundtrackRemovals[path] === marker) {
soundtrackRemovals.remove(path)
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path))
}
soundtracks = soundtracks.filter { it.library != Library.ADDED } + list.filterNot { s -> s.gameFiles?.path?.let { soundtrackRemovals[it] } != null }
android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show()
}
}
return
}
soundtrackWork.execute {
val deleted = com.droiddeck.launcher.frontend.GameRemoval.delete(target)
ui.post {
if (deleted) {
marker.scan = libraryScanGeneration
marker.settled = true
} else {
if (path != null && soundtrackRemovals[path] === marker) {
soundtrackRemovals.remove(path)
com.droiddeck.launcher.playback.SoundtrackController.allow(listOf(path))
}
android.widget.Toast.makeText(this, getString(R.string.gfiles_remove_failed, g.name), android.widget.Toast.LENGTH_SHORT).show()
}
refresh()
}
}
}
private fun removeGame(g: Library.SteamGame) {
if (g.soundtrack) { removeSoundtrack(g); return }
val folder = g.gameFiles ?: return
when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) {
com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit
@@ -2791,12 +2946,14 @@ class FrontEndActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this)
fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
ramCapMb = SessionPrefs.ramCapMb(this)
zramClient = SessionPrefs.zramClient(this)
vramCapMb = SessionPrefs.vramCapMb(this)
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()
@@ -2862,6 +3019,7 @@ class FrontEndActivity : ComponentActivity() {
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
buildWatermark = SessionPrefs.buildWatermarkEnabled(this)
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
bridgeFellBack = SessionPrefs.bridgeFellBack(this)
bridgeFellBackMemory = SessionPrefs.bridgeFellBackForMemory(this)
@@ -2900,6 +3058,19 @@ class FrontEndActivity : ComponentActivity() {
}
val scannedArch = SessionPrefs.activeSteamClientArch(this)
val scannedX64 = scannedArch == "x86_64"
val scannedSoundtracks = runCatching {
(if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.soundtracks(this, scannedArch) else emptyList()) +
com.droiddeck.launcher.frontend.AddedSoundtracks.games(this)
}.getOrDefault(emptyList())
ui.post {
if (scanGeneration == libraryScanGeneration) {
val scanned = if (scanGeneration <= soundtrackAddScan) scannedSoundtracks + soundtracks.filter { cur -> cur.library == Library.ADDED && scannedSoundtracks.none { it.library == Library.ADDED && it.appId == cur.appId } } else scannedSoundtracks
val kept = scanned.filterNot { s -> s.gameFiles?.path?.let { p -> soundtrackRemovals[p]?.let { m -> !m.settled || s.library == Library.ADDED || scanGeneration <= m.scan } } == true }
com.droiddeck.launcher.playback.SoundtrackController.allow(kept.mapNotNull { it.gameFiles?.path })
soundtracks = kept
soundtracksLoaded = true
}
}
val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
val all = games.distinctBy { it.gameId }
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
@@ -3041,6 +3212,8 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.agent.AgentTab.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
}
}, "reset-settings").start()
@@ -3076,6 +3249,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()
@@ -4,6 +4,7 @@ import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
class HomeActivity : Activity() {
override fun attachBaseContext(newBase: android.content.Context) {
@@ -18,15 +19,22 @@ class HomeActivity : Activity() {
}
private fun routeHome() {
val destination = if (HomeApp.isActiveSteamSession()) {
val destination = if (HomeApp.isActiveSteamSession() && !SessionState.pipActive) {
Intent(this, SessionActivity::class.java)
.setAction(SessionService.ACTION_HOME_GUIDE)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
} else {
Intent(this, FrontEndActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
.apply {
val page = com.droiddeck.launcher.core.AppUiPrefs.homePage(this@HomeActivity)
if (page != com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) {
putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, page)
}
}
}
startActivity(destination)
if (SessionState.pipActive && destination.component?.className == FrontEndActivity::class.java.name) HomeApp.showFrontEnd(this, destination)
else startActivity(destination)
finish()
}
}
@@ -18,6 +18,7 @@ import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.graphics.drawable.toBitmap
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlin.math.roundToInt
@@ -41,7 +42,7 @@ object HomeApp {
val userSerial: Long = 0L,
) {
val component get() = ComponentName(packageName, className)
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
val key get() = appKey(packageName, className, userSerial)
val work get() = userSerial != 0L
}
@@ -101,6 +102,9 @@ object HomeApp {
?: resolved.loadLabel(pm)?.toString()?.trim()?.takeIf { it.isNotEmpty() }
}
private fun appKey(packageName: String, className: String, userSerial: Long) =
"$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
fun roleRequestIntent(context: Context): Intent? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null
val roles = context.getSystemService(RoleManager::class.java) ?: return null
@@ -116,13 +120,25 @@ object HomeApp {
val pm = context.packageManager
val own = Process.myUserHandle()
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
val densityDpi = context.resources.displayMetrics.densityDpi
val pack = IconPack.active(context)
val appColors = IconPack.appColors(context)
HomeIcons.load(context)
val overrides = HomeIcons.overrides
val apps = users.userProfiles.flatMap { user ->
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
val component = info.componentName
if (component.packageName == context.packageName && user == own) return@mapNotNull null
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
val icon = runCatching {
(overrides[appKey(component.packageName, component.className, serial)]
?.let { IconPack.drawable(context, it.pack, it.drawable, densityDpi) }
?: pack?.icon(component, densityDpi)
?: pack?.plated(info.getIcon(0), iconPx, densityDpi, appColors))
?.let { pm.getUserBadgedIcon(it, user) }
?.toBitmap(iconPx, iconPx)
}.getOrNull() ?: runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
val app = info.applicationInfo
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
@Suppress("DEPRECATION")
@@ -181,7 +197,10 @@ object HomeApp {
}
private fun syncRecents(activity: android.app.Activity) =
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
keepOutOfRecents(
activity,
activity is FrontEndActivity && !SessionState.running && isDefault(activity) && AppUiPrefs.hideHomeFromRecents(activity),
)
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
@@ -243,6 +262,19 @@ object HomeApp {
fun isActiveSteamSession(): Boolean =
SessionState.running && SessionState.mode == SessionService.MODE_STEAM
fun showFrontEnd(context: Context, intent: Intent = Intent(context, FrontEndActivity::class.java)) {
val frontEnd = FrontEndActivity::class.java.name
val tasks = runCatching { context.getSystemService(android.app.ActivityManager::class.java)?.appTasks }.getOrNull().orEmpty()
val own = tasks.firstOrNull { task ->
runCatching { task.taskInfo.let { it.baseIntent.component?.className == frontEnd && it.topActivity?.className == frontEnd } }
.getOrDefault(false)
}
val launch = Intent(intent).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
if (own != null && runCatching { own.startActivity(context, launch, null) }.isSuccess) return
// The session task shares the front end's affinity, so without MULTIPLE_TASK the front end lands inside the session's PiP window.
context.startActivity(launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK))
}
fun openSystemHomeSettings(context: Context) {
try {
context.startActivity(settingsIntent())
@@ -0,0 +1,46 @@
package com.droiddeck.launcher
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
object HomeIcons {
private const val PREFS = "home_launcher"
private const val KEY = "icon_overrides"
private const val SEPARATOR = '\t'
data class Choice(val pack: String, val drawable: String)
var overrides by mutableStateOf<Map<String, Choice>>(emptyMap())
private set
@Volatile private var loaded = false
@Synchronized
fun load(context: Context) {
if (loaded) return
overrides = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
.getStringSet(KEY, emptySet()).orEmpty().mapNotNull(::decode).toMap()
loaded = true
}
fun set(context: Context, key: String, pack: String, drawable: String) = save(context, overrides + (key to Choice(pack, drawable)))
fun clear(context: Context, key: String) = save(context, overrides - key)
fun clearAll(context: Context) = save(context, emptyMap())
private fun save(context: Context, next: Map<String, Choice>) {
overrides = next
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putStringSet(KEY, next.map { (key, choice) -> encode(key, choice) }.toSet()).apply()
}
internal fun encode(key: String, choice: Choice) = listOf(key, choice.pack, choice.drawable).joinToString(SEPARATOR.toString())
internal fun decode(entry: String): Pair<String, Choice>? {
val parts = entry.split(SEPARATOR)
if (parts.size != 3 || parts.any { it.isEmpty() }) return null
return parts[0] to Choice(parts[1], parts[2])
}
}
@@ -0,0 +1,198 @@
package com.droiddeck.launcher
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.Xml
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.createBitmap
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.drawable.toDrawable
import androidx.palette.graphics.Palette
import org.xmlpull.v1.XmlPullParser
import java.time.LocalDate
import kotlin.math.roundToInt
object IconPack {
const val NONE = ""
private const val PREFS = "home_launcher"
private const val KEY = "icon_pack"
private const val APP_COLORS = "icon_pack_app_colors"
private const val FILTER = "appfilter"
private const val DRAWABLES = "drawable"
private val ACTIONS = listOf("org.adw.launcher.THEMES", "com.novalauncher.THEME")
data class Pack(val packageName: String, val label: String)
internal data class Plate(val back: String?, val mask: String?, val upon: String?, val scale: Float)
internal data class Filter(val icons: Map<String, String>, val calendars: Map<String, String>, val plate: Plate?) {
fun names(component: String, day: Int) = listOfNotNull(calendars[component]?.plus(day), icons[component])
}
class Loaded internal constructor(
private val resources: Resources,
internal val pack: String,
internal val updatedAt: Long,
private val filter: Filter,
) {
fun icon(component: ComponentName, densityDpi: Int) =
filter.names(component.flattenToString(), LocalDate.now().dayOfMonth).firstNotNullOfOrNull { load(resources, pack, it, densityDpi) }
val hasBack get() = filter.plate?.back != null
fun plated(icon: Drawable, size: Int, densityDpi: Int, appColor: Boolean): Drawable? {
val plate = filter.plate ?: return null
fun image(name: String?) = name?.let { load(resources, pack, it, densityDpi) }?.toBitmap(size, size)
val base = icon.toBitmap(size, size)
val color = if (appColor) Palette.from(base).generate().getDominantColor(0).takeIf { it != 0 } else null
return compose(base, image(plate.back), image(plate.mask), image(plate.upon), plate.scale, color).toDrawable(resources)
}
}
@Volatile private var cached: Loaded? = null
fun selected(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, NONE).orEmpty()
fun select(context: Context, pack: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, pack).apply()
}
fun appColors(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(APP_COLORS, false)
fun setAppColors(context: Context, on: Boolean) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(APP_COLORS, on).apply()
}
fun installed(context: Context): List<Pack> {
val pm = context.packageManager
return ACTIONS.flatMap { pm.queryIntentActivities(Intent(it), 0) }
.map { it.activityInfo.applicationInfo }
.distinctBy { it.packageName }
.filter { app -> resources(pm, app.packageName)?.let { withXml(it, app.packageName, FILTER) { true } } == true }
.map { app -> Pack(app.packageName, app.loadLabel(pm).toString().trim().ifEmpty { app.packageName }) }
.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
}
fun active(context: Context): Loaded? {
val pack = selected(context)
if (pack == NONE) return null
val pm = context.packageManager
val updatedAt = runCatching { pm.getPackageInfo(pack, 0).lastUpdateTime }.getOrNull() ?: return null
cached?.takeIf { it.pack == pack && it.updatedAt == updatedAt }?.let { return it }
val resources = resources(pm, pack) ?: return null
val filter = withXml(resources, pack, FILTER) { parse(it) } ?: return null
return Loaded(resources, pack, updatedAt, filter).also { cached = it }
}
fun drawable(context: Context, pack: String, name: String, densityDpi: Int): Drawable? {
val resources = resources(context.packageManager, pack) ?: return null
return load(resources, pack, name, densityDpi)
}
fun names(context: Context, pack: String): List<String> {
val resources = resources(context.packageManager, pack) ?: return emptyList()
return withXml(resources, pack, DRAWABLES) { parseNames(it) }?.takeIf { it.isNotEmpty() }
?: withXml(resources, pack, FILTER) { parse(it).icons.values.distinct().sorted() }.orEmpty()
}
private fun resources(pm: PackageManager, pack: String): Resources? =
runCatching { pm.getResourcesForApplication(pack) }.getOrNull()
private fun load(resources: Resources, pack: String, name: String, densityDpi: Int): Drawable? {
val id = resources.getIdentifier(name, "drawable", pack).takeIf { it != 0 }
?: resources.getIdentifier(name, "mipmap", pack).takeIf { it != 0 }
?: return null
return runCatching { ResourcesCompat.getDrawableForDensity(resources, id, densityDpi, null) }.getOrNull()
}
internal fun parseNames(xml: XmlPullParser): List<String> {
val names = LinkedHashSet<String>()
forEachTag(xml) { if (xml.name == "item") xml.getAttributeValue(null, "drawable")?.trim()?.takeIf { it.isNotEmpty() }?.let { names.add(it) } }
return names.toList()
}
internal fun parse(xml: XmlPullParser): Filter {
val icons = HashMap<String, String>()
val calendars = HashMap<String, String>()
var back: String? = null
var mask: String? = null
var upon: String? = null
var scale = 1f
fun image() = xml.getAttributeValue(null, "img1")?.trim()?.takeIf { it.isNotEmpty() }
forEachTag(xml) {
when (xml.name) {
"item" -> {
val key = componentKey(xml.getAttributeValue(null, "component"))
val drawable = xml.getAttributeValue(null, "drawable")?.trim()
if (key != null && !drawable.isNullOrEmpty()) icons.putIfAbsent(key, drawable)
}
"calendar" -> {
val key = componentKey(xml.getAttributeValue(null, "component"))
val prefix = xml.getAttributeValue(null, "prefix")?.trim()
if (key != null && !prefix.isNullOrEmpty()) calendars.putIfAbsent(key, prefix)
}
"iconback" -> back = back ?: image()
"iconmask" -> mask = mask ?: image()
"iconupon" -> upon = upon ?: image()
"scale" -> scale = xml.getAttributeValue(null, "factor")?.toFloatOrNull() ?: scale
}
}
return Filter(icons, calendars, if (back == null && mask == null && upon == null) null else Plate(back, mask, upon, scale))
}
internal fun compose(icon: Bitmap, back: Bitmap?, mask: Bitmap?, upon: Bitmap?, scale: Float, backColor: Int? = null): Bitmap {
val size = icon.width
val inset = (size * (1 - scale) / 2).roundToInt()
val result = createBitmap(size, size)
val canvas = Canvas(result)
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
val full = Rect(0, 0, size, size)
canvas.drawBitmap(icon, null, Rect(inset, inset, size - inset, size - inset), paint)
mask?.let {
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
canvas.drawBitmap(it, null, full, paint)
}
back?.let {
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)
paint.colorFilter = backColor?.let { color -> PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN) }
canvas.drawBitmap(it, null, full, paint)
}
paint.xfermode = null
paint.colorFilter = null
upon?.let { canvas.drawBitmap(it, null, full, paint) }
return result
}
private inline fun forEachTag(xml: XmlPullParser, block: () -> Unit) {
var event = xml.eventType
while (event != XmlPullParser.END_DOCUMENT) {
if (event == XmlPullParser.START_TAG) block()
event = xml.next()
}
}
internal fun componentKey(component: String?): String? =
component?.trim()?.removePrefix("ComponentInfo{")?.removeSuffix("}")?.let(ComponentName::unflattenFromString)?.flattenToString()
private fun <T> withXml(resources: Resources, pack: String, file: String, block: (XmlPullParser) -> T): T? = runCatching {
val xml = resources.getIdentifier(file, "xml", pack)
val raw = resources.getIdentifier(file, "raw", pack)
if (xml != 0) resources.getXml(xml).use(block)
else (if (raw != 0) resources.openRawResource(raw) else resources.assets.open("$file.xml"))
.use { stream -> block(Xml.newPullParser().also { it.setInput(stream, null) }) }
}.getOrNull()
}
@@ -151,7 +151,7 @@ import com.droiddeck.launcher.ui.sessionDrawerPages
import com.droiddeck.launcher.ui.step
import kotlin.math.abs
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -159,6 +159,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
private var pipUi by mutableStateOf(false)
override val petBlocked: Boolean get() = drawerOpenState || pipUi || pcKeyboardOpen
private var pipAutoEnter by mutableStateOf(false)
private var unfoldedControls by mutableStateOf(false)
private var unfoldedControlsWithController by mutableStateOf(false)
@@ -452,6 +454,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerDefaultProton by mutableStateOf<String?>(null)
private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) }
private var drawerGameProfileId by mutableStateOf<Long?>(null)
private var drawerGameProfileSelectionMade = false
private var fpsLimit by mutableStateOf(SessionState.fpsLimit)
private fun noSteamSession(): Boolean = (SessionState.mode == SessionService.MODE_RUN &&
@@ -460,7 +463,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET,
)) || SessionState.mode == SessionService.MODE_DESKTOP
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
private var drawerGameInventoryRevision = 0L
@Volatile private var drawerGameInventoryRevision = 0L
private var drawerGameFexPresetSaving by mutableStateOf(false)
private var drawerGameNoSteamSaving by mutableStateOf(false)
private val drawerGameProfileFollowState = GameProfileFollowState()
@@ -556,8 +559,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
private var frameGenActiveGameId by mutableStateOf<Long?>(null)
private var frameGenActiveGameName by mutableStateOf<String?>(null)
private var frameGenHasGameOverride by mutableStateOf(false)
private var frameGenPip = false
private val frameGenRequests = java.util.concurrent.atomic.AtomicInteger()
private val frameGenActivityGeneration = synchronized(frameGenGlobalLock) {
frameGenGlobalGeneration.incrementAndGet()
}
@Volatile private var frameGenActivityActive = true
private val frameGenForcePending = java.util.concurrent.atomic.AtomicBoolean()
@Volatile private var frameGenInventoryIds: Set<Long>? = null
@Volatile private var frameGenInventoryRevision = -1L
private val frameGenInventoryLock = Any()
@Volatile private var frameGenInventoryLastAttemptAt = 0L
private val frameGenInventoryRetryScheduled = java.util.concurrent.atomic.AtomicBoolean()
private val frameGenInventoryRefreshScheduled = java.util.concurrent.atomic.AtomicBoolean()
@Volatile private var appliedFrameGenMode: FrameGen.Mode? = null
@Volatile private var appliedFrameGenHz: Float? = null
private var fexPreset by mutableStateOf("")
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
@@ -674,6 +694,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AgentGuest.readyListener = agentReadyListener
com.droiddeck.launcher.agent.AgentAttachments.gameFrame = gameFrame
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isMaintaining()) {
runtimeRemovalBlocked = true
@@ -859,7 +880,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
hud.attach(root, root.childCount)
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
hud.onPresentingWindowChanged = {
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
CompositorHost.rearmFrameGen { applyFrameGen(force = true) }
}
if (SessionState.running && SessionState.firstFrameSeen) {
loading.visible = false
@@ -892,8 +913,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
glassesScope.launch { com.droiddeck.launcher.handtracking.HandTracking.settings.collect { updateHandCamera() } }
glassesScope.launch {
var lastRunGameId: String? = null
while (true) {
updateTrackingRecovery()
if (SessionState.mode == SessionService.MODE_RUN) {
val gameId = SessionState.gameId
?.takeIf { it.toLongOrNull() != null }
?: intent.getStringExtra(SessionService.EXTRA_GAME_ID)
?.takeIf { it.toLongOrNull() != null }
if (gameId != lastRunGameId) {
lastRunGameId = gameId
if (drawerGameProfileFollowState.followsSteam) {
loadFrameGenFor(gameId?.toLongOrNull())
}
applyFrameGen()
}
} else {
lastRunGameId = null
}
kotlinx.coroutines.delay(100)
}
}
@@ -956,7 +993,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
applyOutputPacing()
if (pipUi != frameGenPip) {
frameGenPip = pipUi
if (FrameGen.engine(this@SessionActivity) != FrameGen.ENGINE_OFF && ::surfaceView.isInitialized) applyFrameGen()
if (::surfaceView.isInitialized) applyFrameGen()
}
}
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
@@ -1032,7 +1069,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
},
)
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty()) {
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty(), drawerGameInventoryRevision) {
val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" }
else {
@@ -1045,11 +1082,40 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
}
if (SessionState.mode == SessionService.MODE_STEAM) {
val target = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
val games = LibraryCache.load(this@SessionActivity)
val cachedIds = games.mapNotNull { it.profileKey.toLongOrNull() }.toSet()
val inventoryIds = synchronized(frameGenInventoryLock) {
frameGenInventoryIds
}.orEmpty()
val id = AgentGuest.activeSteamAppId(
this@SessionActivity, cachedIds + inventoryIds
)
val name = id?.let { activeId ->
games.firstOrNull { it.profileKey == activeId.toString() }?.name
}
id to name
}
if (target.first != frameGenActiveGameId) {
frameGenActiveGameId = target.first
if (drawerGameProfileFollowState.followsSteam) {
loadFrameGenFor(target.first)
}
}
frameGenActiveGameName = target.second
}
if (nextGame != gestureGame) {
if (nextGame != null) gameStarts++
gestureGame = nextGame
refreshGestureConfig()
}
if (
SessionState.mode == SessionService.MODE_STEAM &&
CompositorHost.isStarted
) {
applyFrameGen()
}
if (secondScreenDisplays.isNotEmpty()) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
}
@@ -1234,6 +1300,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy,
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
frameGen = frameGen,
frameGenTargetGameId = frameGenTargetGameId()?.toString(),
frameGenTargetGameName = when {
!drawerGameProfileFollowState.followsSteam ->
drawerGameProfileRefresh.data?.profiles
?.firstOrNull { it.first == frameGenTargetGameId() }?.second
SessionState.mode == SessionService.MODE_STEAM -> frameGenActiveGameName
SessionState.mode == SessionService.MODE_RUN ->
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program)
else -> drawerGameProfileRefresh.data?.profiles
?.firstOrNull { it.first == frameGenTargetGameId() }?.second
},
hasGameOverride = frameGenHasGameOverride,
lossless = lossless,
oscMode = oscMode, suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode,
@@ -1253,7 +1331,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onHudSetting = { key, value -> hudConfig = DroidDeckHudConfig.set(this@SessionActivity, key, value); hud.applyConfig() },
onHudOrder = { switches, order -> hudConfig = DroidDeckHudConfig.choose(this@SessionActivity, switches, order); hud.applyConfig() },
onHudReset = { hudConfig = DroidDeckHudConfig.reset(this@SessionActivity); hud.applyConfig() },
onHudOrderReset = { hudConfig = DroidDeckHudConfig.clearOrder(this@SessionActivity); hud.applyConfig() },
onHudExport = { exportHudDiagnostics() },
onUpscaler = { m ->
SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m
@@ -1293,9 +1373,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
applyOutputPacing()
},
onFrameGenPick = { mode ->
FrameGen.set(this@SessionActivity, mode)
val appId = frameGenTargetGameId()
if (appId == null) FrameGen.set(this@SessionActivity, mode)
else FrameGen.setForGame(this@SessionActivity, appId.toString(), mode)
loadFrameGenFor(appId)
readPrefs()
applyFrameGen()
applyFrameGen(force = true)
},
onFrameGenReset = {
val appId = frameGenTargetGameId()
if (appId == null) FrameGen.clearGlobal(this@SessionActivity)
else FrameGen.clearGame(this@SessionActivity, appId.toString())
loadFrameGenFor(appId)
readPrefs()
applyFrameGen(force = true)
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(
@@ -1628,9 +1721,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}, "drawer-components").start()
}
private fun frameGenTargetGameId(): Long? {
if (!drawerGameProfileFollowState.followsSteam) {
return drawerGameProfileId
}
if (SessionState.mode == SessionService.MODE_RUN) {
return (
SessionState.gameId?.toLongOrNull()
?: intent.getStringExtra(SessionService.EXTRA_GAME_ID)?.toLongOrNull()
)
}
if (SessionState.mode == SessionService.MODE_STEAM) {
return frameGenActiveGameId
}
return drawerGameProfileId
}
private fun loadFrameGenFor(appId: Long?) {
val profileId = appId?.toString()
frameGen = FrameGen.mode(this, profileId)
frameGenHasGameOverride = appId?.let {
FrameGen.hasGameOverride(this, it.toString())
} == true
}
private fun selectDrawerGameProfile(appId: Long?) {
drawerGameProfileFollowState.selectManually()
drawerGameProfileSelectionMade = true
drawerGameProfileId = appId
loadFrameGenFor(frameGenTargetGameId())
drawerGameProfileRefresh = drawerGameProfileRefresh.retrying()
readDrawerTextureFiltering(appId)
refreshDrawerGameProfile()
@@ -1703,6 +1822,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (refresh.followsSteam) {
if (drawerGameProfileFollowState.followsSteam) {
drawerGameProfileId = result.selectedAppId
loadFrameGenFor(result.selectedAppId)
readDrawerTextureFiltering(result.selectedAppId)
}
}
@@ -1727,6 +1847,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
gameProtonId = ProtonDefault.gameSelectedId(this, game.profileKey, protons),
gameComponents = ComponentsManager.gameComponents(this, game.profileKey),
gameWindowsComponents = WinComponents.picks(this, game.profileKey),
frameGenMode = FrameGen.mode(this, game.profileKey),
frameGenInherited = !FrameGen.hasGameOverride(this, game.profileKey),
)
}
@@ -1970,7 +2092,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset()
routedTouchMode = nextRoutedTouchMode
requestRelativeMouse()
frameGen = FrameGen.mode(this)
loadFrameGenFor(frameGenTargetGameId())
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
@@ -2114,11 +2236,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun installRuntime(): String? {
val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease()
?: return getString(R.string.session_runtime_catalog_unreachable)
if (release == null) {
SessionEvents.record("runtime.failed", mapOf("step" to "catalog", "reason" to com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.catalogError()))
return getString(R.string.session_runtime_catalog_unreachable)
}
runCatching { com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release) }
val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release,
progressFor(RUNTIME_LINES, release.size / 1_000_000))
return if (ok) null else getString(R.string.session_runtime_install_failed)
if (ok) return null
SessionEvents.record("runtime.failed", mapOf("step" to "install", "reason" to com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installError()))
return getString(R.string.session_runtime_install_failed)
}
private fun installDesktop(): String? {
@@ -2257,7 +2384,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (resized) {
cancelTouchGestures()
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
CompositorHost.resize(holder.surface) { applyFrameGen() }
CompositorHost.resize(holder.surface) { applyFrameGen(force = true) }
resizeOutputForWindow(width, height)
}
}
@@ -2398,17 +2525,161 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private fun applyFrameGen() {
private fun frameGenModeForActiveGame(request: Int): FrameGen.Mode {
if (SessionState.mode == SessionService.MODE_RUN) {
val activeAppId = (
SessionState.gameId?.takeIf { it.toLongOrNull() != null }
?: intent.getStringExtra(SessionService.EXTRA_GAME_ID)
)?.toLongOrNull()
return FrameGen.mode(this, activeAppId?.toString())
}
val cachedIds = LibraryCache.load(this)
.mapNotNull { it.profileKey.toLongOrNull() }
.toSet()
var inventoryRevision = drawerGameInventoryRevision
var ids = synchronized(frameGenInventoryLock) {
if (frameGenInventoryRevision != inventoryRevision) {
frameGenInventoryIds = null
frameGenInventoryRevision = inventoryRevision
frameGenInventoryLastAttemptAt = 0L
}
frameGenInventoryIds
}
if (ids == null) {
val now = SystemClock.elapsedRealtime()
val shouldScan = synchronized(frameGenInventoryLock) {
val currentRevision = drawerGameInventoryRevision
if (frameGenInventoryRevision != currentRevision) {
frameGenInventoryIds = null
frameGenInventoryRevision = currentRevision
frameGenInventoryLastAttemptAt = 0L
}
inventoryRevision = currentRevision
if (frameGenInventoryIds != null) {
false
} else if (
frameGenInventoryLastAttemptAt != 0L &&
now - frameGenInventoryLastAttemptAt < 15_000L
) {
false
} else {
frameGenInventoryLastAttemptAt = now
true
}
}
if (shouldScan) {
val currentIds = runCatching {
Library.launchableGames(this, strictRead = true)
.mapNotNull { it.profileKey.toLongOrNull() }
.toSet()
}.getOrNull()
if (currentIds == null) {
if (frameGenInventoryRetryScheduled.compareAndSet(false, true)) {
uiHandler.postDelayed({
frameGenInventoryRetryScheduled.set(false)
val retry = synchronized(frameGenInventoryLock) {
frameGenInventoryIds == null
}
if (retry && !isFinishing && !isDestroyed) {
applyFrameGen()
}
}, 15_000L)
}
} else {
var published = false
synchronized(frameGenInventoryLock) {
if (drawerGameInventoryRevision == inventoryRevision &&
frameGenInventoryRevision == inventoryRevision
) {
ids = cachedIds + currentIds
frameGenInventoryIds = ids
published = true
}
}
if (published) {
if (frameGenInventoryRefreshScheduled.compareAndSet(false, true)) {
uiHandler.postDelayed({
frameGenInventoryRefreshScheduled.set(false)
if (frameGenActivityActive && !isFinishing && !isDestroyed) {
synchronized(frameGenInventoryLock) {
frameGenInventoryIds = null
frameGenInventoryLastAttemptAt = 0L
}
applyFrameGen()
}
}, 15_000L)
}
if (frameGenRequests.get() != request) {
applyFrameGen()
}
}
}
}
if (ids == null) {
ids = synchronized(frameGenInventoryLock) {
frameGenInventoryIds
} ?: emptySet()
}
}
val activeAppId = AgentGuest.activeSteamAppId(
this, cachedIds + (ids ?: emptySet())
)
if (activeAppId == null) return FrameGen.Mode.OFF
return FrameGen.mode(this, activeAppId.toString())
}
private fun applyFrameGen(force: Boolean = false) {
val request = synchronized(frameGenGlobalLock) {
if (force) frameGenForcePending.set(true)
frameGenRequests.incrementAndGet()
}
val hz = refreshHz()
val pip = pipUi && mirrorRefreshLimit() <= 0
val request = frameGenRequests.incrementAndGet()
Thread({
val problem = synchronized(frameGenRequests) {
val mode = if (pip) FrameGen.Mode.OFF else frameGenModeForActiveGame(request)
val needsApply = synchronized(frameGenGlobalLock) {
if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@Thread
if (request != frameGenRequests.get()) return@Thread
if (pip) FrameGen.apply(this, FrameGen.Mode.OFF, hz) else FrameGen.apply(this, hz)
if (!frameGenActivityActive || isFinishing || isDestroyed) return@Thread
val lastAppliedHz = appliedFrameGenHz
frameGenForcePending.get() || appliedFrameGenMode == null ||
mode != appliedFrameGenMode || lastAppliedHz == null ||
kotlin.math.abs(lastAppliedHz - hz) > 0.1f
}
val prepared = if (needsApply) FrameGen.prepareApply(this, mode) else null
val problem = synchronized(frameGenGlobalLock) {
if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@Thread
if (request != frameGenRequests.get()) return@Thread
if (!frameGenActivityActive || isFinishing || isDestroyed) return@Thread
val forcePending = frameGenForcePending.get()
val lastAppliedHz = appliedFrameGenHz
if (!forcePending && appliedFrameGenMode != null && mode == appliedFrameGenMode &&
lastAppliedHz != null && kotlin.math.abs(lastAppliedHz - hz) <= 0.1f
) {
null
} else {
val ready = prepared ?: return@Thread
frameGenForcePending.set(false)
FrameGen.applyPrepared(this, ready, hz).also { problem ->
if (problem == null) {
appliedFrameGenMode = mode
appliedFrameGenHz = hz
} else {
appliedFrameGenMode = null
appliedFrameGenHz = null
}
}
}
}
val state = Lossless.state(this)
runOnUiThread {
if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@runOnUiThread
lossless = state
if (problem != null) Toast.makeText(this, problem, Toast.LENGTH_LONG).show()
}
@@ -2425,12 +2696,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun importLossless(dll: File) {
Thread({
val message = Lossless.message(this, Lossless.import(this, dll))
val result = Lossless.import(this, dll)
val message = Lossless.message(this, result)
val state = Lossless.state(this)
runOnUiThread {
lossless = state
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
if (FrameGen.engine(this) == FrameGen.ENGINE_LSFG) applyFrameGen()
applyFrameGen(force = result == Lossless.ImportResult.UPDATED)
}
}, "lossless-import").start()
}
@@ -2637,6 +2909,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
val steamVolume =
@@ -3492,37 +3765,46 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
runningGame = { gestureGame },
))
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
private fun captureScreenshot(onDone: (Boolean) -> Unit) = copyGameFrame { bitmap ->
if (bitmap == null) {
onDone(false)
return@copyGameFrame
}
Thread {
val saved = com.droiddeck.launcher.session.BottomScreenshots.save(applicationContext, bitmap)
bitmap.recycle()
runOnUiThread { onDone(saved) }
}.start()
}
private val gameFrame: ((android.graphics.Bitmap?) -> Unit) -> Unit = { copyGameFrame(it) }
/** The game's own surface, without anything DroidDeck draws over it; the caller recycles the bitmap. */
private fun copyGameFrame(onFrame: (android.graphics.Bitmap?) -> Unit) {
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (bottomOutputActive) bottomGame?.surfaceView
else if (::surfaceView.isInitialized) surfaceView else null
val width = source?.width ?: 0
val height = source?.height ?: 0
if (source == null || width <= 0 || height <= 0 || source.holder.surface?.isValid != true) {
onDone(false)
onFrame(null)
return
}
val bitmap = try {
android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888)
} catch (_: OutOfMemoryError) {
onDone(false)
onFrame(null)
return
}
try {
android.view.PixelCopy.request(source, bitmap, { result ->
if (result != android.view.PixelCopy.SUCCESS) {
bitmap.recycle()
onDone(false)
return@request
}
Thread {
val saved = com.droiddeck.launcher.session.BottomScreenshots.save(applicationContext, bitmap)
bitmap.recycle()
runOnUiThread { onDone(saved) }
}.start()
onFrame(null)
} else onFrame(bitmap)
}, uiHandler)
} catch (_: IllegalArgumentException) {
bitmap.recycle()
onDone(false)
onFrame(null)
}
}
@@ -4708,12 +4990,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onResume() {
super.onResume()
drawerGameInventoryRevision++
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
}
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
}
if (CompositorHost.isStarted) applyFrameGen(force = true)
applyFollowOrientation(resources.configuration)
if (runtimeRemovalBlocked) return
if (!SessionState.suspended) pausedFrame = null
@@ -5391,7 +5675,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onDestroy() {
synchronized(frameGenGlobalLock) {
frameGenActivityActive = false
frameGenRequests.incrementAndGet()
}
if (AgentGuest.readyListener === agentReadyListener) AgentGuest.readyListener = null
if (com.droiddeck.launcher.agent.AgentAttachments.gameFrame === gameFrame) com.droiddeck.launcher.agent.AgentAttachments.gameFrame = null
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
relativeMouseRequests.shutdownNow()
backQamInput.cancel()
@@ -5505,6 +5794,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val BOTTOM_RECOVERY_MS = 1_000L
private const val BOTTOM_RECOVERY_TRIES = 3
private const val TAG = "SessionActivity"
private val frameGenGlobalLock = Any()
private val frameGenGlobalGeneration = java.util.concurrent.atomic.AtomicLong(0L)
private var startedScreens = 0
@Volatile private var activeInstallWorker: Any? = null
private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need"
@@ -17,6 +17,7 @@ import com.droiddeck.launcher.ui.UpdatesActions
import com.droiddeck.launcher.ui.UpdatesState
import com.droiddeck.launcher.update.AppUpdates
import com.droiddeck.launcher.update.SelfInstaller
import com.droiddeck.launcher.update.UpdateWatch
internal class UpdatesMenu(private val activity: Activity, private val ui: Handler) {
var catalog by mutableStateOf<AppUpdates.Catalog?>(null)
@@ -43,6 +44,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
.onFailure { error = activity.getString(R.string.upd_unknown_apps_failed); pending = null }
},
onDismissPermission = { askPermission = false; pending = null },
onSeen = { r -> UpdateWatch.seen(activity, r) },
)
val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow)
@@ -77,6 +79,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
private fun choose(f: AppUpdates.Follow) {
AppUpdates.setFollow(activity, f)
UpdateWatch.sync(activity, f, catalog?.let { AppUpdates.release(it, f) })
follow = f
error = null
}
@@ -23,7 +23,7 @@ object AgentAccess {
fun requireCommands(context: Context) {
if (!commandsAllowed(context)) throw AgentException(
"AGENT_COMMANDS_DISABLED",
"Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device",
"Debugging tools are off: turn on Setup > Developer > Debugging tools on the device",
)
}
@@ -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,87 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.provider.OpenableColumns
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
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
}
/** Copies the running game's frame; set while a session is open. */
var gameFrame by mutableStateOf<(((Bitmap?) -> Unit) -> Unit)?>(null)
/** Saves [frame] for [chat] (or a new conversation) on the calling thread; returns its guest path. */
fun saveFrame(context: Context, chat: String?, frame: Bitmap): String? = runCatching {
val folder = chat ?: NEW
val dir = File(hostDir(context), folder).apply { mkdirs() }
val target = File(dir, "game-${System.currentTimeMillis()}.jpg")
val written = target.outputStream().use { frame.compress(Bitmap.CompressFormat.JPEG, 88, it) }
if (!written) {
target.delete()
return@runCatching null
}
"$GUEST_DIR/$folder/${target.name}"
}.getOrNull()
/** 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,159 @@
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 }
/** The chats among [chats] where the user or the agent wrote [query], ignoring case. */
fun search(context: Context, chats: List<Chat>, query: String): List<Chat> {
val q = query.trim()
if (q.isEmpty()) return chats
return chats.filter { chat ->
chat.title.contains(q, ignoreCase = true) || read(file(context, chat.id)).entries.any { matches(it, q) }
}
}
internal fun matches(entry: Entry, query: String) = when (entry) {
is Entry.Asked -> entry.text.contains(query, ignoreCase = true)
is Entry.Said -> entry.text.contains(query, ignoreCase = true)
else -> false
}
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 { if (entry.parent.isNotEmpty()) put("parent", entry.parent) }
.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 {
if (entry.planned) put("planned", true)
entry.usage?.let {
put("ms", it.durationMs).put("cost", it.costUsd).put("in", it.inputTokens).put("out", it.outputTokens)
if (it.context > 0) put("ctx", it.context).put("win", it.window)
}
}
}.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.optString("parent"))
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"), o.optLong("ctx"), o.optLong("win")) else null,
o.optBoolean("planned"),
)
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,389 @@
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
/** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */
val efforts: List<String>
/** 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) {}
/** Context and plan limits the CLI keeps on disk rather than printing, read once a turn of [conversation] is done. */
fun usage(rootfs: File, conversation: String?): AgentEvent? = null
data class Model(val id: String, val label: String)
data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: 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,
/** Tokens the model's context can hold. */
val window: Long? = null,
val limits: List<AgentHost.Limit>? = 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
override val efforts = listOf("low", "medium", "high", "xhigh", "max")
/**
* 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.effort?.let { addAll(listOf("--effort", 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() }
// A subagent's messages carry the call that started it; only its tool calls are shown, under that call.
val parent = o.optString("parent_tool_use_id").takeIf { it.isNotEmpty() && it != "null" }
return when (o.optString("type")) {
"stream_event" -> {
if (parent != null) return null
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" -> if (parent != null) null else block.optString("text").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Said(it) }
"thinking" -> if (parent != null) null else 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), parent = parent.orEmpty())
}
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 && parent == null })
}
"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)
}
"rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info")))
// 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)),
window = window(o.optJSONObject("modelUsage")),
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 val WINDOW_MINUTES = mapOf("five_hour" to 300, "seven_day" to 10_080)
@VisibleForTesting
internal fun limits(info: JSONObject?): List<AgentHost.Limit>? {
val windows = info?.optJSONObject("unifiedWindows") ?: return null
return WINDOW_MINUTES.mapNotNull { (key, minutes) ->
val w = windows.optJSONObject(key) ?: return@mapNotNull null
AgentHost.Limit(minutes, (w.optDouble("utilization", 0.0) * 100).toInt(), w.optLong("resetsAt"))
}.takeIf { it.isNotEmpty() }
}
/** The context window of the model that did most of the turn; subagents may run a smaller one. */
private fun window(models: JSONObject?): Long? {
models ?: return null
return models.keys().asSequence().mapNotNull { models.optJSONObject(it) }
.maxByOrNull { it.optDouble("costUSD", 0.0) }?.optLong("contextWindow")?.takeIf { it > 0 }
}
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" + lineDiff(input.optString("old_string"), input.optString("new_string"))
tool == "Write" -> input.optString("file_path") + "\n" + lineDiff("", 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
override val efforts = listOf("low", "medium", "high")
/** 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)) }
options.effort?.let { addAll(listOf("-c", "model_reasoning_effort=\"$it\"")) }
// codex exec has no system prompt option, so a new conversation starts with the brief.
add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message)
}
override fun 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 const val TOKEN_COUNT = "\"payload\":{\"type\":\"token_count\""
/** Codex prints no limits with --json; its session log, named after the thread, has a token_count event each step. */
override fun usage(rootfs: File, conversation: String?): AgentEvent? {
conversation ?: return null
val log = File(rootfs, "root/.codex/sessions").walkBottomUp().filter { it.isFile && it.name.endsWith("-$conversation.jsonl") }
.maxByOrNull { it.lastModified() } ?: return null
val last = runCatching { log.readLines().lastOrNull { it.contains(TOKEN_COUNT) } }.getOrNull() ?: return null
return tokenCount(last)
}
@VisibleForTesting
internal fun tokenCount(line: String): AgentEvent? {
val payload = runCatching { JSONObject(line).optJSONObject("payload") }.getOrNull()?.takeIf { it.optString("type") == "token_count" } ?: return null
val info = payload.optJSONObject("info")
val rates = payload.optJSONObject("rate_limits")
val limits = listOf("primary", "secondary").mapNotNull { key ->
val w = rates?.optJSONObject(key) ?: return@mapNotNull null
AgentHost.Limit(w.optInt("window_minutes"), w.optDouble("used_percent", 0.0).toInt(), w.optLong("resets_at"))
}
return AgentEvent(
context = info?.optJSONObject("last_token_usage")?.optLong("total_tokens")?.takeIf { it > 0 },
window = info?.optLong("model_context_window")?.takeIf { it > 0 },
limits = limits.takeIf { it.isNotEmpty() },
)
}
private fun 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 const val DIFF_CONTEXT = 2
/**
* [old] against [new], one line per changed or nearby line, each led by ' ', '-' or '+'. Edits
* replace a short span, so the lines both share at the start and end are cut to [DIFF_CONTEXT].
*/
@VisibleForTesting
internal fun lineDiff(old: String, new: String): String {
val a = if (old.isEmpty()) emptyList() else old.removeSuffix("\n").lines()
val b = if (new.isEmpty()) emptyList() else new.removeSuffix("\n").lines()
var head = 0
while (head < a.size && head < b.size && a[head] == b[head]) head++
var tail = 0
while (tail < a.size - head && tail < b.size - head && a[a.size - 1 - tail] == b[b.size - 1 - tail]) tail++
return buildList {
a.subList(maxOf(0, head - DIFF_CONTEXT), head).forEach { add(" $it") }
a.subList(head, a.size - tail).forEach { add("-$it") }
b.subList(head, b.size - tail).forEach { add("+$it") }
a.subList(a.size - tail, minOf(a.size, a.size - tail + DIFF_CONTEXT)).forEach { add(" $it") }
}.joinToString("\n")
}
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,696 @@
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.OrphanReaper
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. [parent] is the subagent call it was made under, if any. */
data class Used(
val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false,
val parent: String = "",
) : Entry
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
/** [planned]: the turn ran in plan mode, so it ends on a plan that nothing has carried out yet. */
data class Finished(val error: String?, val stopped: Boolean = false, val usage: Usage? = null, val planned: Boolean = false) : Entry
}
/** [context] of [window] tokens is what the conversation held when the turn ended. */
data class Usage(
val durationMs: Long, val costUsd: Double, val inputTokens: Long, val outputTokens: Long,
val context: Long = 0, val window: Long = 0,
)
/** A plan usage limit over a rolling window of [minutes]; [resetsAt] is in epoch seconds. */
data class Limit(val minutes: Int, val usedPercent: Int, val resetsAt: 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"
internal const val GUEST_PATH = "/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
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 inspects and drives the app over loopback adb (\$ADB_SERIAL); its guide is ${AgentSetup.CTL}/agent-control.md. " +
"Steam, the desktop and games run in DroidDeck's session, a separate guest from yours: a program you start here is not in it and has no screen. " +
"Reach the session through droiddeckctl: state, start steam, stop, launch, quit, focus, screenshot, logs, and guest to run a command inside it. " +
"Starting, stopping or restarting a session leaves you running. " +
"Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " +
"End a game with droiddeckctl quit, the session with droiddeckctl stop, anything else by its pid. " +
"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. " +
"To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " +
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message."
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
/** The chosen reasoning effort for [harness]; null is the CLI's default. */
var effort 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
/** Tokens the model's context can hold; 0 until a turn has told. */
var window by mutableLongStateOf(0L)
private set
/** The account's plan limits as [harness] last reported them. */
var limits by mutableStateOf<List<Limit>>(emptyList())
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 turnPlanned = false
private var loaded = false
private var appContext: Context? = null
val turnPid: Int get() = turn?.pid ?: 0
fun seen() {
unseen = false
appContext?.let { AgentNotice.clear(it) }
}
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)
effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts }
plan = prefs(app).getBoolean(PLAN_KEY, false)
limits = decodeLimits(prefs(app).getString(limitsKey(harness), null))
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)
val last = loaded.entries.lastOrNull { it is Entry.Finished && (it.usage?.context ?: 0) > 0 } as? Entry.Finished
context = last?.usage?.context ?: 0
window = last?.usage?.window ?: 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 chooseEffort(context: Context, level: String?) {
effort = level
prefs(context).edit().putString(effortKey(harness), level).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)
turnPlanned = plan && current.plans
val command = current.turn(prompt, conversation, AgentHarness.Options(model, turnPlanned, BRIEF, effort))
val workdir = workspace(app)
var threadConversation = conversation
Thread({
runCatching { current.prepare(LinuxRuntime.rootDir(app)) }
runCatching { AgentSetup.installHelpers(app) }
// Without a session nothing else keeps the userland's resolver current.
runCatching { com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent(app, LinuxRuntime.rootDir(app)).publish() }
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))
OrphanReaper.keep(started.pid)
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 parsed = current.parse(line) ?: return@forEachLine
parsed.conversation?.let { threadConversation = it }
val done = parsed.entries.any { it is Entry.Finished }
if (done) ended = true
val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull()
?.let { parsed.copy(context = it.context ?: parsed.context, window = it.window ?: parsed.window, limits = it.limits ?: parsed.limits) } ?: parsed
main.post { if (turn === started) apply(app, event) }
}
}
runCatching { raw?.close() }
val status = runCatching { child.waitFor() }.getOrDefault(-1)
OrphanReaper.release(started.pid)
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)
}
/** Sends [item] now: the running turn stops where it is, and the rest of the queue waits for the next one. */
fun sendNow(context: Context, item: Queued) {
val app = context.applicationContext
if (!queue.remove(item)) return
val rest = queue.toList()
stop(app)
queue.addAll(rest)
send(app, item.text, item.files)
}
/** 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
window = 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, fakeRoot: Boolean = false): ProcessBuilder {
val adb = AgentAdb.prepare(app)
val env = listOf(
"/usr/bin/env", "HOME=/root", "PATH=$GUEST_PATH", "LANG=C.UTF-8",
"ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}", "DROIDDECK_PACKAGE=${app.packageName}",
"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(), null, env + shell + command, fakeRoot)
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 }
event.window?.let { window = it }
event.limits?.let { reported ->
limits = (limits.filter { old -> reported.none { it.minutes == old.minutes } } + reported).sortedBy { it.minutes }
prefs(app).edit().putString(limitsKey(harness), encodeLimits(limits)).apply()
}
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 = ""
val held = if (context > 0) (usage ?: Usage(0, 0.0, 0, 0)).copy(context = context, window = window) else usage
record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null))
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)
} else if (!stopped) notifyEnded(app, error)
}
private fun notifyEnded(app: Context, error: String?) {
val start = entries.indexOfLast { it is Entry.Asked }
val said = entries.subList(start + 1, entries.size).lastOrNull { it is Entry.Said } as? Entry.Said
val reply = said?.let { choices(it.text) }
val kind = when {
error != null -> AgentNotice.Kind.FAILED
!reply?.options.isNullOrEmpty() -> AgentNotice.Kind.QUESTION
else -> AgentNotice.Kind.DONE
}
AgentNotice.post(app, kind, error ?: reply?.text?.takeIf { it.isNotBlank() }?.let { firstLine(it) } ?: "")
}
/** 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" && it.parent.isEmpty() }?.let { (it as Entry.Used).input }
private fun tick() {
now = SystemClock.elapsedRealtime()
appContext?.let { app ->
claimLabRequest(app)
claimOpenUrl(app)
claimDeviceCode(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
if (!openUrl(app, url)) runCatching { File(app.filesDir, "$OPEN_URL.failed").writeText("") }
}
/** dd-gh-login leaves "<code> <url>" here to float the code over the page, and an empty file when it ends. */
private fun claimDeviceCode(app: Context) {
val request = File(app.filesDir, DEVICE_CODE)
if (!request.isFile) return
val claimed = File(app.filesDir, "$DEVICE_CODE.claimed")
if (!request.renameTo(claimed)) return
val parts = runCatching { claimed.readText().trim() }.getOrDefault("").split(' ', limit = 2)
claimed.delete()
val code = parts[0]
val url = parts.getOrNull(1)?.takeIf { it.startsWith("https://") }
if (code.isEmpty() || url == null) {
com.droiddeck.launcher.DeviceCodeActivity.close()
return
}
if (!com.droiddeck.launcher.DeviceCodeActivity.show(app, code, url, AgentAdb.browserDisplay)) deviceCodeOpened(app, openUrl(app, url))
}
/** Tells dd-gh-login whether the device page opened, so it can fall back to android-open. */
fun deviceCodeOpened(app: Context, opened: Boolean) {
runCatching {
val part = File(app.filesDir, "$DEVICE_CODE.result.part")
part.writeText(if (opened) "ok" else "failed")
part.renameTo(File(app.filesDir, "$DEVICE_CODE.result"))
}
}
private fun openUrl(app: Context, url: String): Boolean {
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()
return runCatching { app.startActivity(intent, options) }
.recoverCatching { app.startActivity(intent) }
.onFailure { Log.w(TAG, "could not open a sign-in link: ${it.javaClass.simpleName}") }
.isSuccess
}
/**
* 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 }
val pid = AgentProcesses.pidOf(child)
OrphanReaper.keep(pid)
try {
child.outputStream.close()
child.inputStream.readBytes()
child.waitFor()
} finally {
OrphanReaper.release(pid)
}
}.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 DEVICE_CODE = "agent/device-code"
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}"
private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}"
@VisibleForTesting
internal fun encodeLimits(list: List<Limit>) = org.json.JSONArray(list.map {
org.json.JSONObject().put("minutes", it.minutes).put("used", it.usedPercent).put("resets", it.resetsAt)
}).toString()
@VisibleForTesting
internal fun decodeLimits(text: String?): List<Limit> = runCatching {
val a = org.json.JSONArray(text ?: return emptyList())
(0 until a.length()).map { a.getJSONObject(it) }.map { Limit(it.optInt("minutes"), it.optInt("used"), it.optLong("resets")) }
}.getOrDefault(emptyList())
private fun effortKey(harness: AgentHarness) = "effort_${harness.id}"
internal fun prefs(context: Context) = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
}
/** A reply split into its text and the options of a trailing choices block. */
internal data class Choices(val text: String, val options: List<String>)
private val FENCE = Regex("""[ \t]{0,3}(`{3,}|~{3,})(.*)""")
/** Walks Markdown fences so a choices block counts only at the top level and only as the last thing in the reply. */
internal fun choices(reply: String): Choices {
val lines = reply.split('\n')
var open = ""
var opener = -1
var openChoices = false
var block: IntRange? = null
lines.forEachIndexed { i, line ->
val fence = FENCE.matchEntire(line)
if (open.isEmpty()) {
if (fence != null) {
open = fence.groupValues[1]
opener = i
openChoices = fence.groupValues[2].trim() == "choices"
block = null
} else if (line.isNotBlank()) block = null
} else if (fence != null && fence.groupValues[1][0] == open[0] && fence.groupValues[1].length >= open.length && fence.groupValues[2].isBlank()) {
block = if (openChoices) opener..i else null
open = ""
}
}
val found = block?.takeIf { open.isEmpty() } ?: return Choices(reply, emptyList())
val options = lines.subList(found.first + 1, found.last).map { it.trim().removePrefix("- ").removePrefix("* ").trim() }.filter { it.isNotEmpty() }
return Choices(lines.subList(0, found.first).joinToString("\n").trimEnd(), options)
}
@@ -0,0 +1,121 @@
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)))
AgentSetup.detail[AgentSetup.Step.GITHUB]?.takeIf {
AgentSetup.status[AgentSetup.Step.GITHUB] == AgentSetup.Status.WORKING && it.startsWith("GitHub device code:")
}?.let { return it }
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,58 @@
package com.droiddeck.launcher.agent
import android.app.ActivityManager
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.ui.AgentPet
/** Tells the user a turn has ended when nothing on screen already does. */
internal object AgentNotice {
private const val CHANNEL_ID = "agent_done"
private const val NOTIFICATION_ID = 4108
enum class Kind { DONE, FAILED, QUESTION }
fun post(context: Context, kind: Kind, text: String) {
if (onScreen(context)) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT))
val open = PendingIntent.getActivity(context, 2,
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 title = context.getString(when (kind) {
Kind.DONE -> R.string.agent_done
Kind.FAILED -> R.string.agent_done_failed
Kind.QUESTION -> R.string.agent_done_question
})
runCatching {
manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(title)
.setContentText(text)
.setStyle(Notification.BigTextStyle().bigText(text))
.setContentIntent(open)
.setAutoCancel(true)
.setCategory(Notification.CATEGORY_STATUS)
.build())
}
}
fun clear(context: Context) {
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
}
/** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */
private fun onScreen(context: Context): Boolean {
if (AgentPet.floating) return true
val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) }
return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
}
@@ -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,208 @@
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 com.droiddeck.launcher.session.OrphanReaper
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", "droiddeckctl")
internal const val CTL = "/root/.local/share/droiddeck/ctl"
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()
}
fun runsAsRoot(step: Step) = step == Step.INSTALL
/** 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; " +
"dpkg --configure -a; apt-get update || echo 'Some package sources could not be refreshed; continuing'; apt-get -f install -y; " +
"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, fakeRoot = runsAsRoot(step)).start()
val pid = AgentProcesses.pidOf(child)
OrphanReaper.keep(pid)
try {
child.outputStream.close()
logFile(app, step).apply { parentFile?.mkdirs() }.bufferedWriter().use { log ->
child.inputStream.bufferedReader().forEachLine { line ->
log.appendLine(line)
val text = line.trim()
if (text.isNotEmpty() && !noise(text)) main.post {
detail[step] = text.take(160)
if (step == Step.GITHUB && text.startsWith("GitHub device code:")) AgentHostService.update(app)
}
}
child.waitFor().also { log.appendLine("exit $it") }
}
} finally {
OrphanReaper.release(pid)
}
}
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()
}
/** The whole output of a step's last run; the card shows only its last line. */
fun logFile(app: Context, step: Step) = File(app.filesDir, "agent/setup-${step.name.lowercase()}.log")
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. */
internal fun installHelpers(app: Context) {
val root = LinuxRuntime.rootDir(app)
val bin = File(root, "root/.local/bin").apply { mkdirs() }
for (name in HELPERS) copyAsset(app, "agent/$name", File(bin, name))
val ctl = File(root, CTL.removePrefix("/")).apply { mkdirs() }
for (name in app.assets.list("agent/ctl").orEmpty()) copyAsset(app, "agent/ctl/$name", File(ctl, name))
unpinAdbSerial(File(root, "root/.bashrc"))
}
/** Older tools/agent/setup pinned the adb port in .bashrc, which overrides the live port DroidDeck passes. */
internal fun unpinAdbSerial(bashrc: File) {
val text = runCatching { bashrc.readText() }.getOrNull() ?: return
val fixed = text.replace("ADB_SERIAL=127.0.0.1:5555 ", "ADB_SERIAL=\"\${ADB_SERIAL:-127.0.0.1:5555}\" ")
if (fixed != text) runCatching { bashrc.writeText(fixed) }
}
private fun copyAsset(app: Context, asset: String, target: File) {
app.assets.open(asset).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,23 @@
package com.droiddeck.launcher.agent
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
object AgentTab {
var shown by mutableStateOf(true)
private set
val visible: Boolean get() = shown && AgentHost.available
fun load(context: Context) {
shown = SessionPrefs.agentTab(context)
}
fun set(context: Context, show: Boolean) {
shown = show
SessionPrefs.setAgentTab(context, show)
}
}
@@ -0,0 +1,143 @@
package com.droiddeck.launcher.agent
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.TimeUnit
/** Claude Code's MCP servers and skills in the userland, through its own CLI and skills folder. */
internal object AgentTools {
data class Server(val name: String, val target: String, val status: String) {
/** Connectors come from the claude.ai account and are managed there, not by the CLI. */
val account get() = name.startsWith("claude.ai ")
}
data class Skill(val name: String, val description: String)
class Result(val ok: Boolean, val output: String)
private const val SKILLS = "root/.claude/skills"
private val SERVER = Regex("""^(.+?): (.+) - (.+)$""")
fun servers(context: Context): List<Server>? {
val result = run(context, listOf(ClaudeCode.binary, "mcp", "list"))
if (!result.ok) return null
return parseServers(result.output)
}
internal fun parseServers(output: String): List<Server> = output.lines().mapNotNull { line ->
SERVER.find(line.trim())?.destructured?.let { (name, target, status) -> Server(name, target, status) }
}
/** A URL is added as an HTTP server; anything else is the command that starts a stdio server. */
internal fun addCommand(name: String, target: String): List<String> {
val t = target.trim()
val base = listOf(ClaudeCode.binary, "mcp", "add", "--scope", "user")
return if (t.startsWith("http://") || t.startsWith("https://")) base + listOf("--transport", "http", name.trim(), t)
else base + listOf(name.trim(), "--") + words(t)
}
/** Splits a command line the way a shell would for quotes and backslashes, without expanding anything. */
internal fun words(line: String): List<String> {
val words = mutableListOf<String>()
val word = StringBuilder()
var inWord = false
var quote: Char? = null
var i = 0
while (i < line.length) {
val c = line[i]
when {
quote == '\'' -> if (c == '\'') quote = null else word.append(c)
c == '\\' && i + 1 < line.length && (quote == null || line[i + 1] == '"' || line[i + 1] == '\\') -> {
word.append(line[++i])
inWord = true
}
quote == '"' -> if (c == '"') quote = null else word.append(c)
c == '\'' || c == '"' -> {
quote = c
inWord = true
}
c.isWhitespace() -> if (inWord) {
words += word.toString()
word.clear()
inWord = false
}
else -> {
word.append(c)
inWord = true
}
}
i++
}
if (inWord) words += word.toString()
return words
}
fun add(context: Context, name: String, target: String) = run(context, addCommand(name, target))
fun remove(context: Context, name: String) = run(context, listOf(ClaudeCode.binary, "mcp", "remove", name))
fun skills(context: Context): List<Skill> =
File(LinuxRuntime.rootDir(context), SKILLS).listFiles { f -> f.isDirectory }.orEmpty().sortedBy { it.name.lowercase() }.map { dir ->
Skill(dir.name, description(File(dir, "SKILL.md")))
}
internal fun description(file: File): String = runCatching {
val lines = file.readLines()
if (lines.firstOrNull()?.trim() != "---") return@runCatching ""
lines.drop(1).takeWhile { it.trim() != "---" }.firstOrNull { it.startsWith("description:") }
?.removePrefix("description:")?.trim()?.trim('"', '\'').orEmpty()
}.getOrDefault("")
fun deleteSkill(context: Context, name: String): Boolean {
if (name.isEmpty() || name.contains('/') || name.startsWith(".")) return false
val root = File(LinuxRuntime.rootDir(context), SKILLS)
val dir = File(root, name)
if (dir.parentFile?.path != root.path) return false
return deleteTree(dir.toPath())
}
/** Deletes [path] and what is under it; a symbolic link is removed itself, never what it points to. */
internal fun deleteTree(path: Path): Boolean = runCatching {
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return@runCatching true
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: java.io.IOException?): FileVisitResult {
if (exc != null) throw exc
Files.delete(dir)
return FileVisitResult.CONTINUE
}
})
true
}.getOrDefault(false)
private fun run(context: Context, command: List<String>): Result {
val child = runCatching { AgentHost.guest(context.applicationContext, command, connectAdb = false).start() }
.getOrElse { return Result(false, it.message.orEmpty()) }
val output = StringBuffer()
// The CLI can hold its output open past the deadline, so it is read beside the wait rather than before it.
val reader = Thread({ runCatching { child.inputStream.bufferedReader().forEachLine { output.append(it).append('\n') } } }, "agent-tools").apply { start() }
return try {
val ended = child.waitFor(90, TimeUnit.SECONDS)
if (!ended) child.destroyForcibly()
reader.join(2_000)
Result(ended && child.exitValue() == 0, output.toString().trim())
} catch (e: InterruptedException) {
child.destroyForcibly()
Thread.currentThread().interrupt()
Result(false, output.toString().trim())
} finally {
runCatching { child.inputStream.close() }
}
}
}
@@ -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()
}
}
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.core
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.lab.LabOverlay
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -16,6 +17,7 @@ import java.io.FileInputStream
internal class AddonPack(
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
private val labBuild: Boolean = LabOverlay.active != null,
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
) {
sealed interface State {
@@ -29,6 +31,9 @@ internal class AddonPack(
val state: StateFlow<State> = mutableState.asStateFlow()
private val lock = Any()
@Volatile var failure: String? = null
private set
val available: Boolean get() = sha256.isNotEmpty()
private val tag get() = "pack-$name-${sha256.take(16)}"
private val urls get() = listOfNotNull(
@@ -42,7 +47,8 @@ internal class AddonPack(
fun installed(context: Context): Boolean = version(context).isNotEmpty() && File(dir(context), COMPLETE).isFile
private fun version(context: Context): String = if (!reuseDeviceCopy) sha256 else deviceCopy(context).orEmpty()
private fun version(context: Context): String =
if (reuseDeviceCopy || labBuild) deviceCopy(context) ?: sha256 else sha256
private fun deviceCopy(context: Context): String? = root(context).listFiles().orEmpty()
.filter { dir ->
@@ -64,9 +70,13 @@ internal class AddonPack(
if (installed(app)) { mutableState.value = State.Ready; return }
if (mutableState.value is State.Downloading) return
mutableState.value = State.Downloading(0f)
failure = null
}
scope.launch {
val ok = runCatching { install(app) }.onFailure { Log.w(TAG, "$name: install failed", it) }.getOrDefault(false)
val ok = runCatching { install(app) }.onFailure {
Log.w(TAG, "$name: install failed", it)
failure = it.toString()
}.getOrDefault(false)
mutableState.value = if (ok) State.Ready else State.Failed
if (ok) onReady(app)
}
@@ -90,20 +100,28 @@ internal class AddonPack(
private fun install(context: Context): Boolean {
if (!available) {
Log.w(TAG, if (reuseDeviceCopy) "$name: this build has no pack and none is installed" else "$name: this build has no pack")
failure = if (reuseDeviceCopy) "this build has no pack and none is installed" else "this build has no pack"
Log.w(TAG, "$name: $failure")
return false
}
val root = root(context).apply { mkdirs() }
val archive = File(root, "$sha256.tar.zst")
val problems = mutableListOf<String>()
val downloaded = bundled(context, archive) || urls.any { url ->
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
.also { if (!it) archive.delete() }
.also { if (!it) { archive.delete(); Downloader.lastFailure()?.let(problems::add) } }
}
if (!downloaded) {
failure = problems.joinToString("; ").ifEmpty { "download failed" }
return false
}
if (!downloaded) return false
val staging = File(root, "$sha256.partial")
staging.deleteRecursively()
try {
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) return false
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) {
failure = "could not unpack the pack"
return false
}
check(required.all { File(staging, it).isFile }) { "$name pack is incomplete" }
File(staging, COMPLETE).writeText(sha256)
val target = dir(context)
@@ -152,5 +170,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"))
}
}
@@ -27,6 +27,32 @@ object AppUiPrefs {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", value).apply()
}
const val HOME_PAGE_STEAM = "steam"
const val HOME_PAGE_APPS = "android-apps"
val homePageOptions = listOf(
HOME_PAGE_STEAM to R.string.rail_steam,
HOME_PAGE_APPS to R.string.content_android_apps,
)
fun homePage(context: Context): String =
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE)
.getString("home-page", null)
.takeIf { value -> homePageOptions.any { it.first == value } }
?: HOME_PAGE_STEAM
fun setHomePage(context: Context, value: String) {
require(homePageOptions.any { it.first == value })
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putString("home-page", value).apply()
}
fun hideHomeFromRecents(context: Context): Boolean =
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("hide-home-from-recents", false)
fun setHideHomeFromRecents(context: Context, hidden: Boolean) {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
}
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
fun scale(context: Context): Int = normalizeScale(
@@ -274,10 +274,12 @@ object DeviceReport {
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context))
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("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))
@@ -31,8 +31,26 @@ public final class Downloader {
return thread;
});
private static final ThreadLocal<String> LAST_FAILURE = new ThreadLocal<>();
private Downloader() {}
public static String lastFailure() {
return LAST_FAILURE.get();
}
private static void failed(String url, String reason) {
String host;
try { host = new java.net.URI(url).getHost(); } catch (java.net.URISyntaxException e) { host = null; }
String entry = (host == null ? url : host) + ": " + reason;
String earlier = LAST_FAILURE.get();
LAST_FAILURE.set(earlier == null ? entry : earlier + "; " + entry);
}
private static String describe(Exception e) {
return e.getMessage() == null ? e.getClass().getSimpleName() : e.getClass().getSimpleName() + ": " + e.getMessage();
}
public static final class Cancellation implements java.util.function.BooleanSupplier {
private final AtomicBoolean cancelled = new AtomicBoolean();
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
@@ -87,12 +105,14 @@ public final class Downloader {
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
List<String> sources = DownloadSource.INSTANCE.candidates(url);
LAST_FAILURE.remove();
for (int i = 0; i < sources.size(); i++) {
if (isCancelled(cancelled)) return null;
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
Fetch fetch = fetch(sources.get(i), cancelled);
if (isCancelled(cancelled)) return null;
if (fetch.body != null) {
LAST_FAILURE.remove();
DownloadSource.INSTANCE.succeeded(sources.get(i));
return fetch.body;
}
@@ -103,6 +123,7 @@ public final class Downloader {
}
public static String downloadDirect(String url) {
LAST_FAILURE.remove();
return fetch(url).body;
}
@@ -138,6 +159,7 @@ public final class Downloader {
String expectedSha256, java.util.function.BooleanSupplier cancelled,
java.util.function.Consumer<Float> progress) {
Identity identity = loadIdentity(destination, resume, expectedSha256);
LAST_FAILURE.remove();
for (int i = 0; i < sources.size(); i++) {
String source = sources.get(i);
if (isCancelled(cancelled)) return false;
@@ -150,12 +172,14 @@ public final class Downloader {
if (isCancelled(cancelled)) return false;
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
failed(source, "checksum mismatch");
if (!discardPartial(destination, identity)) return false;
continue;
}
}
if (isCancelled(cancelled)) return false;
resumeFile(destination).delete();
LAST_FAILURE.remove();
DownloadSource.INSTANCE.succeeded(source);
if (progress != null) progress.accept(1f);
return true;
@@ -260,6 +284,7 @@ public final class Downloader {
}
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
failed(url, "HTTP " + code);
return code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE
? Outcome.FATAL : Outcome.RETRY;
}
@@ -308,11 +333,15 @@ public final class Downloader {
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
}
if (isCancelled(cancelled)) return Outcome.CANCELLED;
if (total > 0 && written < total) return Outcome.RETRY;
if (total > 0 && written < total) {
failed(url, "connection closed after " + written + " of " + total + " bytes");
return Outcome.RETRY;
}
return Outcome.DONE;
} catch (Exception e) {
if (isCancelled(cancelled)) return Outcome.CANCELLED;
Log.w(TAG, "download " + url, e);
failed(url, describe(e));
return Outcome.RETRY;
} finally {
if (connection != null) {
@@ -357,6 +386,7 @@ public final class Downloader {
int code = connection.getResponseCode();
if (code / 100 != 2) {
Log.w(TAG, url + " -> HTTP " + code);
failed(url, "HTTP " + code);
return new Fetch(null, code == HttpURLConnection.HTTP_NOT_FOUND || code == HttpURLConnection.HTTP_GONE);
}
try (InputStream in = connection.getInputStream();
@@ -367,6 +397,7 @@ public final class Downloader {
} catch (Exception e) {
if (isCancelled(cancelled)) return new Fetch(null, false);
Log.w(TAG, "GET " + url, e);
failed(url, describe(e));
return new Fetch(null, false);
} finally {
if (connection != null) {
@@ -49,6 +49,16 @@ object GameEnvironment {
return withScopeValue(config, scope, NO_STEAM, if (on) "1" else null)
}
const val GAME_RESOLUTION = "DROIDDECK_GAME_RESOLUTION"
fun gameResolution(config: Config, scope: String): GameResolution.Choice? =
if (scope.isEmpty()) null else GameResolution.parse(config.games[scope]?.get(GAME_RESOLUTION))
fun withGameResolution(config: Config, scope: String, choice: GameResolution.Choice?): Config {
require(scope.isNotEmpty() && validScope(scope))
return withScopeValue(config, scope, GAME_RESOLUTION, choice?.let(GameResolution::format))
}
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.core
object GameResolution {
sealed interface Choice
data class Fixed(val width: Int, val height: Int) : Choice
data class Scaled(val scale: Float) : Choice
data class Aspect(val label: String, val sizes: List<Fixed>)
val aspects = listOf(
Aspect("16:9", listOf(Fixed(960, 540), Fixed(1280, 720), Fixed(1600, 900), Fixed(1920, 1080), Fixed(2560, 1440))),
Aspect("16:10", listOf(Fixed(1280, 800), Fixed(1440, 900), Fixed(1680, 1050), Fixed(1920, 1200), Fixed(2560, 1600))),
Aspect("4:3", listOf(Fixed(640, 480), Fixed(800, 600), Fixed(1024, 768), Fixed(1280, 960), Fixed(1440, 1080))),
)
val scales = listOf(1.5f, 2f, 3f)
const val MIN_WIDTH = 320
const val MIN_HEIGHT = 240
const val MAX_SIDE = 7680
private const val SCALED_PREFIX = "/"
fun parse(value: String?): Choice? {
val text = value?.trim().orEmpty()
if (text.startsWith(SCALED_PREFIX)) {
return text.removePrefix(SCALED_PREFIX).toFloatOrNull()?.takeIf { it > 1f && it <= 8f }?.let(::Scaled)
}
val parts = text.split('x', 'X', '×').map { it.trim().toIntOrNull() }
if (parts.size != 2) return null
val (w, h) = parts
return if (w != null && h != null && valid(w, h)) Fixed(w and 1.inv(), h and 1.inv()) else null
}
fun valid(width: Int, height: Int) = width in MIN_WIDTH..MAX_SIDE && height in MIN_HEIGHT..MAX_SIDE
fun format(choice: Choice): String = when (choice) {
is Fixed -> "${choice.width}x${choice.height}"
is Scaled -> SCALED_PREFIX + formatScale(choice.scale)
}
fun formatScale(scale: Float): String =
(Math.round(scale * 10) / 10f).let { if (it % 1f == 0f) it.toInt().toString() else it.toString() }
fun resolve(choice: Choice, output: Pair<Int, Int>): Pair<Int, Int> = when (choice) {
is Fixed -> choice.width to choice.height
is Scaled -> (Math.round(output.first / choice.scale).coerceAtLeast(MIN_WIDTH) and 1.inv()) to
(Math.round(output.second / choice.scale).coerceAtLeast(MIN_HEIGHT) and 1.inv())
}
fun aspectLabel(width: Int, height: Int): String {
if (width <= 0 || height <= 0) return ""
val ratio = width.toFloat() / height
aspects.firstOrNull { a ->
val (w, h) = a.label.split(':').map(String::toFloat)
kotlin.math.abs(ratio - w / h) < 0.02f
}?.let { return it.label }
if (kotlin.math.abs(ratio - 64f / 27f) < 0.04f || kotlin.math.abs(ratio - 21f / 9f) < 0.04f) return "21:9"
val g = gcd(width, height)
return if (width / g <= 32) "${width / g}:${height / g}" else String.format(java.util.Locale.ROOT, "%.2f:1", ratio)
}
fun sizesFor(aspect: Aspect, panel: Pair<Int, Int>): List<Fixed> {
val long = maxOf(panel.first, panel.second)
val short = minOf(panel.first, panel.second)
val fit = aspect.sizes.filter { it.width <= long && it.height <= short }
return fit.ifEmpty { aspect.sizes.take(1) }
}
private tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
}
@@ -13,6 +13,11 @@ object HostProcess {
@JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?): Int {
return start(command, env, dir, onExit, onLine, outputFile, null)
}
@JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?, onOutputComplete: Runnable?): Int {
val argv = split(command)
if (argv.isEmpty()) return -1
return try {
@@ -35,6 +40,8 @@ object HostProcess {
try {
process.inputStream.bufferedReader().useLines { lines -> lines.forEach { onLine.accept(it) } }
} catch (e: Exception) {
} finally {
onOutputComplete?.run()
}
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
}
@@ -5,6 +5,9 @@ import android.util.Log
import java.io.BufferedWriter
import java.io.File
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.concurrent.atomic.AtomicInteger
object SessionLogCapture {
private const val TAG = "SessionLogCapture"
@@ -104,4 +107,53 @@ object SessionLogCapture {
Log.w(TAG, "could not dump the crash buffer", e)
}
}
fun dumpMemoryPressure(target: File) {
var temporary: File? = null
try {
val staged = File.createTempFile(target.name, ".part", target.parentFile).also { temporary = it }
val lines = StringBuilder()
val done = java.util.concurrent.CountDownLatch(1)
val outputDone = java.util.concurrent.CountDownLatch(1)
val exitStatus = AtomicInteger(Int.MIN_VALUE)
val pid = HostProcess.start(
"/system/bin/logcat -b events -d -v threadtime -t 800", null, target.parentFile,
{ status -> exitStatus.set(status); done.countDown() },
{ line -> synchronized(lines) { lines.append(line).append('\n') } },
null,
outputDone::countDown,
)
val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10)
val finished = if (pid == -1) false else {
val exitTime = deadline - System.nanoTime()
exitTime > 0 && done.await(exitTime, java.util.concurrent.TimeUnit.NANOSECONDS) &&
(deadline - System.nanoTime()).let { it > 0 && outputDone.await(it, java.util.concurrent.TimeUnit.NANOSECONDS) }
}
val body = synchronized(lines) { lines.toString() }
val status = exitStatus.get()
val pressure = runCatching { File("/proc/pressure/memory").readText() }.getOrDefault("unavailable\n")
val meminfo = runCatching { File("/proc/meminfo").readText() }.getOrDefault("unavailable\n")
val gpu = runCatching { File("/sys/class/kgsl/kgsl/page_alloc").readText() }.getOrDefault("unavailable\n")
staged.writeText(
"Android memory events:\n" +
when {
pid == -1 -> "(logcat could not be started at all)\n"
status != Int.MIN_VALUE && status != 0 -> "(logcat failed with exit status $status; no Android memory events were captured)\n" +
if (body.isEmpty()) "" else "\nlogcat command output:\n$body"
!finished -> if (body.isEmpty()) "(logcat did not finish within 10 s; nothing captured)\n"
else body + "(logcat did not finish within 10 s; later events may be missing)\n"
body.isNotEmpty() -> body
else -> "(no readable events were returned)\n"
} +
"\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu"
)
Files.move(
staged.toPath(), target.toPath(),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE,
)
} catch (e: Exception) {
temporary?.delete()
Log.w(TAG, "could not dump memory pressure diagnostics", e)
}
}
}
@@ -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 {
@@ -97,15 +97,16 @@ object AddedGames {
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
}
fun candidates(folder: File): List<File> = rank(folder).exes
fun candidates(folder: File, reuse: Boolean = false): List<File> = rank(folder, reuse).exes
fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
val key = "${folder.path}|${folder.lastModified()}"
val declared = declaredExes(folder)
val stamp = declared.fold(0L) { hash, exe -> hash * 31 + exe.path.hashCode() }
val key = "${folder.path}|${folder.lastModified()}|$stamp"
val now = System.currentTimeMillis()
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
if (reuse) kept?.rank(folder)?.let { return it }
if (reuse) kept?.rank(folder, stamp)?.let { return it }
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) }
val declared = declaredExes(folder)
val preferred = declared.map { it.path }.toSet()
val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking(
declared + guessed.exes.filter { it.path !in preferred },
@@ -115,7 +116,7 @@ object AddedGames {
)
if (ranked.size > 256) ranked.clear()
ranked[key] = now to result
kept?.keepRank(folder, result)
kept?.keepRank(folder, result, stamp)
return result
}
@@ -200,8 +201,7 @@ object AddedGames {
private val scanning = Any()
fun scan(context: Context): List<Game> = synchronized(scanning) {
val file = File(context.filesDir, AddedGamesCache.FILE)
val cache = kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
val cache = cache(context)
try {
scanAll(context)
} finally {
@@ -209,6 +209,13 @@ object AddedGames {
}
}
private val keeping = Any()
private fun cache(context: Context): AddedGamesCache = synchronized(keeping) {
val file = File(context.filesDir, AddedGamesCache.FILE)
kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
}
private fun scanAll(context: Context): List<Game> {
val out = ArrayList<Game>()
GamesFolderMigration.run(context)
@@ -241,11 +248,17 @@ object AddedGames {
return out.distinctBy { it.folder.canonicalPath }
}
fun single(context: Context, folderPath: String): Game? {
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
val folder = File(folderPath)
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
val out = ArrayList<Game>(1)
scanGame(context, folder, out, single = AddedExes.list(context).firstOrNull { it.folder == folderPath })
val entry = AddedExes.list(context).firstOrNull { it.folder == folderPath }
val cache = if (reuse) cache(context) else null
try {
scanGame(context, folder, out, single = entry, reuse = reuse)
} finally {
cache?.save()
}
return out.firstOrNull()
}
@@ -417,7 +430,8 @@ 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) }
if (sidecar?.store == Store.ROCKSTAR && sidecar.launcher != com.droiddeck.launcher.stores.StoreLaunch.LAUNCHER) return
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
@@ -433,6 +447,7 @@ object AddedGames {
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
if (sidecar?.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarLaunch.applyDefaults(context, sidecar.id, appId)
val config = accountConfig(SessionPrefs.activeSteamRoot(context))
val record = config?.let { shortcutRecord(it, appId) }
val rev = record?.optInt("rev", 0) ?: 0
@@ -457,7 +472,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))
}
}
@@ -523,6 +542,17 @@ object AddedGames {
}
}
class Listed(val appId: Long, val name: String, val launchOptions: String)
fun listed(context: Context): List<Listed>? = runCatching {
val file = File(context.filesDir, "session/added-games.json")
if (!file.isFile) return null
val entries = org.json.JSONArray(file.readText())
(0 until entries.length()).mapNotNull { i ->
entries.optJSONObject(i)?.takeIf { it.has("appid") }?.let { Listed(it.optLong("appid") and 0xFFFFFFFFL, it.optString("name"), it.optString("launch")) }
}
}.getOrNull()
fun writeListing(context: Context, games: List<Game>,
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
@@ -7,7 +7,7 @@ import java.io.File
import java.util.concurrent.ConcurrentHashMap
internal class AddedGamesCache(val file: File) {
private class Rank(val modified: Long, val at: Long, val ranking: GameExePicker.Ranking)
private class Rank(val modified: Long, val declared: Long, val at: Long, val ranking: GameExePicker.Ranking)
private class Name(val name: String, val at: Long)
private val ranks = ConcurrentHashMap<String, Rank>()
@@ -22,7 +22,7 @@ internal class AddedGamesCache(val file: File) {
val exes = o.getJSONArray("exes")
val scores = o.getJSONArray("scores")
require(exes.length() > 0 && exes.length() == scores.length())
ranks[path] = Rank(o.getLong("modified"), o.getLong("at"), GameExePicker.Ranking(
ranks[path] = Rank(o.getLong("modified"), o.optLong("declared"), o.getLong("at"), GameExePicker.Ranking(
List(exes.length()) { File(exes.getString(it)) }, List(scores.length()) { scores.getInt(it) }, o.optBoolean("uncertain"),
))
}
@@ -32,19 +32,19 @@ internal class AddedGamesCache(val file: File) {
}
}
fun rank(folder: File): GameExePicker.Ranking? {
fun rank(folder: File, declared: Long = 0): GameExePicker.Ranking? {
val kept = ranks[folder.path] ?: return null
val age = System.currentTimeMillis() - kept.at
val top = kept.ranking.exes.first()
return kept.ranking.takeIf { kept.modified == folder.lastModified() && age in 0 until KEEP_MS && top.isFile }
return kept.ranking.takeIf { kept.modified == folder.lastModified() && kept.declared == declared && age in 0 until KEEP_MS && top.isFile }
}
fun keepRank(folder: File, ranking: GameExePicker.Ranking) {
fun keepRank(folder: File, ranking: GameExePicker.Ranking, declared: Long = 0) {
if (ranking.exes.isEmpty()) {
if (ranks.remove(folder.path) != null) changed = true
return
}
ranks[folder.path] = Rank(folder.lastModified(), System.currentTimeMillis(), ranking)
ranks[folder.path] = Rank(folder.lastModified(), declared, System.currentTimeMillis(), ranking)
changed = true
}
@@ -62,7 +62,7 @@ internal class AddedGamesCache(val file: File) {
val oldest = System.currentTimeMillis() - KEEP_MS
val keptRanks = JSONObject()
ranks.forEach { (path, r) ->
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("at", r.at)
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("declared", r.declared).put("at", r.at)
.put("exes", JSONArray(r.ranking.exes.map { it.path })).put("scores", JSONArray(r.ranking.scores))
.put("uncertain", r.ranking.uncertain))
}
@@ -0,0 +1,69 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object AddedSoundtracks {
private fun file(context: Context) = File(context.filesDir, "added-soundtracks.json")
class Entry(val path: String, val name: String, val id: Int = 0)
internal fun assignIds(list: List<Entry>): List<Entry> {
val used = list.filter { it.id != 0 }.map { it.id }.toMutableSet()
return list.map { e ->
if (e.id != 0) e else {
var id = idOf(e.path)
while (id == 0 || !used.add(id)) id = (id + 1) or Int.MIN_VALUE
Entry(e.path, e.name, id)
}
}
}
@Synchronized
fun entries(context: Context): List<Entry> = runCatching {
val f = file(context).takeIf { it.isFile } ?: return emptyList()
val array = JSONArray(f.readText())
val raw = List(array.length()) { i -> array.getJSONObject(i).let { Entry(it.getString("path"), it.getString("name"), it.optInt("id", 0)) } }
val ready = assignIds(raw)
if (raw.any { it.id == 0 }) save(context, ready)
ready
}.getOrDefault(emptyList())
@Synchronized
private fun save(context: Context, list: List<Entry>): Boolean =
runCatching {
val array = JSONArray()
list.forEach { array.put(JSONObject().put("path", it.path).put("name", it.name).put("id", it.id)) }
val f = file(context)
val tmp = File(f.path + ".tmp")
tmp.writeText(array.toString())
if (tmp.renameTo(f)) true else { tmp.delete(); false }
}.getOrDefault(false)
fun add(context: Context, folder: File): Boolean {
if (!folder.isDirectory || Soundtrack.audioFiles(folder).isEmpty()) return false
return synchronized(this) {
val list = entries(context)
list.any { it.path == folder.path } || save(context, assignIds(list + Entry(folder.path, folder.name)))
}
}
fun remove(context: Context, path: String): Boolean =
synchronized(this) { save(context, entries(context).filterNot { it.path == path }) }
internal fun idOf(path: String): Int = path.hashCode() or Int.MIN_VALUE
fun games(context: Context): List<Library.SteamGame> = entries(context).mapNotNull { e ->
val dir = File(e.path).takeIf { it.isDirectory } ?: return@mapNotNull null
game(context, e, dir, e.id)
}
private fun game(context: Context, e: Entry, dir: File, id: Int): Library.SteamGame {
return Library.SteamGame(
appId = id, name = e.name, art = SoundtrackCollectionArt.chosen(context, id) ?: Soundtrack.firstCover(context, dir), library = Library.ADDED, gameId = id.toLong() and 0xFFFFFFFFL,
gameFiles = dir, source = Library.ADDED, soundtrack = true,
)
}
}
@@ -21,7 +21,7 @@ object GameRemoval {
fun steamFiles(game: Library.SteamGame): SteamFiles? {
val dir = game.gameFiles ?: return null
val common = dir.parentFile ?: return null
if (common.name != "common") return null
if (common.name != (if (game.soundtrack) "music" else "common")) return null
val steamapps = common.parentFile ?: return null
if (steamapps.name != "steamapps") return null
val manifest = File(steamapps, "appmanifest_${game.appId}.acf")
@@ -19,9 +19,10 @@ object Library {
val storeId: String? = null,
val logo: File? = null,
val installedAt: Long = 0L,
val soundtrack: Boolean = false,
) {
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt)
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo, installedAt, soundtrack)
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
val launchKey: String get() = if (storeId != null) "$source:$storeId" else gameIdString
@@ -38,6 +39,7 @@ object Library {
const val BATTLENET_LAUNCHER = "battlenet-launcher"
const val XBOX_CLOUD = "xbox-cloud"
const val SOURCE_STEAM = "steam"
const val SOURCE_COLLECTION = "collection"
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
@@ -123,9 +125,13 @@ object Library {
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
}
fun soundtracks(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> =
steamGames(context, arch = arch, withShared = false, soundtracks = true, soundtracksOnly = true)
fun steamGames(
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
withShared: Boolean = true,
withShared: Boolean = true, soundtracks: Boolean = false, soundtracksOnly: Boolean = false,
onlyAppIds: Set<Int>? = null,
): List<SteamGame> {
val root = SessionPrefs.steamRoot(context, arch)
val cache = File(root, "appcache/librarycache")
@@ -138,21 +144,26 @@ object Library {
if (strictRead && steamapps.isDirectory) check(manifests != null) { context.getString(R.string.game_sync_err_manifests) }
manifests?.sortedBy { it.name }?.forEach { manifest ->
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach
if (appId in NOT_GAMES || out.containsKey(appId) ||
(onlyAppIds != null && appId !in onlyAppIds)
) return@forEach
val text = try { manifest.readText() } catch (e: Exception) { if (strictRead) throw e; return@forEach }
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
if (name.isEmpty() || flags and 4 == 0) return@forEach
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
val musicFiles = if (gameFiles == null) installDir?.let { File(steamapps, "music/$it").takeIf(File::isDirectory) } else null
if (musicFiles != null && !soundtracks) return@forEach
if (soundtracksOnly && musicFiles == null) return@forEach
val images = SteamCacheImages(File(cache, appId.toString()))
val art = images.find(STEAM_CAPSULES)
val hero = images.find(STEAM_HEROES)
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
out[appId] = SteamGameArt.withOverrides(context, SteamGame(
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles,
appId, name, art ?: musicFiles?.let { Soundtrack.firstCover(context, it) }, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles ?: musicFiles, soundtrack = musicFiles != null,
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
icon = images.icon(),
logo = images.find(STEAM_LOGOS),
@@ -161,16 +172,42 @@ object Library {
}
if (withShared) {
val other = if (arch == "x86_64") "arm64" else "x86_64"
val shared = sharedApps(context, arch) - out.keys
if (shared.isNotEmpty()) runCatching { steamGames(context, arch = other, withShared = false) }.getOrDefault(emptyList())
.filter { it.appId in shared }.forEach { out[it.appId] = it }
val shared = try {
sharedApps(context, arch) - out.keys
} catch (e: IllegalStateException) {
if (strictRead) throw e
emptySet()
}
if (shared.isNotEmpty()) {
val otherGames = try {
steamGames(
context,
strictRead = strictRead,
arch = other,
withShared = false,
soundtracks = soundtracks,
onlyAppIds = shared,
)
} catch (e: Exception) {
if (strictRead) throw e
emptyList()
}
otherGames.forEach { out[it.appId] = it }
}
}
return out.values.toList()
}
internal fun sharedApps(context: Context, arch: String): Set<Int> {
val view = File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/shared/${if (arch == "x86_64") "arm64" else "x86-64"}/steamapps")
return view.list().orEmpty().mapNotNull { Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }.toSet()
val entries = view.list()
if (entries == null) {
if (!view.exists()) return emptySet()
throw IllegalStateException("Unable to read the shared Steam library.")
}
return entries.mapNotNull {
Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull()
}.toSet()
}
fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
@@ -0,0 +1,308 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.media.MediaMetadataRetriever
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object Soundtrack {
class Track(
val file: File, val title: String, val disc: Int, val number: Int, val durationMs: Long, val artist: String = "",
val discLabel: String = disc.toString(),
) {
val id: String get() = file.path
}
class Album(val disc: Map<Int, List<Track>>, val artist: String, val cover: File?) {
val tracks: List<Track> get() = disc.values.flatten()
val discs: List<Int> get() = disc.keys.toList()
val multiDisc: Boolean get() = disc.size > 1
val totalMs: Long get() = tracks.sumOf { it.durationMs }
}
class Raw(
val file: File, val folder: String, val tagDisc: Int?, val tagTrack: Int?, val tagTitle: String?, val tagArtist: String?,
val durationMs: Long, val size: Long = file.length(),
)
val EXTENSIONS = setOf("mp3", "flac", "ogg", "oga", "opus", "wav", "m4a", "aac")
private val LOSSLESS = setOf("flac", "wav")
private val COVERS = listOf("AlbumArtwork", "albumartwork", "cover", "Cover", "folder", "Folder", "front", "Front", "artwork", "Artwork")
internal val COVER_EXT = listOf("png", "jpg", "jpeg", "webp")
private val LEADING = Regex("^\\s*\\d+\\s*[.\\-_)]*\\s+")
private val DIGITS = Regex("^\\s*(\\d+)")
fun isAudio(file: File): Boolean = file.isFile && file.extension.lowercase() in EXTENSIONS
fun cleanTitle(fileName: String): String {
val base = fileName.substringBeforeLast('.', fileName).trim()
val tail = if (" - " in base) base.substringAfterLast(" - ") else base
val stripped = tail.replace(LEADING, "").trim()
return stripped.ifEmpty { tail.ifEmpty { base } }
}
internal fun leadingNumber(fileName: String): Int? = DIGITS.find(fileName.substringAfterLast(" - "))?.groupValues?.get(1)?.toIntOrNull()
private fun identity(r: Raw): String {
val d = r.tagDisc
val t = r.tagTrack
if (d != null && t != null) return "n:$d:$t"
val title = (r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name)).lowercase().filter { it.isLetterOrDigit() }
return "t:$title:${leadingNumber(r.file.name)}"
}
private fun better(a: Raw, b: Raw): Raw {
val la = a.file.extension.lowercase() in LOSSLESS
val lb = b.file.extension.lowercase() in LOSSLESS
return when {
la != lb -> if (la) a else b
a.size != b.size -> if (a.size > b.size) a else b
else -> if (a.file.path <= b.file.path) a else b
}
}
fun group(raws: List<Raw>): Map<Int, List<Track>> {
if (raws.isEmpty()) return emptyMap()
val unique = LinkedHashMap<String, Raw>()
val home = HashMap<String, String>()
val disc = HashMap<String, Int>()
val track = HashMap<String, Int>()
val title = HashMap<String, String>()
for (r in raws) {
val id = identity(r)
unique[id] = unique[id]?.let { better(it, r) } ?: r
if (r.folder.isNotEmpty() && home[id].isNullOrEmpty()) home[id] = r.folder
r.tagDisc?.let { disc.putIfAbsent(id, it) }
r.tagTrack?.let { track.putIfAbsent(id, it) }
r.tagTitle?.takeIf { it.isNotBlank() }?.let { title.putIfAbsent(id, it) }
}
val kept = unique.map { (id, r) ->
Raw(
r.file, home[id] ?: r.folder, disc[id] ?: r.tagDisc, track[id] ?: r.tagTrack, title[id] ?: r.tagTitle, r.tagArtist,
r.durationMs, r.size,
)
}
val folders = kept.filter { it.tagDisc == null }.map { it.folder }.distinct().sortedWith(naturalOrder)
val discs = kept.groupBy { r ->
r.tagDisc ?: if (folders.size <= 1 && kept.none { it.tagDisc != null }) 0 else folders.indexOf(r.folder) + 1
}
return discs.toSortedMap().mapValues { (disc, list) ->
list.sortedWith(
compareBy<Raw>({ leadingNumber(it.file.name) ?: it.tagTrack ?: Int.MAX_VALUE }, { it.tagTrack ?: Int.MAX_VALUE }, { it.file.name.lowercase() }),
).mapIndexed { i, r ->
Track(
r.file, r.tagTitle?.takeIf { it.isNotBlank() } ?: cleanTitle(r.file.name), disc, i + 1,
r.durationMs, r.tagArtist.orEmpty(), labelOf(r, disc),
)
}
}
}
private val FOLDER_LABEL = Regex("[0-9][0-9 +&,.\\-]*")
private fun labelOf(r: Raw, disc: Int): String {
if (r.tagDisc != null) return disc.toString()
val name = r.folder.substringAfterLast('/')
return if (FOLDER_LABEL.matches(name)) name else disc.toString()
}
private val naturalOrder = Comparator<String> { a, b ->
val x = Regex("\\d+|\\D+").findAll(a.lowercase()).map { it.value }.toList()
val y = Regex("\\d+|\\D+").findAll(b.lowercase()).map { it.value }.toList()
var i = 0
var out = 0
while (out == 0 && i < minOf(x.size, y.size)) {
val nx = x[i].toBigIntegerOrNull()
val ny = y[i].toBigIntegerOrNull()
out = if (nx != null && ny != null) nx.compareTo(ny) else x[i].compareTo(y[i])
i++
}
if (out != 0) out else x.size.compareTo(y.size)
}
fun cover(dir: File): File? {
for (name in COVERS) for (ext in COVER_EXT) File(dir, "$name.$ext").takeIf { it.isFile }?.let { return it }
return dir.listFiles()?.filter { it.isFile && it.extension.lowercase() in COVER_EXT }?.minByOrNull { it.name.lowercase() }
}
private fun parseNumber(value: String?): Int? = value?.substringBefore('/')?.trim()?.toIntOrNull()
private fun read(file: File, root: File): Raw {
val folder = file.parentFile?.let { parent ->
if (parent.path == root.path) "" else parent.path.removePrefix(root.path).trimStart('/')
}.orEmpty()
val retriever = MediaMetadataRetriever()
return try {
retriever.setDataSource(file.path)
Raw(
file, folder,
parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER)),
parseNumber(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER)),
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE),
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
?: retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST),
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L,
)
} catch (e: Exception) {
Raw(file, folder, null, null, null, null, 0L)
} finally {
runCatching { retriever.release() }
}
}
private fun cacheFile(context: Context, root: File) = File(context.filesDir, "soundtrack-index/${root.path.hashCode().toUInt()}.json")
private fun fromCache(context: Context, root: File, files: List<File>): List<Raw>? = runCatching {
val f = cacheFile(context, root).takeIf { it.isFile } ?: return null
val json = JSONObject(f.readText())
if (json.optString("root") != root.path) return null
val rows = json.getJSONArray("rows")
val byPath = HashMap<String, JSONObject>()
for (i in 0 until rows.length()) rows.getJSONObject(i).let { byPath[it.getString("p")] = it }
if (byPath.size != files.size) return null
files.map { file ->
val row = byPath[file.path] ?: return null
if (row.getLong("s") != file.length() || row.getLong("m") != file.lastModified()) return null
Raw(
file, row.getString("f"), row.optInt("d", -1).takeIf { it >= 0 }, row.optInt("n", -1).takeIf { it >= 0 },
row.optString("t").takeIf { it.isNotEmpty() }, row.optString("a").takeIf { it.isNotEmpty() }, row.optLong("l"),
)
}
}.getOrNull()
private fun toCache(context: Context, root: File, raws: List<Raw>) {
runCatching {
val rows = JSONArray()
for (r in raws) rows.put(
JSONObject().put("p", r.file.path).put("s", r.file.length()).put("m", r.file.lastModified()).put("f", r.folder)
.put("d", r.tagDisc ?: -1).put("n", r.tagTrack ?: -1).put("t", r.tagTitle.orEmpty()).put("a", r.tagArtist.orEmpty())
.put("l", r.durationMs),
)
val f = cacheFile(context, root)
f.parentFile?.mkdirs()
val tmp = File(f.path + ".tmp")
tmp.writeText(JSONObject().put("root", root.path).put("rows", rows).toString())
if (!tmp.renameTo(f)) tmp.delete()
}
}
fun audioFiles(root: File): List<File> {
val out = ArrayList<File>()
fun walk(dir: File, depth: Int) {
val children = dir.listFiles() ?: return
for (c in children.sortedBy { it.name.lowercase() }) {
if (c.isDirectory) { if (depth < 4) walk(c, depth + 1) } else if (isAudio(c)) out += c
}
}
walk(root, 0)
return out
}
private fun coverCache(context: Context, root: File): File {
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(root.path.toByteArray(Charsets.UTF_8))
val key = digest.take(16).joinToString("") { "%02x".format(it) }
return File(context.filesDir, "soundtrack-index/cover-$key.jpg")
}
fun cachedCover(context: Context, root: File): File? = coverCache(context, root).takeIf { it.isFile && it.length() > 0L }
private fun embeddedBytes(file: File): ByteArray? = runCatching {
val retriever = MediaMetadataRetriever()
try {
retriever.setDataSource(file.path)
retriever.embeddedPicture
} finally {
runCatching { retriever.release() }
}
}.getOrNull()?.takeIf { it.isNotEmpty() }
private fun hashOf(bytes: ByteArray): String =
java.security.MessageDigest.getInstance("SHA-256").digest(bytes).take(16).joinToString("") { "%02x".format(it) }
private fun embeddedCover(context: Context, root: File, files: List<File>): File? {
cachedCover(context, root)?.let { return it }
val miss = File(coverCache(context, root).path + ".none")
val probed = files.take(8)
val signature = hashOf(probed.joinToString("\n") { "${it.path}|${it.length()}|${it.lastModified()}" }.toByteArray(Charsets.UTF_8))
if (runCatching { miss.isFile && miss.readText().trim() == signature }.getOrDefault(false)) return null
for (file in probed) {
val bytes = embeddedBytes(file) ?: continue
val out = coverCache(context, root)
runCatching {
out.parentFile?.mkdirs()
out.writeBytes(bytes)
}.onSuccess { return out }
}
runCatching {
miss.parentFile?.mkdirs()
miss.writeText(signature)
}
return null
}
fun firstCover(context: Context, root: File): File? = cover(root) ?: embeddedCover(context, root, audioFiles(root))
@Synchronized
fun trackCover(context: Context, file: File): File? {
val dir = File(context.filesDir, "soundtrack-index/track-covers")
val marker = File(dir, "t-" + hashOf("${file.path}|${file.length()}|${file.lastModified()}".toByteArray(Charsets.UTF_8)))
if (marker.isFile) {
val name = runCatching { marker.readText().trim() }.getOrDefault("")
if (name.isEmpty()) return null
File(dir, name).takeIf { it.isFile && it.length() > 0L }?.let {
val now = System.currentTimeMillis()
marker.setLastModified(now)
it.setLastModified(now)
return it
}
}
val bytes = embeddedBytes(file)
return runCatching {
dir.mkdirs()
if (bytes == null) {
marker.writeText("")
prune(dir, setOf(marker.name))
null
} else {
val out = File(dir, "c-" + hashOf(bytes) + ".jpg")
if (!out.isFile || out.length() == 0L) out.writeBytes(bytes)
marker.writeText(out.name)
prune(dir, setOf(marker.name, out.name))
out
}
}.getOrNull()
}
private const val TRACK_COVER_BYTES = 64L * 1024 * 1024
private const val TRACK_COVER_FILES = 2000
private fun prune(dir: File, keep: Set<String>) {
val all = dir.listFiles()?.filter { it.isFile } ?: return
var bytes = all.sumOf { it.length() }
var count = all.size
for (f in all.sortedBy { it.lastModified() }) {
if (bytes <= TRACK_COVER_BYTES && count <= TRACK_COVER_FILES) break
if (f.name in keep) continue
bytes -= f.length()
count--
f.delete()
}
}
fun load(context: Context, root: File, coverHint: File? = null): Album {
val files = audioFiles(root)
val raws = fromCache(context, root, files) ?: files.map { read(it, root) }.also { toCache(context, root, it) }
val disc = SoundtrackOrder.apply(context, root, group(raws))
val artist = disc.values.flatten().map { it.artist }.filter { it.isNotBlank() }.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key.orEmpty()
return Album(disc, artist, coverHint ?: cover(root) ?: embeddedCover(context, root, files))
}
fun formatLength(ms: Long): String {
val total = ms / 1000
val h = total / 3600
val m = (total % 3600) / 60
val s = total % 60
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s)
}
}
@@ -0,0 +1,50 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import java.io.File
object SoundtrackCollectionArt {
internal fun dir(context: Context, id: Int) = File(context.filesDir, "soundtrack-art/$id")
private fun sourceFile(context: Context, id: Int) = File(dir(context, id), "source")
fun chosen(context: Context, id: Int): File? = dir(context, id).takeIf { it.isDirectory }?.let { AddedGameArt.chosen(it, AddedGameArt.Slot.COVER) }
fun source(context: Context, id: Int): String =
sourceFile(context, id).takeIf { it.isFile }?.readText()?.trim().orEmpty().substringAfter('|', "")
fun options(context: Context, id: Int, root: File?): List<AddedGameArt.Option> {
val paths = if (root != null) {
val images = root.listFiles()?.filter { it.isFile && it.extension.lowercase() in Soundtrack.COVER_EXT }?.sortedBy { it.name.lowercase() }.orEmpty()
(images + listOfNotNull(Soundtrack.firstCover(context, root))).map { it.path }
} else SoundtrackCollections.tracksOf(id).map { it.cover }
return paths.filter { it.isNotEmpty() && File(it).isFile }.distinct().map { AddedGameArt.Option(AddedGameArt.FOLDER, it, it) }
}
fun choose(context: Context, id: Int, option: AddedGameArt.Option): Boolean {
val folder = dir(context, id)
val fresh = AddedGameArt.storeNew(folder, AddedGameArt.Slot.COVER, option) ?: return false
AddedGameArt.dropOlder(folder, AddedGameArt.Slot.COVER, fresh)
sourceFile(context, id).writeText(option.group + "|" + option.full)
return true
}
fun reset(context: Context, id: Int) {
chosen(context, id)?.delete()
sourceFile(context, id).delete()
}
fun describe(context: Context, id: Int, root: File? = null): List<AddedGameArt.SlotState> {
val own = chosen(context, id)
val state = if (own != null) AddedGameArt.SlotState(AddedGameArt.Slot.COVER, own, AddedGameArt.FILE, true)
else {
val auto = if (root != null) Soundtrack.firstCover(context, root) else SoundtrackCollections.autoCover(id)
AddedGameArt.SlotState(AddedGameArt.Slot.COVER, auto, if (auto != null) AddedGameArt.FOLDER else AddedGameArt.AUTO, false)
}
return listOf(state)
}
fun clear(context: Context, id: Int) {
dir(context, id).deleteRecursively()
}
}
@@ -0,0 +1,191 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import androidx.compose.runtime.mutableStateOf
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.Executors
object SoundtrackCollections {
const val FAVORITES_ID = 2_000_000_000
class TrackRef(val path: String, val title: String, val artist: String, val album: String, val durationMs: Long, val cover: String = "")
class Collection(val id: Int, val name: String, val tracks: List<TrackRef>)
class Snapshot(val favorites: List<TrackRef>, val collections: List<Collection>)
private val state = mutableStateOf(Snapshot(emptyList(), emptyList()))
private var loaded = false
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-collections").apply { isDaemon = true } }
val snapshot: Snapshot get() = state.value
private fun file(context: Context) = File(context.filesDir, "soundtrack-collections.json")
internal fun toggled(list: List<TrackRef>, ref: TrackRef): List<TrackRef> =
if (list.any { it.path == ref.path }) list.filterNot { it.path == ref.path } else list + ref
internal fun merged(list: List<TrackRef>, add: List<TrackRef>): List<TrackRef> {
val have = list.mapTo(HashSet()) { it.path }
return list + add.filter { have.add(it.path) }
}
internal fun cleanName(raw: String): String = raw.trim().replace(Regex("\\s+"), " ")
internal fun nameTaken(collections: List<Collection>, name: String, except: Int? = null): Boolean =
collections.any { it.id != except && it.name.equals(name, ignoreCase = true) }
internal fun nextId(collections: List<Collection>): Int =
(collections.maxOfOrNull { it.id } ?: FAVORITES_ID).coerceAtLeast(FAVORITES_ID) + 1
private fun encode(s: Snapshot): String {
fun refs(list: List<TrackRef>) = JSONArray().also { array ->
list.forEach {
array.put(
JSONObject().put("path", it.path).put("title", it.title).put("artist", it.artist).put("album", it.album)
.put("duration", it.durationMs).put("cover", it.cover),
)
}
}
val collections = JSONArray()
s.collections.forEach { collections.put(JSONObject().put("id", it.id).put("name", it.name).put("tracks", refs(it.tracks))) }
return JSONObject().put("favorites", refs(s.favorites)).put("collections", collections).toString()
}
private fun decode(text: String): Snapshot {
fun refs(array: JSONArray?): List<TrackRef> = if (array == null) emptyList() else List(array.length()) { i ->
array.getJSONObject(i).let {
TrackRef(it.getString("path"), it.optString("title"), it.optString("artist"), it.optString("album"), it.optLong("duration"), it.optString("cover"))
}
}
val root = JSONObject(text)
val collections = root.optJSONArray("collections")
return Snapshot(
refs(root.optJSONArray("favorites")),
if (collections == null) emptyList() else List(collections.length()) { i ->
collections.getJSONObject(i).let { Collection(it.getInt("id"), it.getString("name"), refs(it.optJSONArray("tracks"))) }
},
)
}
@Synchronized
fun load(context: Context) {
if (loaded) return
loaded = true
val f = file(context)
if (f.isFile) runCatching { state.value = decode(f.readText()) }
}
private fun commit(context: Context, next: Snapshot) {
state.value = next
val f = file(context)
val json = encode(next)
writer.execute {
runCatching {
val tmp = File(f.path + ".tmp")
tmp.writeText(json)
if (!tmp.renameTo(f)) tmp.delete()
}
}
}
fun tracksOf(id: Int): List<TrackRef> =
if (id == FAVORITES_ID) snapshot.favorites else snapshot.collections.firstOrNull { it.id == id }?.tracks.orEmpty()
fun isFavorite(path: String): Boolean = snapshot.favorites.any { it.path == path }
@Synchronized
fun toggleFavorite(context: Context, ref: TrackRef) {
load(context)
val s = snapshot
commit(context, Snapshot(toggled(s.favorites, ref), s.collections))
}
@Synchronized
fun create(context: Context, rawName: String, tracks: List<TrackRef>): Int? {
load(context)
val s = snapshot
val name = cleanName(rawName)
if (name.isEmpty() || nameTaken(s.collections, name)) return null
val id = nextId(s.collections)
commit(context, Snapshot(s.favorites, s.collections + Collection(id, name, merged(emptyList(), tracks))))
return id
}
@Synchronized
fun rename(context: Context, id: Int, rawName: String): Boolean {
load(context)
val s = snapshot
val name = cleanName(rawName)
if (id == FAVORITES_ID || name.isEmpty() || nameTaken(s.collections, name, id)) return false
commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, name, it.tracks) else it }))
return true
}
@Synchronized
fun delete(context: Context, id: Int) {
load(context)
val s = snapshot
if (id == FAVORITES_ID) return
commit(context, Snapshot(s.favorites, s.collections.filterNot { it.id == id }))
SoundtrackCollectionArt.clear(context, id)
}
@Synchronized
fun add(context: Context, id: Int, tracks: List<TrackRef>) {
load(context)
val s = snapshot
if (id == FAVORITES_ID) commit(context, Snapshot(merged(s.favorites, tracks), s.collections))
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, merged(it.tracks, tracks)) else it }))
}
@Synchronized
fun remove(context: Context, id: Int, paths: Set<String>) {
load(context)
val s = snapshot
if (id == FAVORITES_ID) commit(context, Snapshot(s.favorites.filterNot { it.path in paths }, s.collections))
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, it.tracks.filterNot { t -> t.path in paths }) else it }))
}
@Synchronized
fun reorder(context: Context, id: Int, ordered: List<String>) {
load(context)
val s = snapshot
fun arrange(list: List<TrackRef>): List<TrackRef> {
val byPath = list.associateBy { it.path }
val placed = ordered.mapNotNull { byPath[it] }
val named = ordered.toSet()
val rest = list.filter { it.path !in named }
return placed + rest
}
if (id == FAVORITES_ID) commit(context, Snapshot(arrange(s.favorites), s.collections))
else commit(context, Snapshot(s.favorites, s.collections.map { if (it.id == id) Collection(id, it.name, arrange(it.tracks)) else it }))
}
@Synchronized
fun refresh() {
state.value = Snapshot(state.value.favorites, state.value.collections)
}
internal fun autoCover(id: Int): File? = coverOf(tracksOf(id))
private fun coverOf(tracks: List<TrackRef>): File? =
tracks.firstNotNullOfOrNull { t -> t.cover.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } }
private fun game(context: Context, id: Int, name: String, tracks: List<TrackRef>): Library.SteamGame = Library.SteamGame(
appId = id, name = name, art = SoundtrackCollectionArt.chosen(context, id) ?: coverOf(tracks), library = Library.ADDED, gameId = id.toLong(),
source = Library.SOURCE_COLLECTION, soundtrack = true,
)
fun games(context: Context, favoritesLabel: String): List<Library.SteamGame> {
val s = snapshot
return listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + s.collections.map { game(context, it.id, it.name, it.tracks) }
}
fun album(context: Context, id: Int): Soundtrack.Album {
val tracks = tracksOf(id).filter { File(it.path).isFile }.mapIndexed { i, t ->
Soundtrack.Track(File(t.path), t.title, 1, i + 1, t.durationMs, t.artist)
}
return Soundtrack.Album(mapOf(1 to tracks), "", SoundtrackCollectionArt.chosen(context, id))
}
}
@@ -0,0 +1,32 @@
package com.droiddeck.launcher.frontend
import android.content.Context
object SoundtrackIndex {
class Hit(val ref: SoundtrackCollections.TrackRef, val game: Library.SteamGame)
private var cacheKey = ""
private var cache: List<Hit> = emptyList()
private fun fingerprint(dir: java.io.File?): Long =
if (dir == null) 0L else Soundtrack.audioFiles(dir).fold(17L) { h, f -> 31 * (31 * (31 * h + f.path.hashCode()) + f.length()) + f.lastModified() }
fun build(context: Context, games: List<Library.SteamGame>): List<Hit> {
val roots = games.filter { it.gameFiles != null }
val key = roots.joinToString("|") { "${it.appId}:${it.gameFiles?.path}:${it.art?.path}:${fingerprint(it.gameFiles)}" }
synchronized(this) { if (key == cacheKey) return cache }
val hits = roots.flatMap { g ->
val dir = g.gameFiles ?: return@flatMap emptyList()
val album = Soundtrack.load(context, dir, g.art)
val cover = (g.art ?: album.cover)?.path.orEmpty()
album.tracks.map { t ->
Hit(SoundtrackCollections.TrackRef(t.file.path, t.title, t.artist.ifBlank { album.artist }, g.name, t.durationMs, cover), g)
}
}
synchronized(this) {
cacheKey = key
cache = hits
}
return hits
}
}
@@ -0,0 +1,67 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import androidx.compose.runtime.mutableIntStateOf
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.Executors
object SoundtrackOrder {
private val changes = mutableIntStateOf(0)
private var cache: Map<String, List<String>>? = null
private val writer = Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-order").apply { isDaemon = true } }
val version: Int get() = changes.intValue
private fun file(context: Context) = File(context.filesDir, "soundtrack-order.json")
@Synchronized
private fun read(context: Context): Map<String, List<String>> {
cache?.let { return it }
val out = HashMap<String, List<String>>()
val f = file(context)
if (f.isFile) runCatching {
val json = JSONObject(f.readText())
for (key in json.keys()) {
val array = json.getJSONArray(key)
out[key] = List(array.length()) { array.getString(it) }
}
}
cache = out
return out
}
@Synchronized
fun set(context: Context, root: File, paths: List<String>) {
val next = HashMap(read(context))
next[root.path] = paths
cache = next
val body = JSONObject().also { json -> next.forEach { (k, v) -> json.put(k, JSONArray(v)) } }.toString()
val target = file(context)
writer.execute {
val tmp = File(target.path + ".tmp")
runCatching {
tmp.writeText(body)
if (!tmp.renameTo(target)) tmp.delete()
}
}
changes.intValue++
}
internal fun ordered(disc: Map<Int, List<Soundtrack.Track>>, order: List<String>): Map<Int, List<Soundtrack.Track>> {
if (order.isEmpty()) return disc
val index = HashMap<String, Int>()
order.forEachIndexed { i, p -> index.putIfAbsent(p, i) }
return disc.mapValues { (_, list) ->
list.sortedBy { index[it.file.path] ?: Int.MAX_VALUE }.mapIndexed { i, t ->
Soundtrack.Track(t.file, t.title, t.disc, i + 1, t.durationMs, t.artist, t.discLabel)
}
}
}
fun apply(context: Context, root: File, disc: Map<Int, List<Soundtrack.Track>>): Map<Int, List<Soundtrack.Track>> {
val order = read(context)[root.path] ?: return disc
return ordered(disc, order)
}
}
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.frontend
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Icon
import android.net.Uri
import android.widget.Toast
import com.droiddeck.launcher.FrontEndActivity
import com.droiddeck.launcher.LauncherIcon
import com.droiddeck.launcher.R
object SoundtrackShortcuts {
private val linkPattern = Regex("droiddeck://soundtrack/(-?[0-9]{1,11})")
fun uri(appId: Int): String = "droiddeck://soundtrack/$appId"
fun parse(link: String?): Int? = link?.let { linkPattern.matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }
fun read(intent: Intent): Int? = if (intent.action == Intent.ACTION_VIEW) parse(intent.dataString) else null
private fun info(context: Context, game: Library.SteamGame): ShortcutInfo {
val name = game.name.ifBlank { context.getString(R.string.app_name) }
val icon = GameShortcuts.iconBitmap(game)?.let(Icon::createWithBitmap) ?: Icon.createWithResource(context, R.mipmap.ic_launcher)
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri(game.appId)), context, FrontEndActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
return ShortcutInfo.Builder(context, "soundtrack:${game.appId}")
.setActivity(LauncherIcon.activity(context))
.setShortLabel(name.take(40)).setLongLabel(name).setIcon(icon).setIntent(intent).build()
}
fun pin(activity: Activity, game: Library.SteamGame) {
val manager = activity.getSystemService(ShortcutManager::class.java)
val requested = runCatching {
manager.isRequestPinShortcutSupported && manager.requestPinShortcut(info(activity, game), null)
}.getOrDefault(false)
if (!requested) Toast.makeText(activity, R.string.game_shortcut_unsupported, Toast.LENGTH_LONG).show()
}
}
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.frontend
object SoundtrackTracks {
enum class Sort { DEFAULT, TITLE_ASC, TITLE_DESC, LONGEST, SHORTEST }
fun <T> sort(items: List<T>, sort: Sort, title: (T) -> String, duration: (T) -> Long): List<T> = when (sort) {
Sort.DEFAULT -> items
Sort.TITLE_ASC -> items.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, title))
Sort.TITLE_DESC -> items.sortedWith(compareByDescending(String.CASE_INSENSITIVE_ORDER, title))
Sort.LONGEST -> items.sortedByDescending(duration)
Sort.SHORTEST -> items.sortedBy(duration)
}
fun matches(query: String, vararg fields: String): Boolean {
val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() }
if (words.isEmpty()) return true
val haystack = fields.map { it.lowercase() }
return words.all { word -> haystack.any { it.contains(word) } }
}
fun rank(query: String, title: String): Int {
val q = query.trim().lowercase()
val t = title.lowercase()
return when {
t == q -> 0
t.startsWith(q) -> 1
else -> 2
}
}
}
@@ -24,11 +24,7 @@ object SteamGameArt {
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO)
if (cover == null && hero == null && icon == null && logo == null) return game
return Library.SteamGame(
game.appId, game.name, cover ?: game.art, game.library, game.gameId,
hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId,
logo ?: game.logo,
)
return game.withArt(cover ?: game.art, hero ?: game.hero, icon ?: game.icon, logo ?: game.logo)
}
fun chosenSource(context: Context, appId: Int, slot: AddedGameArt.Slot): Pair<String, String> {
@@ -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 ->
@@ -28,12 +28,38 @@ object FrameGen {
fun engine(context: Context): String = mode(context).engine
fun mode(context: Context): Mode {
fun mode(context: Context): Mode = mode(context, null)
fun mode(context: Context, appId: String?): Mode {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val engine = prefs.getString("engine", ENGINE_OFF).let { if (it == LEGACY_ENGINE_WINFG) ENGINE_DDFG else it ?: ENGINE_OFF }
val target = prefs.getInt("target", 0)
val gamePrefix = appId?.takeIf { it.isNotBlank() }?.let { "game.$it." }
?.takeIf { prefs.contains(it + "engine") } ?: ""
val engine = prefs.getString(gamePrefix + "engine", ENGINE_OFF)
.let { if (it == LEGACY_ENGINE_WINFG) ENGINE_DDFG else it ?: ENGINE_OFF }
val target = prefs.getInt(gamePrefix + "target", 0)
if (engine == ENGINE_LSFG && target in ADAPTIVE_TARGETS) return Mode(engine, target = target)
return Mode(engine, prefs.getInt("multiplier", 2).coerceIn(2, 4))
return Mode(engine, prefs.getInt(gamePrefix + "multiplier", 2).coerceIn(2, 4))
}
fun hasGameOverride(context: Context, appId: String): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).contains("game.$appId.engine")
fun setForGame(context: Context, appId: String, mode: Mode) {
val prefix = "game.$appId."
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(prefix + "engine", mode.engine)
.putInt(prefix + "multiplier", mode.multiplier)
.putInt(prefix + "target", mode.target)
.apply()
}
fun clearGame(context: Context, appId: String) {
val prefix = "game.$appId."
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove(prefix + "engine")
.remove(prefix + "multiplier")
.remove(prefix + "target")
.apply()
}
fun set(context: Context, mode: Mode) {
@@ -41,6 +67,11 @@ object FrameGen {
.putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply()
}
fun clearGlobal(context: Context) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.remove("engine").remove("multiplier").remove("target").apply()
}
fun label(context: Context): String = label(context, mode(context))
fun label(context: Context, mode: Mode): String = when {
@@ -50,14 +81,32 @@ object FrameGen {
else -> context.getString(R.string.frame_gen_off)
}
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz)
data class PreparedApply internal constructor(
val mode: Mode,
internal val lsfgStatus: Int? = null,
internal val lsfgCachePath: String? = null,
)
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
fun prepareApply(context: Context, mode: Mode): PreparedApply {
if (mode.engine != ENGINE_LSFG) return PreparedApply(mode)
val status = Lossless.sync(context)
val cachePath = Lossless.cacheFile(context)?.absolutePath
return PreparedApply(mode, status, cachePath)
}
fun apply(context: Context, refreshHz: Float): String? =
apply(context, mode(context), refreshHz)
fun apply(context: Context, mode: Mode, refreshHz: Float): String? =
applyPrepared(context, prepareApply(context, mode), refreshHz)
fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? {
val mode = prepared.mode
when (mode.engine) {
ENGINE_LSFG -> {
val status = Lossless.sync(context)
val cache = Lossless.cacheFile(context)
if (status != LsfgNative.STATUS_OK || cache == null) {
val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED
val cachePath = prepared.lsfgCachePath
if (status != LsfgNative.STATUS_OK || cachePath == null) {
WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
val problem = context.getString(
if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed,
@@ -66,7 +115,7 @@ object FrameGen {
return problem
}
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG)
WaylandCompositor.nativeSetLsfgCachePath(cache.absolutePath)
WaylandCompositor.nativeSetLsfgCachePath(cachePath)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, mode.target)
}
@@ -7,15 +7,21 @@ internal object DroidDeckHudConfig {
val DEFAULTS: Map<String, String> = linkedMapOf(
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
"hudOutline" to "40", "hudOutlineAccent" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
"showGpuModel" to "1", "showGPULoad" to "1", "showCPUUsage" to "1", "showCPULoad" to "1",
"showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0",
"showVram" to "1", "showRAM" to "1", "showSwap" to "1", "showBattery" to "0", "showBatteryTime" to "0", "showPower" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "fpsDecimal" to "1",
"showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1",
"showEngine" to "1", "showRenderer" to "1",
"showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1",
"showProton" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "",
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
)
private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer")
private val NOT_READINGS = setOf("showCPULoad", "showRenderer", "fpsDecimal")
/** Orders saved before the GPU switch was named after the alias the HUD actually reads. */
private val RENAMED = mapOf("showGPU" to "showGPULoad")
fun load(context: Context): MutableMap<String, String> {
val values = LinkedHashMap(DEFAULTS)
@@ -36,7 +42,31 @@ internal object DroidDeckHudConfig {
val values = load(context)
if (key !in DEFAULTS) return values
values[key] = value
TWINS[key]?.let { values[it] = value }
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
return values
}
/** Writes several switches and the row order in one go, so the HUD is rebuilt once. */
fun choose(context: Context, switches: Map<String, Boolean>, order: List<String>): Map<String, String> {
val values = load(context)
for ((key, on) in switches) if (key in DEFAULTS) {
values[key] = flag(on)
}
val size = DroidDeckHudSize.from(values["hudSize"])
val groups = sizeOrders(values).toMutableMap()
if (groups.isEmpty()) {
val legacy = legacyOrder(values)
if (legacy.isNotEmpty()) for (each in DroidDeckHudSize.values()) groups[each] = legacy.filter { it in each.rows }
}
groups[size] = order.filter { it in ORDER }
values["hudOrder"] = encodeOrders(groups)
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
return values
}
fun clearOrder(context: Context): Map<String, String> {
val values = load(context)
values["hudOrder"] = ""
SessionPrefs.setDroidDeckHudConfig(context, encode(values))
return values
}
@@ -46,5 +76,37 @@ internal object DroidDeckHudConfig {
return DEFAULTS
}
/** Every metric switch, in the order the HUD lists them before the user moves any. Derived from
* [DEFAULTS], so a switch added there shows up here without a second list to keep in step. */
val ORDER: List<String> = DEFAULTS.keys.filter { it.startsWith("show") && it !in NOT_READINGS }
/** Only the rows the user moved for [size], in the order they left them. */
fun storedOrder(values: Map<String, String>, size: DroidDeckHudSize): List<String> =
sizeOrders(values)[size] ?: legacyOrder(values)
/** Orders saved before each size kept its own: one list, applied to every size. */
private fun legacyOrder(values: Map<String, String>): List<String> {
val raw = values["hudOrder"].orEmpty()
if (raw.isBlank() || raw.contains(':')) return emptyList()
return raw.split('|').map { RENAMED[it] ?: it }.filter { it in ORDER }
}
private fun sizeOrders(values: Map<String, String>): Map<DroidDeckHudSize, List<String>> {
val raw = values["hudOrder"].orEmpty()
if (raw.isBlank()) return emptyMap()
val groups = LinkedHashMap<DroidDeckHudSize, List<String>>()
for (group in raw.split(';')) {
val colon = group.indexOf(':')
if (colon <= 0) continue
val size = DroidDeckHudSize.values().firstOrNull { it.token == group.substring(0, colon) } ?: continue
groups[size] = group.substring(colon + 1).split('|').map { RENAMED[it] ?: it }.filter { it in ORDER }
}
return groups
}
private fun encodeOrders(groups: Map<DroidDeckHudSize, List<String>>): String =
groups.entries.filter { it.value.isNotEmpty() }
.joinToString(";") { "${it.key.token}:${it.value.joinToString("|")}" }
private fun flag(on: Boolean) = if (on) "1" else "0"
}
@@ -10,11 +10,9 @@ import android.view.View
import android.view.animation.PathInterpolator
import android.view.ViewGroup
import android.widget.FrameLayout
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.ui.Motion
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -24,7 +22,7 @@ import kotlin.math.roundToInt
class DroidDeckHudHost(context: Context) {
private val context = context.applicationContext
private val handler = Handler(Looper.getMainLooper())
private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH))
private val feed = GameFrameFeed.forRoot(LinuxRuntime.rootDir(this.context))
private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context))
private var view: DroidDeckHudView? = null
private var parent: ViewGroup? = null
@@ -39,6 +37,8 @@ class DroidDeckHudHost(context: Context) {
private var snapping = false
private var previewFade: ValueAnimator? = null
private var flingX = 0f
private var flingY = 0f
private var throwSpring: com.droiddeck.launcher.ui.FlingSpring? = null
private var engine = ""
private var gpuName = ""
private var protonPid = 0
@@ -95,18 +95,22 @@ class DroidDeckHudHost(context: Context) {
stopMotion(hud)
shrinkPastEdge(hud, rawX, rawY)
}
hud.setOnFlungListener { vx, _ -> flingX = vx }
hud.setOnFlungListener { vx, vy -> flingX = vx; flingY = vy }
hud.setOnTabDraggedListener { x, y -> dragTab(hud, x, y) }
hud.setOnTabDroppedListener { dropTab(hud) }
hud.setOnTabDragCancelledListener { snapping = false; keepOnScreen(hud) }
hud.setOnMovedListener { x, y ->
wantX = x; wantY = y
val vx = flingX
val vy = flingY
flingX = 0f
dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
flingY = 0f
// A throw only carries the strip into its tab; a floating HUD flung across goes to the other side.
val coast = hud.isStrip
dockEdgeFor(hud, if (coast) vx else 0f, if (coast) vy else 0f)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
stopMotion(hud)
fadeDockPreview(hud)
if (snaps && !hud.isStrip) { snapToAnchor(hud, vx); return@setOnMovedListener }
if (snaps && !hud.isStrip) { snapToAnchor(hud, vx, vy); return@setOnMovedListener }
val fromX = hud.x; val fromY = hud.y
keepOnScreen(hud)
wantX = hud.x; wantY = hud.y
@@ -179,9 +183,8 @@ class DroidDeckHudHost(context: Context) {
private fun applyShown() {
if (!running) return
val show = !hidden && !backgrounded
val visible = show && SessionState.mode != SessionService.MODE_DESKTOP
view?.visibility = if (visible) View.VISIBLE else View.GONE
showing = visible
view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show
if (show != polling) {
polling = show
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
@@ -238,28 +241,36 @@ class DroidDeckHudHost(context: Context) {
}
private fun presentedFps(): Float {
if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f
val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f
if (!runCatching { WaylandCompositor.nativeFrameGenActive() }
.getOrDefault(false)) return 0f
val stats = runCatching {
WaylandCompositor.nativeFrameGenStats()
}.getOrNull() ?: return 0f
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
}
private fun dockEdgeFor(v: View): DroidDeckHudDock? {
val over = overhang(v) ?: return null
/** The edge the HUD tucks into: one it hangs far enough over, or would once a throw at [vx], [vy] coasts out. */
private fun dockEdgeFor(v: View, vx: Float = 0f, vy: Float = 0f): DroidDeckHudDock? {
val over = overhang(v, vx * com.droiddeck.launcher.ui.EdgeFling.COAST_S, vy * com.droiddeck.launcher.ui.EdgeFling.COAST_S) ?: return null
return over.key.takeIf { over.value >= DOCK_OVERHANG }
}
private fun overhang(v: View): Map.Entry<DroidDeckHudDock, Float>? {
private fun overhang(v: View, dx: Float = 0f, dy: Float = 0f): Map.Entry<DroidDeckHudDock, Float>? {
val p = v.parent as? View ?: return null
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
val strip = (v as? DroidDeckHudView)?.isStrip == true
val density = v.resources.displayMetrics.density
val w = if (strip) minOf(v.width.toFloat(), STRIP_PULL_ACROSS_DP * density) else v.width.toFloat()
val h = if (strip) maxOf(v.height.toFloat(), STRIP_PULL_OFF_DP * density) else v.height.toFloat()
val x = v.x + dx
val y = v.y + dy
return mapOf(
DroidDeckHudDock.LEFT to -v.x / w,
DroidDeckHudDock.RIGHT to (v.x + v.width - p.width) / w,
DroidDeckHudDock.TOP to -v.y / h,
DroidDeckHudDock.BOTTOM to (v.y + v.height - p.height) / h,
DroidDeckHudDock.LEFT to -x / w,
DroidDeckHudDock.RIGHT to (x + v.width - p.width) / w,
DroidDeckHudDock.TOP to -y / h,
DroidDeckHudDock.BOTTOM to (y + v.height - p.height) / h,
).maxByOrNull { it.value }
}
@@ -294,6 +305,7 @@ class DroidDeckHudHost(context: Context) {
}
private fun stopMotion(hud: DroidDeckHudView) {
throwSpring?.cancel()
hud.animate().setUpdateListener(null)
hud.animate().cancel()
}
@@ -323,23 +335,21 @@ class DroidDeckHudHost(context: Context) {
}
}
private fun snapToAnchor(hud: DroidDeckHudView, vx: Float) {
/** Sends the HUD to a side the way a chat head goes: by where the throw would carry it, springing on from its speed. */
private fun snapToAnchor(hud: DroidDeckHudView, vx: Float, vy: Float) {
val p = hud.parent as? View ?: return
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f)
anchorX = if (hud.x + vx * FLING_REACH_S < maxX / 2f) 0f else 1f
val right = com.droiddeck.launcher.ui.EdgeFling.toRight(hud.x + hud.width / 2f, p.width.toFloat(), vx, context.resources.displayMetrics.density)
anchorX = if (right) 1f else 0f
wantX = anchorX * maxX
wantY = hud.y.coerceIn(0f, maxY)
wantY = com.droiddeck.launcher.ui.EdgeFling.restY(hud.y, vy, 0f, maxY)
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
stopMotion(hud)
if (Motion.scale == 0f) {
hud.scaleX = 1f; hud.scaleY = 1f
hud.x = wantX; hud.y = wantY
return
}
hud.scaleX = 1f; hud.scaleY = 1f
snapping = true
hud.animate().x(wantX).y(wantY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(260).toLong()).setInterpolator(EASE)
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
val spring = throwSpring ?: com.droiddeck.launcher.ui.FlingSpring { sx, sy -> hud.x = sx; hud.y = sy }.also { throwSpring = it }
spring.start(hud.x, hud.y, vx, vy, wantX, wantY) { snapping = false; keepOnScreen(hud) }
}
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
@@ -496,10 +506,9 @@ class DroidDeckHudHost(context: Context) {
companion object {
private const val DOCK_OVERHANG = 0.4f
private const val FLING_REACH_S = 0.18f
private const val PREVIEW_FROM = 0.55f
private const val STRIP_PULL_ACROSS_DP = 600f
private const val STRIP_PULL_OFF_DP = 150f
private const val STRIP_PULL_ACROSS_DP = 360f
private const val STRIP_PULL_OFF_DP = 100f
private const val EXPAND_FADE = 0.5f
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
@@ -13,6 +13,27 @@
package com.droiddeck.launcher.hud
/**
* Size modes for the DroidDeck HUD (the 4th selectable in-game overlay style). One shared color-coded
* visual language, four amounts of detail — see the approved mockup. The config value is the lower-case
* token stored under the `hudSize` key; the label is the user-facing string.
*/
/** The text sizes and spacing a [DroidDeckHudSize] lays its rows out with, in sp. */
data class DroidDeckHudStyle(
val row: Float,
val unit: Float,
val pad: Float,
val lineGap: Float,
val labelGap: Float,
val key: Float = 0f,
val sub: Float = 0f,
val foot: Float = 0f,
val band: Float = 0f,
val gutter: Float = 0f,
val tileGap: Float = 0f,
val innerPad: Float = 0f,
)
enum class DroidDeckHudSize(val token: String, val label: String) {
FULL("full", "Full"),
TILES("tiles", "Tiles"),
@@ -26,27 +47,73 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
return all[(ordinal + 1) % all.size]
}
fun supportedChips(): Set<String> = when (this) {
MINIMAL -> MINIMAL_CHIPS
PILL -> PILL_CHIPS
FULL, TILES, STRIP -> STANDARD_CHIPS
MEGA -> MEGA_CHIPS
}
/**
* The rows this size draws, in the order it draws them before the user moves any. This is the single
* source of truth for both surfaces: [DroidDeckHudView] draws exactly these and the settings screen
* offers exactly these. A switch outside the set is ignored by the size, so the two cannot drift.
*/
val rows: List<String> get() = ROWS.getValue(this)
/** This size's rows: the ones the user moved first, then the rest in the order [rows] lists them. */
fun rowsIn(stored: List<String>): List<String> =
stored.filter { it in rows } + rows.filter { it !in stored }
/**
* The numbers each size sets its text in, in sp. One table so a size's scale can be read (and changed)
* in one place instead of hunting the `sp(...)` literals scattered through its builder.
*/
val style: DroidDeckHudStyle get() = STYLE.getValue(this)
companion object {
fun from(token: String?): DroidDeckHudSize =
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "1% low", "0.1% low", "0.01% low", "FPS .1", "Engine", "Clock")
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
val STANDARD_CHIPS = setOf(
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
"Battery", "GPU model", "Engine", "1% low", "0.1% low", "0.01% low", "FPS .1", "Clock",
private val EXTRAS = setOf("showClock")
val ROWS: Map<DroidDeckHudSize, List<String>> = mapOf(
FULL to listOf(
"showFPS", "showFPSGraph", "showGpuModel", "showDisplay", "showHdr", "showGPULoad", "showGpuTemp",
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
"showPower", "showLatency", "showAvg", "showLow1", "showLow01", "showLow001",
),
TILES to listOf(
"showFPS", "showFPSGraph", "showLatency", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
"showVram", "showRAM", "showEngine", "showDisplay", "showHdr", "showAvg", "showLow1",
"showLow01", "showLow001", "showGpuModel", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower",
),
PILL to listOf(
"showFPS", "showFPSGraph", "showGpuModel", "showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp",
"showRAM", "showBattery", "showBatteryTemp", "showBatteryTime", "showPower", "showLatency", "showDisplay",
"showVram", "showHdr",
),
MINIMAL to listOf(
"showFPS", "showBatteryTime", "showFPSGraph", "showLow1", "showLow01", "showLow001", "showAvg", "showLatency",
"showEngine", "showDisplay", "showHdr",
),
MEGA to DroidDeckHudConfig.ORDER.filter { it !in EXTRAS },
STRIP to listOf(
"showFPS", "showFPSGraph", "showLow1", "showLow01", "showLow001", "showGPULoad", "showGpuTemp",
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
"showPower", "showDisplay", "showHdr", "showGpuModel",
),
)
val MEGA_ONLY = setOf(
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
val STYLE: Map<DroidDeckHudSize, DroidDeckHudStyle> = mapOf(
FULL to DroidDeckHudStyle(row = 12f, unit = 12f * 0.62f, pad = 10f, lineGap = 4f, labelGap = 8f),
TILES to DroidDeckHudStyle(row = 18f, unit = 11f, pad = 9f, lineGap = 4f, labelGap = 8f,
key = 10f, sub = 10f, tileGap = 6f, innerPad = 8f),
PILL to DroidDeckHudStyle(row = 30f, unit = 30f * 0.36f, pad = 10f, lineGap = 3f, labelGap = 12f,
sub = 11.5f),
MINIMAL to DroidDeckHudStyle(row = 34f, unit = 34f * 0.32f, pad = 10f, lineGap = 4f, labelGap = 8f,
sub = 11.5f, foot = 9.5f),
MEGA to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.62f, pad = 10f, lineGap = 3.5f, labelGap = 7f,
band = 9.5f, gutter = 16f),
STRIP to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.8f, pad = 10f, lineGap = 0f, labelGap = 13f),
)
val MEGA_CHIPS = STANDARD_CHIPS + MEGA_ONLY
fun rowsFor(size: DroidDeckHudSize, values: Map<String, String>): List<String> =
size.rowsIn(DroidDeckHudConfig.storedOrder(values, size))
}
}
@@ -69,6 +69,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private val density = resources.displayMetrics.density
private var cfg: KeyValueSet = KeyValueSet()
private var size = DroidDeckHudSize.FULL
private var scale = 1f
private var bgOpacity = 0.8f
@@ -95,13 +96,16 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showLow001 = true
private var fpsDecimal = true
private var showClockTime = true
private var showLatency = true
private var showAvg = true
private var showDisplay = true
private var showHdr = true
private var storedOrder: List<String> = emptyList()
private var showPerCore = true
private var showSwap = true
private var showNet = true
private var showResolution = true
private var showProton = true
private var showWrapper = true
private var showDxVer = true
private var showSession = true
private var engineLabel = ""
@@ -177,7 +181,7 @@ class DroidDeckHudView(context: Context) : View(context) {
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, glow)
}
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
private class HudRow(val label: Span, val vals: List<Span>, val inline: Boolean = false)
private class HudRow(val key: String, val label: Span, val vals: List<Span>, val inline: Boolean = false)
private val glyphs = ArrayList<Glyph>()
private val tileRects = ArrayList<RectF>()
private var graphRect: RectF? = null
@@ -289,41 +293,52 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun cycleSize() {
size = size.next()
refreshOrder()
onSizeCycledListener?.accept(size.token)
rebuildAndInvalidate()
}
private fun refreshOrder() {
storedOrder = DroidDeckHudConfig.storedOrder(mapOf("hudOrder" to cfg.get("hudOrder", "")), size)
}
private fun switchOn(key: String): Boolean =
cfg.get(key, DroidDeckHudConfig.DEFAULTS[key] ?: "1") == "1"
fun applyConfig(configString: String?) {
if (configString.isNullOrEmpty()) return
val cfg = KeyValueSet(configString)
cfg = KeyValueSet(configString)
size = DroidDeckHudSize.from(cfg.get("hudSize", "minimal"))
showFPS = cfg.get("showFPS", "1") == "1"
showEngine = cfg.get("showEngine", "1") == "1"
showGpuModel = cfg.get("showGpuModel", "1") == "1"
showCPU = cfg.get("showCPUUsage", cfg.get("showCPULoad", "1")) == "1"
showGPU = cfg.get("showGPULoad", "1") == "1"
showCpuTemp = cfg.get("showTemp", "1") == "1"
showGpuTemp = cfg.get("showGpuTemp", "0") == "1"
showVram = cfg.get("showVram", "1") == "1"
showRAM = cfg.get("showRAM", "1") == "1"
showBattery = cfg.get("showBattery", "1") == "1"
showPower = cfg.get("showPower", "1") == "1"
showBatteryTemp = cfg.get("showBatteryTemp", "0") == "1"
showGraph = cfg.get("showFPSGraph", "0") == "1"
showLow1 = cfg.get("showLow1", "1") == "1"
showLow01 = cfg.get("showLow01", "1") == "1"
showLow001 = cfg.get("showLow001", "1") == "1"
showFPS = switchOn("showFPS")
showEngine = switchOn("showEngine")
showGpuModel = switchOn("showGpuModel")
showCPU = switchOn("showCPUUsage")
showGPU = switchOn("showGPULoad")
showCpuTemp = switchOn("showTemp")
showGpuTemp = switchOn("showGpuTemp")
showVram = switchOn("showVram")
showRAM = switchOn("showRAM")
showBattery = switchOn("showBattery")
showPower = switchOn("showPower")
showBatteryTemp = switchOn("showBatteryTemp")
showGraph = switchOn("showFPSGraph")
showLow001 = switchOn("showLow001")
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
showClockTime = cfg.get("showClock", "1") == "1"
showPerCore = cfg.get("showPerCore", "1") == "1"
showSwap = cfg.get("showSwap", "1") == "1"
showNet = cfg.get("showNet", "1") == "1"
showResolution = cfg.get("showResolution", "1") == "1"
showProton = cfg.get("showProton", "1") == "1"
showWrapper = cfg.get("showWrapper", "1") == "1"
showDxVer = cfg.get("showDxVer", "1") == "1"
showSession = cfg.get("showSession", "1") == "1"
showClockTime = switchOn("showClock")
showLatency = switchOn("showLatency")
showAvg = switchOn("showAvg")
showLow1 = switchOn("showLow1")
showLow01 = switchOn("showLow01")
showDisplay = switchOn("showDisplay")
showHdr = switchOn("showHdr")
refreshOrder()
showPerCore = switchOn("showPerCore")
showSwap = switchOn("showSwap")
showNet = switchOn("showNet")
showResolution = switchOn("showResolution")
showProton = switchOn("showProton")
showSession = switchOn("showSession")
tempDisplay = HudMetrics.TempDisplay.from(cfg)
lockController.setLocked(cfg.get("hudLocked", "1") == "1")
dock = DroidDeckHudDock.from(cfg.get("hudDock", "none"))
@@ -458,6 +473,8 @@ class DroidDeckHudView(context: Context) : View(context) {
return w
}
private fun showHdrLine(): Boolean = showHdr && hdrState != DroidDeckHudHdr.NONE
private fun placeRun(startX: Float, baseline: Float, spans: List<Span>, glow: Boolean = false): Float {
var x = startX
for (s in spans) {
@@ -539,13 +556,15 @@ class DroidDeckHudView(context: Context) : View(context) {
val s = snap
if (s == null) { contentW = 0f; contentH = 0f; return }
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
buildRows(s)
if (contentW <= 0f || contentH <= 0f) return
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
val pad = sp(size.style.pad)
when (size) {
DroidDeckHudSize.FULL -> { buildFull(s); intoPanel(sp(10f), header = true) }
DroidDeckHudSize.TILES -> { buildTiles(s); intoPanel(sp(9f), header = true) }
DroidDeckHudSize.PILL -> { buildPill(s); intoPanel(sp(10f), header = false) }
DroidDeckHudSize.MINIMAL -> buildMinimal(s)
DroidDeckHudSize.MEGA -> { buildMega(s); intoPanel(sp(10f), header = true) }
DroidDeckHudSize.STRIP -> buildStrip(s)
DroidDeckHudSize.MINIMAL -> intoPanel(pad, header = true, halfRound = true)
DroidDeckHudSize.PILL -> intoPanel(pad, header = false)
else -> intoPanel(pad, header = true)
}
}
@@ -615,7 +634,12 @@ class DroidDeckHudView(context: Context) : View(context) {
return Pair(dDividerTop + max(1f, density), x)
}
private fun intoPanel(pad: Float, header: Boolean) {
/**
* Moves a size's content, laid out from [pad] at the origin, into the panel: under the header, or after
* the logo chip on the Pill. Lines that start on the content's left edge are lined up by their ink, so
* the logo, labels and numbers share one edge.
*/
private fun intoPanel(pad: Float, header: Boolean, halfRound: Boolean = !header) {
if (contentW <= 0f || contentH <= 0f) return
for (i in glyphs.indices) {
val g = glyphs[i]
@@ -641,7 +665,7 @@ class DroidDeckHudView(context: Context) : View(context) {
val panel = RectF(panelLeft(), panelInset(), max(contentW - pad + dx, headerRight) + sp(18f),
contentH - pad + dy + sp(10f) + stroke)
chipRect?.let { it.offsetTo(it.left, panel.centerY() - it.height() / 2f) }
finishPanel(panel, halfRound = !header)
finishPanel(panel, halfRound = halfRound)
}
private fun finishPanel(panel: RectF, halfRound: Boolean) {
@@ -712,316 +736,188 @@ class DroidDeckHudView(context: Context) : View(context) {
contentW = max(contentW, pad + w + pad)
}
private fun hasGpuStats(s: HudMetrics.Snapshot): Boolean =
s.gpuPercent != null || s.gpuTempC != null || s.gpuClockMhz != null
private fun buildFull(s: HudMetrics.Snapshot) {
val rowPx = sp(12f); val unitPx = rowPx * 0.62f
val pad = sp(10f); val lineGap = sp(4f); val lvGap = sp(8f)
val rows = ArrayList<HudRow>()
if (showGpuModel && gpuNameText().isNotBlank())
rows.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
if (displayServer.isNotBlank())
rows.add(HudRow(Span("DISP", colDisp, rowPx), listOf(Span(displayServer, colValue, rowPx))))
if (hdrState != DroidDeckHudHdr.NONE)
rows.add(HudRow(Span("HDR", colHdr, rowPx), hdrValue(rowPx)))
if (showGPU && hasGpuStats(s)) {
val v = ArrayList<Span>()
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx)
rows.add(HudRow(Span("GPU", colGpu, rowPx), v))
}
if (showCPU) {
val v = ArrayList<Span>()
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
rows.add(HudRow(Span("CPU", colCpu, rowPx), v))
}
if (showVram && s.vramText() != null)
rows.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
if (showRAM) {
val v = ArrayList<Span>()
v += valueUnit(s.ramUsedText(), rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx)
rows.add(HudRow(Span("RAM", colRam, rowPx), v))
}
if (showBattery || showPower || showBatteryTemp) {
val v = ArrayList<Span>(); var any = false
if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true }
if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx)
.let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } }
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
if (any) rows.add(HudRow(Span("BAT", colBat, rowPx), v))
}
if (showFPS) {
val v = ArrayList<Span>()
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
if (showLow1)
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
if (showLow01)
rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow001)
rows.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
var labelCol = 0f
for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx))
val h = lineH(rowPx); val asc = ascent(rowPx)
var y = pad; var maxRight = pad
for (r in rows) {
val baseline = y - asc
placeRun(pad, baseline, listOf(r.label))
val valX = if (r.inline) pad + measure(r.label.text, rowPx) + lvGap
else pad + labelCol + lvGap
val end = placeRun(valX, baseline, r.vals)
maxRight = max(maxRight, end)
y += h + lineGap
}
if (showFPS && showGraph) {
val ftPx = unitPx * 1.15f
val baseline = y - asc
placeRun(pad, baseline, listOf(Span("Frametime", colFps, ftPx)))
val stat = "min:${fmt1(graphMinMs)} max:${fmt1(graphMaxMs)}"
val statX = pad + max(labelCol, measure("Frametime", ftPx)) + lvGap
val end = placeRun(statX, baseline, listOf(Span(stat, colDim, unitPx)))
maxRight = max(maxRight, end)
y += h + lineGap
val gh = sp(22f)
val right = max(maxRight, pad + sp(160f))
graphRect = RectF(pad, y, right, y + gh)
maxRight = max(maxRight, right)
y += gh
}
contentW = maxRight + pad
contentH = y + pad
addSubtleClock(pad)
private fun switchLabel(key: String): Pair<String, Int> = when (key) {
"showGpuModel" -> "MODEL" to colGpu
"showGPULoad" -> "GPU" to colGpu
"showGpuTemp" -> "GPU.T" to colGpu
"showCPUUsage" -> "CPU" to colCpu
"showTemp" -> "CPU.T" to colCpu
"showBatteryTemp" -> "BAT.T" to colBat
"showPower" -> "PWR" to colBat
"showBattery" -> "BAT" to colBat
"showBatteryTime" -> "BAT TIME" to colBat
"showVram" -> "VRAM" to colVram
"showRAM" -> "RAM" to colRam
"showSwap" -> "SWP" to colRam
"showNet" -> "NET" to colFps
"showPerCore" -> "CORE" to colCpu
"showFPS" -> "FPS" to colFps
"showLatency" -> "MS" to colDim
"showAvg" -> "AVG" to colLo
"showLow1" -> "1%" to colLo
"showLow01" -> "0.1%" to colLo
"showLow001" -> "0.01%" to colLo
"showEngine" -> "API" to colFps
"showDisplay" -> "DISP" to colDisp
"showHdr" -> "HDR" to colHdr
"showResolution" -> "RES" to colDim
"showProton" -> "PROTON" to colVram
"showSession" -> "TIME" to colDim
else -> key.removePrefix("show") to colDim
}
private fun buildTiles(s: HudMetrics.Snapshot) {
val keyPx = sp(10f); val valPx = sp(18f); val subPx = sp(10f); val unitPx = sp(11f)
val pad = sp(9f); val innerPad = sp(8f); val tileGap = sp(6f); val lineGap = sp(4f)
class Tile(val key: String, val keyColor: Int, val value: List<Span>, val sub: String?, val wide: Boolean)
val tiles = ArrayList<Tile>()
if (showFPS) tiles.add(Tile("FPS", colFps, listOf(Span(fpsText(fpsNow), colValue, valPx, glow = true)),
"${fmt1(fpsAvg)} avg" + (if (showLow1) " · ${lowText(lows.low1Fps) ?: "—"} 1%" else ""), false))
if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx),
"${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false))
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
if (showGpuTemp && s.gpuTempC != null) HudMetrics.formatTemp(s.gpuTempC.toFloat(), tempDisplay, false)
else s.gpuClockMhz?.let { "${it}MHz" }, false))
if (showCPU) tiles.add(Tile("CPU", colCpu, numUnit(s.cpuPercent?.toString(), "%", valPx, unitPx),
listOfNotNull(s.cpuClockMhz?.let { "${it}MHz" },
if (showCpuTemp) s.cpuTempC?.let { HudMetrics.formatTemp(it.toFloat(), tempDisplay, false) } else null)
.joinToString(" · ").ifBlank { null }, false))
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
if (showEngine && engineLabel.isNotBlank())
tiles.add(Tile("API", colFps, listOf(Span(engineLabel, colValue, valPx)),
dxVersion().ifBlank { null }, false))
if (displayServer.isNotBlank())
tiles.add(Tile("DISPLAY", colDisp, listOf(Span(displayServer, colValue, valPx)),
if (hdrState != DroidDeckHudHdr.NONE) hdrText() else null, false))
if (showGpuModel && gpuNameText().isNotBlank())
tiles.add(Tile("GPU", colGpu, gpuModelSpans(valPx, colValue), null, true))
if (showBattery || showPower || showBatteryTemp) {
val parts = ArrayList<Span>(); var any = false
if (showBattery && s.battery.percent != null) { parts += numUnit(s.battery.percent.toString(), "%", valPx, unitPx); any = true }
if (showBatteryTemp && s.battery.tempC != null) { if (any) parts += Span(" · ", colDim, subPx); parts += tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valPx, unitPx); any = true }
if (showPower && s.battery.watts > 0f) { if (any) parts += Span(" · ", colDim, subPx); parts += numUnit(fmt1(s.battery.watts), "W", valPx, unitPx); any = true }
if (any) tiles.add(Tile("BAT", colBat, parts, null, true))
private fun reading(key: String, s: HudMetrics.Snapshot, labelPx: Float, valuePx: Float, unitPx: Float): HudRow {
if (key == "showFPSGraph") return HudRow(key, Span("", colDim, 0f), emptyList())
val (label, color) = switchLabel(key)
val values: List<Span> = when (key) {
"showGpuModel" -> if (gpuNameText().isBlank()) numUnit(null, "", valuePx, unitPx)
else gpuModelSpans(valuePx, colValue)
"showGPULoad" -> numUnit(s.gpuPercent?.toString(), "%", valuePx, unitPx)
"showGpuTemp" -> tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, valuePx, unitPx)
"showCPUUsage" -> numUnit(s.cpuPercent?.toString(), "%", valuePx, unitPx)
"showTemp" -> tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, valuePx, unitPx)
"showBatteryTemp" -> tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, valuePx, unitPx)
"showPower" -> numUnit(if (s.battery.watts > 0f) fmt1(s.battery.watts) else null, "W", valuePx, unitPx)
"showBattery" -> numUnit(s.battery.percent?.toString(), "%", valuePx, unitPx)
"showBatteryTime" -> valueUnit(s.battery.runtimeText ?: "—", valuePx, unitPx)
"showVram" -> valueUnit(s.vramText() ?: "—", valuePx, unitPx)
"showRAM" -> numUnit(s.ramPercent.roundToInt().toString(), "%", valuePx, unitPx)
"showSwap" -> valueUnit(s.swapUsedText() ?: "—", valuePx, unitPx)
"showNet" -> listOf(
Span("↓", colDim, unitPx), Span(((s.netDownBps ?: 0L) / 1024L).toString(), colValue, valuePx),
Span(" ↑", colDim, unitPx), Span(((s.netUpBps ?: 0L) / 1024L).toString(), colValue, valuePx),
)
"showPerCore" -> listOf(Span(s.perCorePercent.size.toString(), colValue, valuePx))
"showFPS" -> glowing(numUnit(fpsText(fpsNow), "", valuePx, unitPx))
"showLatency" -> numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valuePx, unitPx)
"showAvg" -> numUnit(fmt1(fpsAvg), "", valuePx, unitPx)
"showLow1" -> numUnit(lowText(lows.low1Fps), "", valuePx, unitPx)
"showLow01" -> numUnit(lowText(lows.low01Fps), "", valuePx, unitPx)
"showLow001" -> numUnit(lowText(lows.low001Fps), "", valuePx, unitPx)
"showEngine" -> listOf(Span(engineLabel.ifBlank { "—" }, colValue, valuePx))
"showDisplay" -> listOf(Span(displayServer.ifBlank { "—" }, colDisp, valuePx))
"showHdr" -> if (showHdrLine()) hdrValue(valuePx) else listOf(Span("off", colDim, valuePx))
"showResolution" -> listOf(Span(resolutionString(), colValue, valuePx))
"showProton" -> listOf(Span(wineVersion.ifBlank { "—" }, colVram, valuePx))
"showSession" -> listOf(Span(elapsedString(), colValue, valuePx))
else -> listOf(Span("—", colDim, valuePx))
}
if (tiles.isEmpty()) { contentW = 0f; contentH = 0f; return }
val keyH = lineH(keyPx); val valH = lineH(valPx); val subH = lineH(subPx)
fun tileW(t: Tile) = max(max(measure(t.key, keyPx), runWidth(t.value)),
t.sub?.let { measure(it, subPx) } ?: 0f) + innerPad * 2
var normalW = 0f
for (t in tiles) if (!t.wide) normalW = max(normalW, tileW(t))
if (normalW == 0f) for (t in tiles) normalW = max(normalW, tileW(t) / 2f)
val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH
val fullW = normalW * 2 + tileGap
var x = pad; var y = pad; var col = 0
fun place(t: Tile, tx: Float, ty: Float, tw: Float) {
tileRects.add(RectF(tx, ty, tx + tw, ty + tileH))
var by = ty + innerPad - ascent(keyPx)
placeRun(tx + innerPad, by, listOf(Span(t.key, t.keyColor, keyPx)))
by = ty + innerPad + keyH + lineGap - ascent(valPx)
placeRun(tx + innerPad, by, t.value)
if (t.sub != null) {
by = ty + innerPad + keyH + lineGap + valH + lineGap - ascent(subPx)
placeRun(tx + innerPad, by, listOf(Span(t.sub, colDim, subPx)))
}
}
for (t in tiles) {
if (t.wide) {
if (col != 0) { y += tileH + tileGap; col = 0; x = pad }
place(t, pad, y, fullW)
y += tileH + tileGap; col = 0; x = pad
} else {
place(t, x, y, normalW)
col++; x += normalW + tileGap
if (col == 2) { col = 0; x = pad; y += tileH + tileGap }
}
}
if (col != 0) y += tileH + tileGap
if (showFPS && showGraph) {
graphRect = RectF(pad, y, pad + fullW, y + sp(22f))
y += sp(22f) + tileGap
}
contentW = pad + fullW + pad
contentH = y + (pad - tileGap)
addSubtleClock(pad)
return HudRow(key, Span(label, color, labelPx), values.ifEmpty { listOf(Span("—", colDim, valuePx)) })
}
private fun buildPill(s: HudMetrics.Snapshot) {
val bigPx = sp(30f); val bigUnitPx = bigPx * 0.36f; val stkPx = sp(11.5f)
val pad = sp(10f); val midGap = sp(12f); val stkLineGap = sp(3f)
private fun buildRows(s: HudMetrics.Snapshot) {
val st = size.style
val pad = sp(st.pad); val lineGap = sp(st.lineGap); val lvGap = sp(st.labelGap)
val gutter = sp(if (st.gutter > 0f) st.gutter else 14f)
val unitPx = sp(if (st.unit > 0f) st.unit else st.row * 0.62f)
val basePx = sp(if (st.sub > 0f) st.sub else st.row)
val left = ArrayList<Span>()
val generating = differs(fpsNow)
val fpsPx = if (generating) bigPx * 0.55f else bigPx
left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true)
left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx)
val stack = ArrayList<List<Span>>()
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
run {
val l = ArrayList<Span>()
if (showGPU && s.gpuPercent != null) { l += Span("GPU ${s.gpuPercent}%", colGpu, stkPx) }
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
if (l.isNotEmpty()) stack.add(l)
val keys = size.rowsIn(storedOrder).filter { switchOn(it) }
if (keys.isEmpty()) { contentW = 0f; contentH = 0f; return }
val hero = (size == DroidDeckHudSize.PILL || size == DroidDeckHudSize.MINIMAL) && keys.firstOrNull() == "showFPS"
val tiles = size == DroidDeckHudSize.TILES
val bigPx = sp(st.row); val bigUnitPx = sp(st.unit)
val heroSpans = listOf(
Span(fpsText(fpsNow), colValue, bigPx, glow = true),
Span("fps", colDim, bigUnitPx),
)
val listed = keys.filter { !hero || it != "showFPS" }.flatMap { key ->
val labelPx = if (tiles) sp(st.key) else basePx
val valuePx = if (tiles) sp(st.row) else basePx
if (key == "showPerCore" && size == DroidDeckHudSize.MEGA)
perCoreRows(s, labelPx, valuePx, unitPx)
else listOf(reading(key, s, labelPx, valuePx, unitPx))
}
if (showRAM) stack.add(listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, stkPx)))
if (showBattery || showPower || showBatteryTemp) {
val l = ArrayList<Span>()
fun part(spans: List<Span>) {
l += if (l.isEmpty()) Span("BAT ", colBat, stkPx) else Span(" · ", colDim, stkPx)
l += spans
val maxCols = if (size == DroidDeckHudSize.MEGA) 3 else 2
val cols = when {
listed.size >= 9 -> maxCols
listed.size >= 4 -> minOf(2, maxCols)
else -> 1
}
if (tiles) {
val innerPad = sp(st.innerPad); val tileGap = sp(st.tileGap)
val keyH = lineH(sp(st.key)); val valH = lineH(sp(st.row))
val cellW = listed.maxOf { max(measure(it.label.text, it.label.sizePx), runWidth(it.vals)) } + innerPad * 2f
val graphMin = if (listed.any { it.key == "showFPSGraph" }) sp(GRAPH_MIN_WIDTH_SP) else 0f
val cellMin = graphMin + innerPad * 2f
val cellH = innerPad * 2f + keyH + lineGap + valH
for ((i, r) in listed.withIndex()) {
val x = pad + (i % cols) * (cellW + tileGap)
val y = pad + (i / cols) * (cellH + tileGap)
tileRects.add(RectF(x, y, x + cellW, y + cellH))
if (r.key == "showFPSGraph") {
graphRect = RectF(x + innerPad, y + innerPad, x + max(cellW, cellMin) - innerPad, y + cellH - innerPad)
continue
}
placeRun(x + innerPad, y + innerPad - ascent(r.label.sizePx), listOf(r.label))
placeRun(x + innerPad, y + innerPad + keyH + lineGap - ascent(sp(st.row)), r.vals)
}
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, stkPx)))
if (showBatteryTemp && s.battery.tempC != null)
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, stkPx, stkPx * 0.62f))
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, stkPx)))
if (l.isNotEmpty()) stack.add(l)
}
run {
val l = ArrayList<Span>()
l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx)
if (displayServer.isNotBlank()) { l += Span(" · ", colDim, stkPx); l += Span(displayServer, colDisp, stkPx) }
if (showVram && s.vramText() != null) { l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) }
stack.add(l)
}
if (hdrState != DroidDeckHudHdr.NONE) stack.add(hdrLine(stkPx))
var statsW = 0f
for (l in stack) statsW = max(statsW, runWidth(l))
val nameOnTop = gpuName != null && runWidth(gpuName) > statsW
if (gpuName != null && !nameOnTop) stack.add(0, gpuName)
val apiStr = apiLabel()
val hasApi = apiStr != "FPS"
val apiH = if (hasApi) lineH(stkPx) else 0f
val apiGap = if (hasApi) stkLineGap else 0f
val leftW = runWidth(left); val leftH = lineH(bigPx)
val apiW = if (hasApi) measure(apiStr, stkPx) else 0f
val leftBlockW = max(leftW, apiW)
val leftColH = apiH + apiGap + leftH
val stkH = lineH(stkPx)
var stackW = 0f
for (l in stack) stackW = max(stackW, runWidth(l))
val stackTotalH = stack.size * stkH + (stack.size - 1).coerceAtLeast(0) * stkLineGap
val innerH = max(leftColH, stackTotalH)
val topLineH = if (nameOnTop) stkH + stkLineGap else 0f
contentW = pad + leftBlockW + midGap + stackW + pad
contentH = pad + topLineH + innerH + pad
var ly = pad + topLineH + (innerH - leftColH) / 2f
if (hasApi) {
placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx)))
ly += apiH + apiGap
}
placeRun(pad, ly - ascent(bigPx), left)
var sy = pad + topLineH + (innerH - stackTotalH) / 2f
for (l in stack) {
placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l)
sy += stkH + stkLineGap
}
addSubtleClock(pad, leftAligned = true)
if (nameOnTop && gpuName != null) {
val end = placeRun(pad, pad - ascent(stkPx), gpuName)
contentW = max(contentW, end + pad)
val lines = (listed.size + cols - 1) / cols
contentW = pad + cols * (cellW + tileGap) - tileGap + pad
contentH = pad + lines * (cellH + tileGap) - tileGap + pad
} else {
val columns = (0 until cols).map { c -> listed.filterIndexed { i, _ -> i % cols == c } }
val labelW = columns.map { col -> col.maxOfOrNull { measure(it.label.text, it.label.sizePx) } ?: 0f }
val colW = columns.mapIndexed { c, col ->
val body = if (col.isEmpty()) 0f else labelW[c] + lvGap + (col.maxOfOrNull { runWidth(it.vals) } ?: 0f)
val graph = if (col.any { it.key == "showFPSGraph" }) sp(GRAPH_MIN_WIDTH_SP) + labelW[c] + lvGap else 0f
max(body, graph)
}
val gaps = (0 until cols).count { columns[it].isNotEmpty() }.coerceAtLeast(1) - 1
val bodyW = colW.sum() + gutter * gaps
var bodyH = 0f
for (col in columns) {
var y = 0f
for (r in col) y += rowHeight(r) + lineGap
if (col.isNotEmpty()) bodyH = max(bodyH, y - lineGap)
}
val heroW = if (hero) runWidth(heroSpans) else 0f
val heroH = if (hero) lineH(bigPx) else 0f
val x0 = pad + if (hero && listed.isNotEmpty()) heroW + gutter else 0f
val top = pad + (max(bodyH, heroH) - bodyH) / 2f
var x = x0
for (c in 0 until cols) {
if (columns[c].isEmpty()) continue
var y = top
for (r in columns[c]) {
if (r.key == "showFPSGraph") {
val left = x + labelW[c] + lvGap
graphRect = RectF(left, y, max(x + colW[c], left + sp(GRAPH_MIN_WIDTH_SP)), y + sp(GRAPH_HEIGHT_SP))
y += sp(GRAPH_HEIGHT_SP) + lineGap
continue
}
val px = maxOf(r.label.sizePx, r.vals.maxOfOrNull { it.sizePx } ?: 0f)
val baseline = y - ascent(px)
placeRun(x, baseline, listOf(r.label))
placeRun(x + labelW[c] + lvGap, baseline, r.vals)
y += lineH(px) + lineGap
}
x += colW[c] + gutter
}
if (hero) {
val baseline = pad + (max(bodyH, heroH) - heroH) / 2f - ascent(bigPx)
placeRun(pad, baseline, heroSpans, glow = true)
}
contentW = max(x0 + bodyW, pad + heroW) + pad
contentH = pad + max(bodyH, heroH) + pad
}
}
private fun buildMinimal(s: HudMetrics.Snapshot) {
val bigPx = sp(34f); val bigUnitPx = bigPx * 0.32f; val subPx = sp(11.5f); val footPx = sp(9.5f)
val stroke = outlineWidth()
val left = contentLeft()
val inner = panelInset() + stroke
private fun rowHeight(r: HudRow): Float =
if (r.key == "showFPSGraph") sp(GRAPH_HEIGHT_SP)
else lineH(maxOf(r.label.sizePx, r.vals.maxOfOrNull { it.sizePx } ?: 0f))
val minGenerating = differs(fpsNow)
val big = listOf(
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx))
val sub = ArrayList<Span>()
fun low(label: String, value: Float) {
if (sub.isNotEmpty()) sub += Span(" · ", colDim, subPx)
sub += Span("$label ", colDim, subPx)
sub += Span(lowText(value) ?: "—", colFps, subPx)
private fun perCoreRows(s: HudMetrics.Snapshot, labelPx: Float, valuePx: Float, unitPx: Float): List<HudRow> {
val pct = s.perCorePercent
val clk = s.perCoreClockMhz
return (0 until max(pct.size, clk.size)).map { i ->
val vals = ArrayList<Span>()
vals += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", valuePx, unitPx)
vals += Span(" ", colDim, unitPx)
vals += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", valuePx, unitPx)
HudRow("showPerCore", Span("C$i", colCpu, labelPx), vals)
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer)
.filter { it.isNotBlank() }.joinToString(" · ")
val hdr = if (hdrState != DroidDeckHudHdr.NONE) hdrLine(footPx) else emptyList()
val (headerBottom, headerRight) = addPanelHeader(left, inner)
val x = headerRight
val colW = maxOf(runWidth(big), runWidth(sub), x - left,
max(measure(footerLabel, footPx), runWidth(hdr)), if (showGraph) sp(120f) else 0f)
val bigBase = headerBottom + sp(8f) + capHeight(big[0].sizePx)
placeRun(left - inkLeft(big[0].text, big[0].sizePx), bigBase, big, glow = true)
var last = bigBase
if (sub.isNotEmpty()) {
last += sp(10f) + capHeight(subPx)
placeRun(left - inkLeft(sub[0].text, subPx), last, sub)
}
if (showGraph) {
val top = last + sp(9f)
graphRect = RectF(left, top, left + colW, top + sp(24f))
last = top + sp(24f)
}
if (footerLabel.isNotBlank()) {
val base = last + sp(8f) + capHeight(footPx)
glyphs.add(Glyph(left - inkLeft(footerLabel, footPx), base, footerLabel, blend(colDim), footPx))
last = base
}
if (hdr.isNotEmpty()) {
val base = last + sp(6f) + capHeight(footPx)
placeRun(left - inkLeft(hdr[0].text, footPx), base, hdr)
last = base
}
measurePaint.textSize = footPx
val panel = RectF(panelLeft(), panelInset(), left + colW + sp(34f), last + measurePaint.fontMetrics.descent + sp(9f) + stroke)
finishPanel(panel, halfRound = true)
}
private fun buildStrip(s: HudMetrics.Snapshot) {
@@ -1046,66 +942,27 @@ class DroidDeckHudView(context: Context) : View(context) {
}
val generating = differs(fpsNow)
val fps = ArrayList<Span>()
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
fps += Span("fps", colDim, unitPx)
x = placeRun(x, baseline, fps) + groupGap
if (showGraph) {
val gw = sp(72f); val gh = h * 0.55f
if (x + gw <= right) {
for (key in size.rowsIn(storedOrder)) {
if (!switchOn(key)) continue
if (key == "showFPSGraph") {
val gw = sp(72f); val gh = h * 0.55f
if (x + gw > right) break
graphRect = RectF(x, mid - gh / 2f, x + gw, mid + gh / 2f)
x += gw + groupGap
continue
}
}
val groups = ArrayList<List<Span>>()
run {
val l = ArrayList<Span>()
fun low(label: String, value: Float) {
if (l.isNotEmpty()) l += Span(" ", colDim, rowPx)
l += Span("$label ", colDim, rowPx)
l += Span(lowText(value) ?: "—", colFps, rowPx)
val spans = if (key == "showFPS") {
val fps = ArrayList<Span>()
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
fps += Span("fps", colDim, unitPx)
fps
} else {
val row = reading(key, s, rowPx, rowPx, unitPx)
listOf(row.label, Span(" ", colDim, rowPx)) + row.vals
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
if (l.isNotEmpty()) groups += l
}
if (showGPU || showGpuTemp) {
val l = arrayListOf(Span("GPU", colGpu, rowPx))
if (showGPU) l += Span(" ${s.gpuPercent ?: "—"}%", colGpu, rowPx)
if (showGpuTemp && s.gpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx) }
groups += l
}
if (showCPU || showCpuTemp) {
val l = arrayListOf(Span("CPU", colCpu, rowPx))
if (showCPU) l += Span(" ${s.cpuPercent ?: "—"}%", colCpu, rowPx)
if (showCpuTemp && s.cpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx) }
groups += l
}
if (showVram) s.vramText()?.let { groups += listOf(Span("VRAM $it", colVram, rowPx)) }
if (showRAM) groups += listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, rowPx))
if (showBattery || showPower || showBatteryTemp) {
val l = ArrayList<Span>()
fun part(spans: List<Span>) {
l += if (l.isEmpty()) Span("BAT ", colBat, rowPx) else Span(" ", colDim, rowPx)
l += spans
}
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, rowPx)))
if (showBatteryTemp && s.battery.tempC != null)
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx))
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, rowPx)))
if (l.isNotEmpty()) groups += l
}
if (displayServer.isNotBlank()) groups += listOf(Span(displayServer, colDisp, rowPx))
if (hdrState != DroidDeckHudHdr.NONE) groups += hdrLine(rowPx)
if (showGpuModel && gpuNameText().isNotBlank()) groups += gpuModelSpans(rowPx, colDim, compact = true)
for (g in groups) {
if (x + runWidth(g) > right) break
x = placeRun(x, baseline, g) + groupGap
if (x + runWidth(spans) > right) break
x = placeRun(x, baseline, spans) + groupGap
}
stripRect = RectF(0f, 0f, w, h)
@@ -1125,168 +982,6 @@ class DroidDeckHudView(context: Context) : View(context) {
return inkRect.left.toFloat()
}
private fun layoutColumn(rows: List<HudRow>, x: Float, y0: Float,
rowPx: Float, lineGap: Float, lvGap: Float): Pair<Float, Float> {
if (rows.isEmpty()) return Pair(y0, x)
var labelCol = 0f
for (r in rows) if (!r.inline) labelCol = max(labelCol, measure(r.label.text, rowPx))
val h = lineH(rowPx); val asc = ascent(rowPx)
var y = y0; var right = x
for (r in rows) {
val baseline = y - asc
placeRun(x, baseline, listOf(r.label))
val valX = if (r.inline) x + measure(r.label.text, rowPx) + lvGap
else x + labelCol + lvGap
val end = placeRun(valX, baseline, r.vals)
right = max(right, end)
y += h + lineGap
}
return Pair(y - lineGap, right)
}
private fun layoutWrap(fragments: List<List<Span>>, x: Float, y0: Float, maxWidth: Float,
px: Float, lineGap: Float): Pair<Float, Float> {
if (fragments.isEmpty()) return Pair(y0, x)
val h = lineH(px); val asc = ascent(px)
val sepW = measure(" · ", px)
var cx = x; var y = y0; var right = x; var firstOnLine = true
for (frag in fragments) {
val w = runWidth(frag)
if (!firstOnLine && (cx + sepW + w - x) > maxWidth) { y += h + lineGap; cx = x; firstOnLine = true }
if (!firstOnLine) { placeRun(cx, y - asc, listOf(Span(" · ", colDim, px))); cx += sepW }
val end = placeRun(cx, y - asc, frag)
cx = end; right = max(right, end); firstOnLine = false
}
return Pair(y + h, right)
}
private fun buildMega(s: HudMetrics.Snapshot) {
val rowPx = sp(11.5f); val unitPx = rowPx * 0.62f; val bandPx = sp(9.5f)
val pad = sp(10f); val lineGap = sp(3.5f); val lvGap = sp(7f); val gutter = sp(16f)
val left = ArrayList<HudRow>()
if (showGpuModel && gpuNameText().isNotBlank())
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
if (showGPU && hasGpuStats(s)) {
val v = ArrayList<Span>()
v += numUnit(s.gpuPercent?.toString(), "%", rowPx, unitPx)
if (showGpuTemp) tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
v += gap(unitPx); v += numUnit(s.gpuClockMhz?.toString(), "MHz", rowPx, unitPx)
left.add(HudRow(Span("GPU", colGpu, rowPx), v))
}
if (showCPU) {
val v = ArrayList<Span>()
v += numUnit(s.cpuPercent?.toString(), "%", rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.cpuClockMhz?.toString(), "MHz", rowPx, unitPx)
if (showCpuTemp) tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx)
.let { if (it.isNotEmpty()) { v += gap(unitPx); v += it } }
left.add(HudRow(Span("CPU", colCpu, rowPx), v))
}
if (showPerCore) {
val pct = s.perCorePercent; val clk = s.perCoreClockMhz
val n = max(pct.size, clk.size)
for (i in 0 until n) {
val v = ArrayList<Span>()
v += numUnit(if (i < pct.size && pct[i] >= 0) pct[i].toString() else null, "%", rowPx, unitPx)
v += gap(unitPx)
v += numUnit(if (i < clk.size && clk[i] > 0) clk[i].toString() else null, "MHz", rowPx, unitPx)
left.add(HudRow(Span("C$i", colCpu, rowPx), v))
}
}
val right = ArrayList<HudRow>()
if (showVram && s.vramText() != null)
right.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
if (showRAM) {
val v = ArrayList<Span>()
v += valueUnit(s.ramUsedText(), rowPx, unitPx)
v += Span("/", colDim, unitPx); v += valueUnit(s.ramTotalText(), rowPx, unitPx)
v += gap(unitPx); v += numUnit(s.ramPercent.roundToInt().toString(), "%", rowPx, unitPx)
right.add(HudRow(Span("RAM", colRam, rowPx), v))
}
if (showSwap && s.swapUsedText() != null) {
val v = ArrayList<Span>()
v += valueUnit(s.swapUsedText()!!, rowPx, unitPx)
s.swapTotalText()?.let { v += Span("/", colDim, unitPx); v += valueUnit(it, rowPx, unitPx) }
right.add(HudRow(Span("SWP", colRam, rowPx), v))
}
if (showNet && s.netDownBps != null) {
val d = (s.netDownBps ?: 0L) / 1024L
val u = (s.netUpBps ?: 0L) / 1024L
val v = ArrayList<Span>()
v += Span("↓", colDim, unitPx); v += Span(d.toString(), colValue, rowPx)
v += Span(" ↑", colDim, unitPx); v += Span(u.toString(), colValue, rowPx)
v += Span("KB/s", colDim, unitPx)
right.add(HudRow(Span("NET", colFps, rowPx), v))
}
if (showBattery || showPower || showBatteryTemp) {
val v = ArrayList<Span>(); var any = false
if (showBattery && s.battery.percent != null) { v += numUnit(s.battery.percent.toString(), "%", rowPx, unitPx); any = true }
if (showBatteryTemp) tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx)
.let { if (it.isNotEmpty()) { if (any) v += gap(unitPx); v += it; any = true } }
if (showPower && s.battery.watts > 0f) { if (any) v += gap(unitPx); v += numUnit(fmt1(s.battery.watts), "W", rowPx, unitPx); any = true }
if (any) right.add(HudRow(Span("BAT", colBat, rowPx), v))
}
if (showFPS) {
val v = ArrayList<Span>()
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
right.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
if (showLow1)
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
if (showLow01)
right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow001)
right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
val (leftBottom, leftRight) = layoutColumn(left, pad, pad, rowPx, lineGap, lvGap)
val rightX = (if (left.isEmpty()) pad else leftRight + gutter)
val (rightBottom, rightRight) = layoutColumn(right, rightX, pad, rowPx, lineGap, lvGap)
var y = max(leftBottom, rightBottom)
var maxRight = max(leftRight, rightRight)
val band = ArrayList<List<Span>>()
if (showResolution) band.add(listOf(Span("RES ", colDim, bandPx), Span(resolutionString(), colValue, bandPx)))
if (displayServer.isNotBlank()) band.add(listOf(Span("DISP ", colDim, bandPx), Span(displayServer, colDisp, bandPx)))
if (hdrState != DroidDeckHudHdr.NONE) band.add(listOf(Span("HDR ", colDim, bandPx)) + hdrValue(bandPx))
if (showProton && wineVersion.isNotBlank()) band.add(listOf(Span(wineVersion, colVram, bandPx)))
if (showSession) band.add(listOf(Span("elapsed ", colDim, bandPx), Span(elapsedString(), colValue, bandPx)))
if (band.isNotEmpty()) {
y += sp(4f)
val (bBottom, bRight) = layoutWrap(band, pad, y, max(maxRight - pad, sp(180f)), bandPx, lineGap)
y = bBottom; maxRight = max(maxRight, bRight)
}
if (showGraph) {
y += sp(3f)
val gh = sp(22f)
val gr = max(maxRight, pad + sp(220f))
graphRect = RectF(pad, y, gr, y + gh)
maxRight = max(maxRight, gr)
y += gh
}
val dxLine = dxVersionLabeled()
val hasDx = showDxVer && dxLine.isNotBlank()
if (hasDx) {
y += sp(4f)
maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(dxLine, colDim, bandPx))))
y += lineH(bandPx)
}
if (showWrapper && graphicsWrapper.isNotBlank()) {
y += if (hasDx) sp(1f) else sp(4f)
maxRight = max(maxRight, placeRun(pad, y - ascent(bandPx), listOf(Span(graphicsWrapper, colDim, bandPx))))
y += lineH(bandPx)
}
contentW = maxRight + pad
contentH = y + pad
addSubtleClock(pad)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
setMeasuredDimension(
@@ -1567,6 +1262,8 @@ class DroidDeckHudView(context: Context) : View(context) {
const val MIN_SCALE = 0.5f
const val MAX_SCALE = 2f
const val GRAPH_CLIP_MS = 49.9f
const val GRAPH_HEIGHT_SP = 22f
const val GRAPH_MIN_WIDTH_SP = 160f
fun parseIntOr(s: String?, d: Int): Int = try { s?.trim()?.toInt() ?: d } catch (e: Exception) { d }
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.hud
import java.io.File
import java.io.RandomAccessFile
import kotlin.math.roundToInt
internal class FrameStats {
@@ -159,7 +160,11 @@ internal class FrameStats {
}
}
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
internal class GameFrameFeed(
private val file: File,
val stats: FrameStats = FrameStats(),
private val clockControl: File? = null,
) {
private var handle = 0L
private var nextOpenNs = 0L
private var lastRingFrameNs = 0L
@@ -171,6 +176,8 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
private var lastCompositorNs = 0L
@Volatile private var compositorFrames = 0L
private var seenCompositorFrames = 0L
private var clockShiftNs = 0L
private var clockShiftReadNs = Long.MIN_VALUE
@Volatile var engine = ""
private set
@@ -199,6 +206,9 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
}
val n = HudFrames.nativePoll(handle, frametimes, times)
if (n > 0) {
var shift = guestClockShift(nowNs, SHIFT_NS)
if (nowNs - (times[n - 1] + shift) > LIVE_NS) shift = guestClockShift(nowNs, SHIFT_RECHECK_NS)
for (i in 0 until n) times[i] += shift
if (!fromGamescope) {
stats.reset()
fromGamescope = true
@@ -216,6 +226,16 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
return n > 0 || compositorAdded
}
internal fun guestClockShift(nowNs: Long, maxAgeNs: Long): Long {
val control = clockControl ?: return 0L
if (clockShiftReadNs != Long.MIN_VALUE && nowNs - clockShiftReadNs < maxAgeNs) return clockShiftNs
clockShiftReadNs = nowNs
clockShiftNs = runCatching {
RandomAccessFile(control, "r").use { if (it.length() < Long.SIZE_BYTES) 0L else java.lang.Long.reverseBytes(it.readLong()) }
}.getOrDefault(0L).coerceAtLeast(0L)
return clockShiftNs
}
fun onCompositorFrame(nowNs: Long) {
if (fromGamescope) {
lastCompositorNs = 0L
@@ -253,6 +273,11 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
private const val LIVE_NS = 2_000_000_000L
private const val STALE_NS = 5_000_000_000L
private const val INFO_NS = 500_000_000L
private const val SHIFT_NS = 1_000_000_000L
private const val SHIFT_RECHECK_NS = 100_000_000L
private const val CLOCK_CONTROL_PATH = "tmp/.bl-clock"
fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH))
fun engineLabel(name: String): String = when (name) {
"DXVK" -> "DXVK"
@@ -50,6 +50,7 @@ public class HudLockController {
private final Callbacks cb;
private final GestureDetector detector;
private final ScaleGestureDetector scaleDetector;
private final android.view.VelocityTracker velocity = android.view.VelocityTracker.obtain();
private boolean locked = false;
@@ -86,8 +87,18 @@ public class HudLockController {
public boolean onTouchEvent(MotionEvent event) {
scaleDetector.onTouchEvent(event);
detector.onTouchEvent(event);
// The HUD moves under the finger, so the throw is measured on the screen, not in the HUD.
MotionEvent onScreen = MotionEvent.obtain(event);
onScreen.setLocation(event.getRawX(), event.getRawY());
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) velocity.clear();
velocity.addMovement(onScreen);
onScreen.recycle();
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
if (dragging && !locked && !pinched && action == MotionEvent.ACTION_UP) {
velocity.computeCurrentVelocity(1000);
cb.onFlung(velocity.getXVelocity(), velocity.getYVelocity());
}
if (dragging && !locked) cb.onMoved(view.getX(), view.getY());
dragging = false;
}
@@ -124,12 +135,6 @@ public class HudLockController {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (dragging && !locked && !pinched) cb.onFlung(velocityX, velocityY);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (pinched) return true;
@@ -14,6 +14,8 @@
package com.droiddeck.launcher.hud;
import com.droiddeck.launcher.session.BatteryRuntimeEstimator;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
@@ -560,10 +562,9 @@ public class HudMetrics {
return sawSignal;
}
private Double smoothedBatteryRuntimeHours = null;
private static final double MAX_RUNTIME_HOURS = 72.0;
private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65;
private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35;
private final BatteryRuntimeEstimator batteryRuntimeEstimator = new BatteryRuntimeEstimator();
private Boolean lastBatteryDischarging = null;
private Boolean lastBatteryCharging = null;
public Battery collectBattery() {
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
@@ -581,11 +582,22 @@ public class HudMetrics {
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
boolean discharging = st == BatteryManager.BATTERY_STATUS_DISCHARGING
|| st == BatteryManager.BATTERY_STATUS_NOT_CHARGING;
if (lastBatteryDischarging != null && lastBatteryDischarging.booleanValue() != discharging) {
batteryRuntimeEstimator.reset();
}
lastBatteryDischarging = discharging;
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
Boolean sysCharging = readChargingFromPowerSupply();
if (sysCharging != null) charging = sysCharging;
}
long currentMicroAmps = Math.abs(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
if (lastBatteryCharging != null
&& lastBatteryCharging.booleanValue() != charging) {
batteryRuntimeEstimator.reset();
}
lastBatteryCharging = charging;
long currentMicroAmps = BatteryRuntimeEstimator.toMicroamps(bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
long chargeCounter = bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
int voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
@@ -606,36 +618,16 @@ public class HudMetrics {
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
}
Double runtimeHours = !charging
? batteryRuntimeEstimator.estimateHours(chargeCounter, Math.abs((double) currentMicroAmps))
: null;
String runtimeText;
if (charging) {
smoothedBatteryRuntimeHours = null;
runtimeText = "LEFT CHG";
} else if (currentMicroAmps <= 0L || chargeCounter <= 0L) {
runtimeText = null;
} else {
double rawHours = (double) chargeCounter / (double) currentMicroAmps;
if (!Double.isFinite(rawHours) || rawHours <= 0.0 || rawHours > MAX_RUNTIME_HOURS) {
runtimeText = null;
} else {
double smoothed = smoothedBatteryRuntimeHours == null ? rawHours
: (smoothedBatteryRuntimeHours * RUNTIME_SMOOTHING_OLD_WEIGHT)
+ (rawHours * RUNTIME_SMOOTHING_NEW_WEIGHT);
smoothedBatteryRuntimeHours = smoothed;
runtimeText = "LEFT " + formatRuntimeHours(smoothed);
}
}
if (st == BatteryManager.BATTERY_STATUS_FULL || (percent != null && percent >= 100)) runtimeText = "Full";
else if (charging) runtimeText = "Charging";
else runtimeText = BatteryRuntimeEstimator.formatDuration(runtimeHours);
return new Battery(watts, charging, percent, tempC, runtimeText);
}
private static String formatRuntimeHours(double hours) {
int totalMinutes = Math.max(1, (int) Math.round(hours * 60.0));
int wholeHours = totalMinutes / 60;
int minutes = totalMinutes % 60;
if (wholeHours > 0 && minutes > 0) return wholeHours + "h " + minutes + "m";
if (wholeHours > 0) return wholeHours + "h";
return minutes + "m";
}
private static float currentRawToAmps(long raw) {
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
long a = Math.abs(raw);
@@ -651,15 +643,10 @@ public class HudMetrics {
return currentRawToAmps(raw);
}
public Integer getCpuClockMhz() {
int cores = Runtime.getRuntime().availableProcessors();
long maxKhz = 0;
for (int i = 0; i < cores; i++) {
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
if (cur != null && cur > maxKhz) maxKhz = cur;
}
if (maxKhz <= 0) return null;
return (int) (maxKhz / 1000L);
static Integer fastestCoreMhz(int[] perCoreMhz) {
int max = 0;
for (int mhz : perCoreMhz) max = Math.max(max, mhz);
return max > 0 ? max : null;
}
private List<String> gpuClockPathsCache = null;
@@ -809,7 +796,8 @@ public class HudMetrics {
if (mango != null) return mangoSnapshot(mango);
Integer cpu = getCpuUsagePercent();
Integer gpu = getGpuUsagePercent();
Integer cpuClk = getCpuClockMhz();
int[] perCoreClk = getPerCoreClockMhz();
Integer cpuClk = fastestCoreMhz(perCoreClk);
Integer gpuClk = getGpuClockMhz();
Integer cpuTemp = getCpuTempC();
Integer gpuTemp = getGpuTempC();
@@ -829,7 +817,6 @@ public class HudMetrics {
Battery battery = collectBattery();
int[] perCorePct = readPerCorePercent();
int[] perCoreClk = getPerCoreClockMhz();
long[] swap = getSwapBytes();
long[] net = readNetRateBps();
@@ -848,26 +835,65 @@ public class HudMetrics {
Battery android = collectBattery();
MangoReadings.Battery bat = m.battery();
Battery battery = bat == null ? android : new Battery(bat.getWatts(), bat.getCharging(),
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, android.runtimeText);
bat.getPercent() != null ? bat.getPercent() : android.percent, android.tempC, bat.getRuntimeText());
long[] net = readNetRateBps();
return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), getCpuClockMhz(), m.gpuClockMhz(),
int[] perCoreClk = getPerCoreClockMhz();
return new Snapshot(cpu != null ? cpu.getPercent() : null, m.gpuPercent(), fastestCoreMhz(perCoreClk), m.gpuClockMhz(),
m.cpuTempC(), m.gpuTempC(), used, total, total > 0 ? used * 100f / total : 0f, m.vramBytes(), battery,
cpu != null ? cpu.getPerCore() : new int[0], getPerCoreClockMhz(),
cpu != null ? cpu.getPerCore() : new int[0], perCoreClk,
mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapUsedBytes() : null,
mem != null && mem.getSwapTotalBytes() > 0 ? mem.getSwapTotalBytes() : null,
net == null ? null : net[0], net == null ? null : net[1]);
}
public int[] getPerCoreClockMhz() {
private final java.util.Map<Integer, long[][]> lastTimeInState = new java.util.HashMap<>();
public synchronized int[] getPerCoreClockMhz() {
int cores = Runtime.getRuntime().availableProcessors();
int[] out = new int[Math.max(0, cores)];
for (int i = 0; i < out.length; i++) {
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
out[i] = (cur != null && cur > 0) ? (int) (cur / 1000L) : 0;
long[][] table = readTimeInState("/sys/devices/system/cpu/cpu" + i + "/cpufreq/stats/time_in_state");
long khz = table == null ? -1L : averageKhz(lastTimeInState.put(i, table), table);
if (khz <= 0L) {
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
khz = cur != null ? cur : 0L;
}
out[i] = khz > 0L ? (int) (khz / 1000L) : 0;
}
return out;
}
static long averageKhz(long[][] before, long[][] after) {
if (before == null || after == null || !java.util.Arrays.equals(before[0], after[0])) return -1L;
long weighted = 0L, time = 0L;
for (int i = 0; i < after[0].length; i++) {
long dt = after[1][i] - before[1][i];
if (dt <= 0L) continue;
weighted += after[0][i] * dt;
time += dt;
}
return time > 0L ? weighted / time : -1L;
}
private static long[][] readTimeInState(String path) {
List<long[]> rows = new ArrayList<>();
try (BufferedReader r = new BufferedReader(new FileReader(path))) {
String line;
while ((line = r.readLine()) != null) {
String[] parts = line.trim().split("\\s+");
if (parts.length < 2) continue;
try { rows.add(new long[] { Long.parseLong(parts[0]), Long.parseLong(parts[1]) }); }
catch (NumberFormatException ignored) {}
}
} catch (Exception e) {
return null;
}
if (rows.isEmpty()) return null;
long[][] table = new long[2][rows.size()];
for (int i = 0; i < rows.size(); i++) { table[0][i] = rows.get(i)[0]; table[1][i] = rows.get(i)[1]; }
return table;
}
private long[] lastCoreTotal = null;
private long[] lastCoreIdle = null;
private static final int PER_CORE_STAT = 1, PER_CORE_ESTIMATE = 2;
@@ -2,13 +2,18 @@ package com.droiddeck.launcher.hud
import android.os.Environment
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.BatteryRuntimeEstimator
import java.io.File
import kotlin.math.abs
import kotlin.math.roundToInt
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
class Battery(val percent: Int?, val watts: Float, val charging: Boolean)
class Battery(val percent: Int?, val watts: Float, val charging: Boolean, val runtimeText: String?)
private val batteryRuntimeEstimator = BatteryRuntimeEstimator()
private var lastBatteryDischarging: Boolean? = null
private val cpuTimes = HashMap<String, LongArray>()
private val cpuPercents = HashMap<String, Int>()
@@ -106,32 +111,113 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }?.take(2)
if (dirs.isNullOrEmpty()) return null
var chargeNow = 0f
var chargeFull = 0f
var watts = 0f
var charging = false
var weightedChargeNow = 0.0
var weightedChargeFull = 0.0
var allHaveWeightedCharge = true
val perBatteryPercents = ArrayList<Int>()
var runtimeChargeUah = 0.0
var runtimeChargeComplete = true
var aggregateCurrentUa = 0.0
var currentComplete = true
var watts = 0.0
var anyDischarging = false
var anyChargingStatus = false
var allFull = true
var suppliedRuntimeSeconds: Long? = null
for (dir in dirs) {
val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull()
if (status == "Charging" || status == "Unknown" || status == "Full") charging = true
val now = File(dir, "charge_now").takeIf { it.exists() } ?: File(dir, "energy_now")
val full = File(dir, "charge_full").takeIf { it.exists() } ?: File(dir, "energy_full")
if (now.exists()) {
chargeNow += (readFloat(now) ?: 0f) / 1_000_000f
chargeFull += (readFloat(full) ?: 0f) / 1_000_000f
} else {
chargeNow += (readFloat(File(dir, "capacity")) ?: 0f) / 100f
chargeFull = dirs.size.toFloat()
val isDischarging = status == "Discharging" || status == "Not charging"
if (isDischarging) anyDischarging = true
if (status == "Charging" || status == "Unknown") anyChargingStatus = true
if (status != "Full") allFull = false
val chargeNowFile = File(dir, "charge_now")
val chargeFullFile = File(dir, "charge_full")
val energyNowFile = File(dir, "energy_now")
val energyFullFile = File(dir, "energy_full")
val voltageFile = File(dir, "voltage_now")
val chargeNow = if (chargeNowFile.isFile) readFloat(chargeNowFile)?.toDouble() else null
val chargeFull = if (chargeFullFile.isFile) readFloat(chargeFullFile)?.toDouble() else null
val energyNow = if (energyNowFile.isFile) readFloat(energyNowFile)?.toDouble() else null
val energyFull = if (energyFullFile.isFile) readFloat(energyFullFile)?.toDouble() else null
val voltageUv = if (voltageFile.isFile) readFloat(voltageFile)?.toDouble() else null
val nowForPercent: Double? = when {
chargeNow != null && chargeNow >= 0.0 -> chargeNow
energyNow != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)
else -> null
}
if (!charging) {
val power = File(dir, "power_now")
watts += if (power.exists()) kotlin.math.abs(readFloat(power) ?: 0f) / 1_000_000f
else kotlin.math.abs((readFloat(File(dir, "current_now")) ?: 0f) * (readFloat(File(dir, "voltage_now")) ?: 0f)) / 1e12f
val fullForPercent: Double? = when {
chargeFull != null && chargeFull > 0.0 -> chargeFull
energyFull != null && voltageUv != null -> BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyFull, voltageUv)
else -> null
}
if (nowForPercent != null && fullForPercent != null && fullForPercent > 0.0) {
weightedChargeNow += nowForPercent
weightedChargeFull += fullForPercent
perBatteryPercents += (nowForPercent * 100.0 / fullForPercent).roundToInt().coerceIn(0, 100)
} else {
allHaveWeightedCharge = false
readFloat(File(dir, "capacity"))?.roundToInt()?.coerceIn(0, 100)?.let { perBatteryPercents += it }
}
when {
chargeNow != null && chargeNow >= 0.0 -> runtimeChargeUah += chargeNow
energyNow != null && voltageUv != null ->
BatteryRuntimeEstimator.chargeMicroampHoursFromEnergy(energyNow, voltageUv)?.let { runtimeChargeUah += it }
?: run { runtimeChargeComplete = false }
else -> runtimeChargeComplete = false
}
if (dirs.size == 1) {
suppliedRuntimeSeconds = readLong(File(dir, "time_to_empty_avg"))?.takeIf { it > 0L }
?: readLong(File(dir, "time_to_empty_now"))?.takeIf { it > 0L }
?: suppliedRuntimeSeconds
}
val currentFile = File(dir, "current_now")
val powerFile = File(dir, "power_now")
val currentNow = if (currentFile.isFile) readFloat(currentFile)?.toDouble() else null
val currentForEta = when {
currentNow != null -> abs(currentNow)
powerFile.isFile && voltageUv != null -> readFloat(powerFile)?.toDouble()?.let {
BatteryRuntimeEstimator.currentMicroampsFromPower(it, voltageUv)
}
else -> null
}
if (currentForEta == null) currentComplete = false else aggregateCurrentUa += currentForEta
if (isDischarging) {
val power = if (powerFile.isFile) readFloat(powerFile)?.toDouble() else null
if (power != null) watts += abs(power) / 1_000_000.0
else if (currentNow != null && voltageUv != null) watts += abs(currentNow * voltageUv) / 1_000_000_000_000.0
}
}
val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null
return Battery(percent, if (charging) 0f else watts, charging)
val percent = when {
allHaveWeightedCharge && weightedChargeFull > 0.0 -> (weightedChargeNow * 100.0 / weightedChargeFull).roundToInt().coerceIn(0, 100)
perBatteryPercents.isNotEmpty() -> perBatteryPercents.average().roundToInt().coerceIn(0, 100)
else -> null
}
if (lastBatteryDischarging != null && lastBatteryDischarging != anyDischarging) {
batteryRuntimeEstimator.reset()
}
lastBatteryDischarging = anyDischarging
val estimatedHours = if (anyDischarging && runtimeChargeComplete && currentComplete)
batteryRuntimeEstimator.estimateHours(runtimeChargeUah, aggregateCurrentUa) else null
val runtimeHours = suppliedRuntimeSeconds?.let { it / 3600.0 } ?: estimatedHours
val charging = !anyDischarging && anyChargingStatus
val runtimeText = when {
anyDischarging -> BatteryRuntimeEstimator.formatDuration(runtimeHours)
charging -> "Charging"
allFull -> "Full"
else -> null
}
return Battery(percent, if (anyDischarging) watts.toFloat() else 0f, charging, runtimeText)
}
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
@@ -56,6 +56,7 @@ public final class PadBridge {
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
private final float[][] rawSticks = new float[SLOTS][4];
private final boolean[][] keyTriggers = new boolean[SLOTS][2];
private final int[] retainedSticks = new int[SLOTS];
private final PadState effectiveState = new PadState();
private final PadState homeGuideReport = new PadState();
@@ -289,7 +290,10 @@ public final class PadBridge {
}
public static boolean isControllerKeyEvent(KeyEvent event) {
InputDevice device = event.getDevice();
return isControllerKeyEvent(event, event.getDevice());
}
static boolean isControllerKeyEvent(KeyEvent event, InputDevice device) {
if (device == null || device.isVirtual() || isSystemVirtualInputName(device.getName())) return false;
if (KeyEvent.isGamepadButton(event.getKeyCode())) {
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
@@ -314,7 +318,10 @@ public final class PadBridge {
}
public static boolean isControllerMotionEvent(MotionEvent event) {
InputDevice device = event.getDevice();
return isControllerMotionEvent(event, event.getDevice());
}
static boolean isControllerMotionEvent(MotionEvent event, InputDevice device) {
return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual()
&& !isSystemVirtualInputName(device.getName())
&& (device.supportsSource(InputDevice.SOURCE_GAMEPAD)
@@ -375,10 +382,11 @@ public final class PadBridge {
}
public synchronized boolean onKeyEvent(KeyEvent event) {
if (!isControllerKeyEvent(event) || excluded.test(event.getDeviceId())) return false;
int slot = slotFor(event.getDevice());
InputDevice device = event.getDevice();
if (!isControllerKeyEvent(event, device) || excluded.test(event.getDeviceId())) return false;
int slot = slotFor(device);
if (slot < 0) return false;
int side = JoyCon.side(event.getDevice());
int side = JoyCon.side(device);
if (side >= 0 && partners[slot] != NO_CONTROLLER && JoyCon.isRail(side, event.getScanCode())) return true;
long timing = InputTiming.begin();
PadState pad = stateFor(slot);
@@ -400,18 +408,18 @@ public final class PadBridge {
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Z:
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed);
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(device) ? DeckControls.R4 : DeckControls.L4, pressed);
break;
case KeyEvent.KEYCODE_BUTTON_C:
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.L4 : DeckControls.R4, pressed);
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(device) ? DeckControls.L4 : DeckControls.R4, pressed);
break;
case KeyEvent.KEYCODE_BUTTON_L2:
pad.leftTrigger = keyTrigger(pad.leftTrigger, pressed, event.getRepeatCount(),
analogTrigger(event.getDevice(), MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE));
analogTrigger(device, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE), keyTriggers[slot], 0);
break;
case KeyEvent.KEYCODE_BUTTON_R2:
pad.rightTrigger = keyTrigger(pad.rightTrigger, pressed, event.getRepeatCount(),
analogTrigger(event.getDevice(), MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS));
analogTrigger(device, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS), keyTriggers[slot], 1);
break;
case KeyEvent.KEYCODE_DPAD_UP: pad.up = pressed; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: pad.right = pressed; break;
@@ -419,7 +427,7 @@ public final class PadBridge {
case KeyEvent.KEYCODE_DPAD_LEFT: pad.left = pressed; break;
default: return false;
}
noteDevice(event.getDevice(), slot);
noteDevice(device, slot);
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
if (pressed) notePlayerInput();
statButtons++;
@@ -471,6 +479,7 @@ public final class PadBridge {
stateFor(slot).clear();
retainedSticks[slot] = 0;
Arrays.fill(rawSticks[slot], 0f);
Arrays.fill(keyTriggers[slot], false);
}
private void mutateState(java.util.function.Consumer<PadState> mutation) {
@@ -489,16 +498,16 @@ public final class PadBridge {
}
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isControllerMotionEvent(event) || excluded.test(event.getDeviceId())) return false;
InputDevice device = event.getDevice();
if (!isControllerMotionEvent(event, device) || excluded.test(event.getDeviceId())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
int slot = slotFor(event.getDevice());
int slot = slotFor(device);
if (slot < 0) return false;
long timing = InputTiming.begin();
PadState pad = stateFor(slot);
noteDevice(event.getDevice(), slot);
noteDevice(device, slot);
statAxes++;
scheduleStats();
InputDevice device = event.getDevice();
int side = JoyCon.side(device);
if (side >= 0) {
int[] stick = JoyCon.stickAxes(side, device, event.getSource());
@@ -515,7 +524,7 @@ public final class PadBridge {
}
float lx = event.getAxisValue(MotionEvent.AXIS_X);
float ly = event.getAxisValue(MotionEvent.AXIS_Y);
boolean wired = wiredXboxLayout(event);
boolean wired = wiredXboxLayout(device, event.getSource());
float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
retainStick(slot, JoyCon.LEFT, lx, ly);
@@ -525,11 +534,11 @@ public final class PadBridge {
float lt = 0f;
float rt = 0f;
if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) {
lt = leftTrigger(event, wired);
lt = axisTrigger(leftTrigger(event, wired), keyTriggers[slot], 0);
pad.leftTrigger = lt;
}
if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) {
rt = rightTrigger(event, wired);
rt = axisTrigger(rightTrigger(event, wired), keyTriggers[slot], 1);
pad.rightTrigger = rt;
}
if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) {
@@ -553,9 +562,27 @@ public final class PadBridge {
return true;
}
static float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog) {
if (analog || repeatCount > 0) return current;
return pressed ? 1f : 0f;
static float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog, boolean[] held, int side) {
if (repeatCount > 0) return current;
if (!analog) {
held[side] = pressed;
return pressed ? 1f : 0f;
}
if (pressed) {
if (current != 0f) return current;
held[side] = true;
return 1f;
}
if (!held[side]) return current;
held[side] = false;
return 0f;
}
static float axisTrigger(float value, boolean[] held, int side) {
if (!held[side]) return value;
if (value == 0f) return 1f;
held[side] = false;
return value;
}
static boolean analogTrigger(InputDevice device, int... axes) {
@@ -987,7 +1014,7 @@ public final class PadBridge {
}
private boolean isPrimary(KeyEvent event) {
int id = event.getDevice().getId();
int id = event.getDeviceId();
int first = firstPlayerSlot();
return owners[first] == id || partners[first] == id;
}
@@ -390,7 +390,8 @@ object SteamTouchConfig {
options: Options? = null,
): File? {
val dir = configDir(context) ?: return null
val source = bindings.entries.fold(config.text ?: return null) { text, (ref, change) ->
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n" else return null
val source = bindings.entries.fold(base) { text, (ref, change) ->
SteamTouchBindings.rewrite(text, ref, change) ?: text
}
val key = steamKey(context, appId)
@@ -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
}
}
@@ -0,0 +1,288 @@
package com.droiddeck.launcher.playback
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.PlaybackParameters
import androidx.media3.common.Player
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import com.droiddeck.launcher.frontend.Soundtrack
import com.google.common.util.concurrent.ListenableFuture
import java.io.File
object SoundtrackController {
var playing by mutableStateOf(false)
private set
var currentId by mutableStateOf<String?>(null)
private set
var title by mutableStateOf("")
private set
var shuffle by mutableStateOf(false)
private set
var repeat by mutableStateOf(Player.REPEAT_MODE_OFF)
private set
var durationMs by mutableStateOf(0L)
private set
var buffering by mutableStateOf(false)
private set
var volume by mutableStateOf(1f)
private set
var activeCollection by mutableStateOf<Int?>(null)
private set
var sleepEndsAt by mutableLongStateOf(0L)
private set
var sleepTrackEnd by mutableStateOf(false)
private set
private var app: Context? = null
private val removed: MutableSet<String> = java.util.Collections.synchronizedSet(HashSet())
private var activeRoot: String? = null
private var savedId: String? = null
private var future: ListenableFuture<MediaController>? = null
private var controller: MediaController? = null
private val pending = ArrayList<(MediaController) -> Unit>()
private val listener = object : Player.Listener {
override fun onEvents(player: Player, events: Player.Events) = sync(player)
}
private val disconnect = object : MediaController.Listener {
override fun onDisconnected(controller: MediaController) {
if (this@SoundtrackController.controller === controller) {
this@SoundtrackController.controller = null
future = null
reset()
}
}
}
private fun reset() {
playing = false
currentId = null
title = ""
durationMs = 0L
buffering = false
volume = 1f
activeCollection = null
}
private fun sync(player: Player) {
playing = player.isPlaying
buffering = player.playbackState == Player.STATE_BUFFERING
currentId = player.currentMediaItem?.mediaId?.takeIf { player.mediaItemCount > 0 }
title = player.mediaMetadata.title?.toString().orEmpty()
shuffle = player.shuffleModeEnabled
repeat = player.repeatMode
durationMs = player.duration.takeIf { it > 0 } ?: 0L
volume = player.volume
if (!player.playWhenReady) sleepTrackEnd = false
persistResume(player)
}
private fun persistResume(player: Player) {
val context = app ?: return
val id = currentId ?: return
if (activeCollection != null) return
val root = activeRoot ?: SoundtrackSettings.resume(context)?.root?.takeIf { id.startsWith("$it/") }?.also { activeRoot = it } ?: return
if (id != savedId || !player.isPlaying) {
savedId = id
SoundtrackSettings.saveResume(context, root, id, if (player.playbackState == Player.STATE_ENDED) 0L else player.currentPosition)
}
}
private fun applySettings(c: MediaController) {
val context = app ?: return
SoundtrackSettings.load(context)
c.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch))
c.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.skipSilence) })
sendEqualizer(c)
c.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(context)) })
}
private fun sendEqualizer(c: MediaController) {
c.sendCustomCommand(
SoundtrackService.EQUALIZER,
Bundle().apply {
putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.eqOn)
putIntArray(SoundtrackService.ARG_BANDS, SoundtrackSettings.bands.toIntArray())
putInt(SoundtrackService.ARG_BASS, SoundtrackSettings.bass)
},
)
}
private fun run(context: Context, block: (MediaController) -> Unit) {
app = context.applicationContext
val live = controller
if (live != null) { block(live); return }
pending += block
if (future != null) return
val app = context.applicationContext
val token = SessionToken(app, ComponentName(app, SoundtrackService::class.java))
val built = MediaController.Builder(app, token).setListener(disconnect)
.setConnectionHints(Bundle().apply { putBoolean(SoundtrackService.HINT_OWNER, true) }).buildAsync()
future = built
built.addListener({
val ready = runCatching { built.get() }.getOrNull()
if (ready == null) {
future = null
pending.clear()
return@addListener
}
controller = ready
ready.addListener(listener)
applySettings(ready)
sync(ready)
val queued = pending.toList()
pending.clear()
queued.forEach { it(ready) }
}, ContextCompat.getMainExecutor(app))
}
fun connect(context: Context) = run(context) { }
fun position(): Long = controller?.currentPosition ?: 0L
fun belongsCollection(id: Int): Boolean = activeCollection == id && currentId != null
fun belongs(root: File?): Boolean {
if (activeCollection != null) return false
val id = currentId ?: return false
return root != null && id.startsWith(root.path + "/")
}
private fun items(album: Soundtrack.Album, albumTitle: String): List<MediaItem> {
val cover = album.cover?.let { Uri.fromFile(it) }
return album.tracks.map { t ->
MediaItem.Builder()
.setMediaId(t.file.path)
.setMediaMetadata(
MediaMetadata.Builder()
.setTitle(t.title)
.setArtist(t.artist.ifBlank { album.artist }.ifBlank { null })
.setAlbumTitle(albumTitle)
.setTrackNumber(t.number)
.setDiscNumber(t.disc.takeIf { it > 0 })
.setArtworkUri(cover)
.setIsPlayable(true)
.build(),
)
.build()
}
}
fun play(
context: Context, album: Soundtrack.Album, albumTitle: String, startId: String?, shuffled: Boolean? = null,
root: File? = null, startMs: Long = 0L, collection: Int? = null,
) {
val list = items(album, albumTitle)
if (list.isEmpty()) return
run(context) { c ->
if (root != null && root.path in removed) return@run
val start = list.indexOfFirst { it.mediaId == startId }.coerceAtLeast(0)
root?.let { activeRoot = it.path }
activeCollection = collection
c.setMediaItems(list, start, startMs)
shuffled?.let { c.shuffleModeEnabled = it }
c.prepare()
c.play()
}
}
fun allow(paths: Collection<String>) {
removed.removeAll(paths.toSet())
}
fun toggle(context: Context, album: Soundtrack.Album, albumTitle: String, root: File?, collection: Int? = null) {
run(context) { c ->
if (root != null && root.path in removed) return@run
val mine = if (collection != null) belongsCollection(collection) else belongs(root)
if (mine && c.mediaItemCount > 0) {
if (c.isPlaying) c.pause() else {
if (c.playbackState == Player.STATE_ENDED) c.seekToDefaultPosition(0)
c.play()
}
} else {
val saved = if (collection != null) null else root?.let { r -> SoundtrackSettings.resume(context)?.takeIf { it.root == r.path && album.tracks.any { t -> t.id == it.id } } }
play(context, album, albumTitle, saved?.id ?: album.tracks.firstOrNull()?.id, root = root, startMs = saved?.positionMs ?: 0L, collection = collection)
}
}
}
fun pause(context: Context) {
val live = controller
if (live != null) live.pause() else if (future != null) pending += { it.pause() }
}
fun next(context: Context) = run(context) { it.seekToNext() }
fun previous(context: Context) = run(context) { c -> if (c.currentPosition > 3000L) c.seekTo(0) else c.seekToPrevious() }
fun seekTo(context: Context, ms: Long) = run(context) { it.seekTo(ms) }
fun setShuffle(context: Context, on: Boolean) = run(context) { it.shuffleModeEnabled = on }
fun cycleRepeat(context: Context) = run(context) {
it.repeatMode = when (it.repeatMode) {
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
else -> Player.REPEAT_MODE_OFF
}
}
fun setVolume(context: Context, volume: Float) = run(context) { it.volume = volume.coerceIn(0f, 1f) }
fun setSpeed(context: Context, value: Float) {
SoundtrackSettings.load(context)
SoundtrackSettings.setSpeed(context, value)
run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) }
}
fun setPitch(context: Context, value: Float) {
SoundtrackSettings.load(context)
SoundtrackSettings.setPitch(context, value)
run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) }
}
fun setSkipSilence(context: Context, on: Boolean) {
SoundtrackSettings.load(context)
SoundtrackSettings.setSkipSilence(context, on)
run(context) { it.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) }
}
fun setEqualizer(context: Context, on: Boolean, bands: List<Int>, bass: Int) {
SoundtrackSettings.load(context)
SoundtrackSettings.setEqualizer(context, on, bands, bass)
run(context) { sendEqualizer(it) }
}
fun setIngame(context: Context, on: Boolean) {
run(context) { it.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) }
}
fun setSleep(context: Context, minutes: Int) {
sleepEndsAt = if (minutes > 0) System.currentTimeMillis() + minutes * 60_000L else 0L
sleepTrackEnd = minutes < 0
run(context) { it.sendCustomCommand(SoundtrackService.SLEEP, Bundle().apply { putInt(SoundtrackService.ARG_MINUTES, minutes) }) }
}
fun sleepRemainingMs(): Long {
val left = sleepEndsAt - System.currentTimeMillis()
if (sleepEndsAt > 0L && left <= 0L) sleepEndsAt = 0L
return left.coerceAtLeast(0L)
}
fun stopIf(context: Context, root: File?) {
root?.let { removed.add(it.path) }
if (root == null || currentId?.startsWith(root.path + "/") != true) return
run(context) { c ->
c.stop()
c.clearMediaItems()
}
}
}
@@ -0,0 +1,282 @@
package com.droiddeck.launcher.playback
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.audiofx.BassBoost
import android.media.audiofx.Equalizer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Process
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.CommandButton
import androidx.media3.session.DefaultMediaNotificationProvider
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import androidx.media3.session.SessionCommand
import androidx.media3.session.SessionResult
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Soundtrack
import com.google.common.collect.ImmutableList
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import java.io.File
private class EdgeButtonsProvider(context: Context) : DefaultMediaNotificationProvider(context) {
override fun getMediaButtons(
session: MediaSession, playerCommands: Player.Commands, customLayout: ImmutableList<CommandButton>, showPauseButton: Boolean,
): ImmutableList<CommandButton> {
val all = super.getMediaButtons(session, playerCommands, customLayout, showPauseButton)
val custom = all.filter { it.sessionCommand != null }
if (custom.size < 2) return all
return ImmutableList.builder<CommandButton>()
.add(custom.first())
.addAll(all.filter { it.sessionCommand == null })
.addAll(custom.drop(1))
.build()
}
}
class SoundtrackService : MediaSessionService() {
private var session: MediaSession? = null
private var exo: ExoPlayer? = null
private var equalizer: Equalizer? = null
private var bassBoost: BassBoost? = null
private var effectsSession = C.AUDIO_SESSION_ID_UNSET
private var eqOn = false
private var eqBands = IntArray(0)
private var eqBass = 0
private var sleepAtTrackEnd = false
private val handler = Handler(Looper.getMainLooper())
private val sleepRunnable = Runnable { session?.player?.pause() }
private val covers = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-cover").apply { isDaemon = true } }
override fun onCreate() {
super.onCreate()
val player = ExoPlayer.Builder(this)
.setAudioAttributes(mediaAttributes(), !com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(this))
.setHandleAudioBecomingNoisy(true)
.setWakeMode(androidx.media3.common.C.WAKE_MODE_LOCAL)
.build()
exo = player
val sessionIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
player.addListener(object : Player.Listener {
override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) = refreshButtons()
override fun onRepeatModeChanged(repeatMode: Int) = refreshButtons()
override fun onAudioSessionIdChanged(audioSessionId: Int) = applyEffects()
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
if (!playWhenReady) sleepAtTrackEnd = false
}
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
refreshTrackCover(mediaItem)
val ended = reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT
if (sleepAtTrackEnd && ended) {
sleepAtTrackEnd = false
player.pause()
}
}
})
session = MediaSession.Builder(this, player).setCallback(Resolver()).apply { sessionIntent?.let { setSessionActivity(it) } }.build()
setMediaNotificationProvider(EdgeButtonsProvider(this).apply { setSmallIcon(R.drawable.ic_soundtrack) })
}
private fun mediaAttributes(): AudioAttributes =
AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build()
private fun buttons(player: Player): ImmutableList<CommandButton> = ImmutableList.of(
CommandButton.Builder()
.setDisplayName(getString(R.string.soundtracks_shuffle))
.setIconResId(if (player.shuffleModeEnabled) R.drawable.ic_shuffle_on else R.drawable.ic_shuffle_off)
.setSessionCommand(SHUFFLE)
.build(),
CommandButton.Builder()
.setDisplayName(
getString(
when (player.repeatMode) {
Player.REPEAT_MODE_ALL -> R.string.soundtracks_repeat_all
Player.REPEAT_MODE_ONE -> R.string.soundtracks_repeat_one
else -> R.string.soundtracks_repeat_off
},
),
)
.setIconResId(
when (player.repeatMode) {
Player.REPEAT_MODE_ALL -> R.drawable.ic_repeat_all
Player.REPEAT_MODE_ONE -> R.drawable.ic_repeat_one
else -> R.drawable.ic_repeat_off
},
)
.setSessionCommand(REPEAT)
.build(),
)
private fun hasPinnedArt(item: MediaItem): Boolean =
item.mediaMetadata.artworkUri?.path.orEmpty().let { it.contains("/steam-art/") || it.contains("/soundtrack-art/") }
private fun refreshTrackCover(item: MediaItem?) {
val current = item ?: return
if (hasPinnedArt(current)) return
val file = File(current.mediaId)
covers.execute {
val art = Soundtrack.trackCover(this, file) ?: return@execute
handler.post {
val player = exo ?: return@post
val live = player.currentMediaItem ?: return@post
val uri = Uri.fromFile(art)
if (live.mediaId != current.mediaId || live.mediaMetadata.artworkUri == uri || hasPinnedArt(live)) return@post
player.replaceMediaItem(
player.currentMediaItemIndex,
live.buildUpon().setMediaMetadata(live.mediaMetadata.buildUpon().setArtworkUri(uri).build()).build(),
)
}
}
}
private fun releaseEffects() {
runCatching { equalizer?.release() }
runCatching { bassBoost?.release() }
equalizer = null
bassBoost = null
effectsSession = C.AUDIO_SESSION_ID_UNSET
}
private fun applyEffects() {
val id = exo?.audioSessionId ?: C.AUDIO_SESSION_ID_UNSET
if (!eqOn || id == C.AUDIO_SESSION_ID_UNSET) {
releaseEffects()
return
}
if (id != effectsSession) {
releaseEffects()
effectsSession = id
equalizer = runCatching { Equalizer(0, id) }.getOrNull()
bassBoost = runCatching { BassBoost(0, id) }.getOrNull()
}
runCatching {
equalizer?.let { eq ->
val range = eq.bandLevelRange
for (band in 0 until minOf(eq.numberOfBands.toInt(), eqBands.size)) {
eq.setBandLevel(band.toShort(), eqBands[band].coerceIn(range[0].toInt(), range[1].toInt()).toShort())
}
eq.enabled = true
}
}
runCatching {
bassBoost?.let { boost ->
if (boost.strengthSupported) boost.setStrength(eqBass.coerceIn(0, 1000).toShort())
boost.enabled = eqBass > 0
}
}
}
private fun setSleep(minutes: Int) {
handler.removeCallbacks(sleepRunnable)
sleepAtTrackEnd = false
if (minutes > 0) handler.postDelayed(sleepRunnable, minutes * 60_000L)
else if (minutes < 0) sleepAtTrackEnd = true
}
private fun refreshButtons() {
val live = session ?: return
live.setCustomLayout(buttons(live.player))
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = session
override fun onTaskRemoved(rootIntent: Intent?) {
val player = session?.player
if (player == null || !player.playWhenReady || player.mediaItemCount == 0 || player.playbackState == Player.STATE_ENDED) stopSelf()
}
override fun onDestroy() {
handler.removeCallbacks(sleepRunnable)
covers.shutdownNow()
releaseEffects()
session?.let {
it.player.release()
it.release()
}
session = null
super.onDestroy()
}
companion object {
const val HINT_OWNER = "droiddeck.owner"
private val SHUFFLE = SessionCommand("droiddeck.shuffle", Bundle.EMPTY)
private val REPEAT = SessionCommand("droiddeck.repeat", Bundle.EMPTY)
val SKIP_SILENCE = SessionCommand("droiddeck.skipsilence", Bundle.EMPTY)
val EQUALIZER = SessionCommand("droiddeck.equalizer", Bundle.EMPTY)
val SLEEP = SessionCommand("droiddeck.sleep", Bundle.EMPTY)
val INGAME = SessionCommand("droiddeck.ingame", Bundle.EMPTY)
const val ARG_ON = "on"
const val ARG_BANDS = "bands"
const val ARG_BASS = "bass"
const val ARG_MINUTES = "minutes"
}
private inner class Resolver : MediaSession.Callback {
private fun isOwner(controller: MediaSession.ControllerInfo) =
controller.uid == Process.myUid() && controller.connectionHints.getBoolean(HINT_OWNER, false)
override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult =
if (controller.uid == Process.myUid() || controller.isTrusted) {
MediaSession.ConnectionResult.AcceptedResultBuilder(session)
.setAvailableSessionCommands(
MediaSession.ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon().add(SHUFFLE).add(REPEAT).add(SKIP_SILENCE).add(EQUALIZER).add(SLEEP).add(INGAME).build(),
)
.setCustomLayout(buttons(session.player))
.build()
} else {
MediaSession.ConnectionResult.reject()
}
override fun onCustomCommand(
session: MediaSession, controller: MediaSession.ControllerInfo, customCommand: SessionCommand, args: Bundle,
): ListenableFuture<SessionResult> {
val player = session.player
when (customCommand.customAction) {
SHUFFLE.customAction -> player.shuffleModeEnabled = !player.shuffleModeEnabled
REPEAT.customAction -> player.repeatMode = when (player.repeatMode) {
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
else -> Player.REPEAT_MODE_OFF
}
SKIP_SILENCE.customAction, EQUALIZER.customAction, SLEEP.customAction, INGAME.customAction -> {
if (!isOwner(controller)) return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_PERMISSION_DENIED))
when (customCommand.customAction) {
SKIP_SILENCE.customAction -> exo?.skipSilenceEnabled = args.getBoolean(ARG_ON)
INGAME.customAction -> exo?.setAudioAttributes(mediaAttributes(), !args.getBoolean(ARG_ON))
EQUALIZER.customAction -> {
eqOn = args.getBoolean(ARG_ON)
eqBands = args.getIntArray(ARG_BANDS) ?: IntArray(0)
eqBass = args.getInt(ARG_BASS)
applyEffects()
}
else -> setSleep(args.getInt(ARG_MINUTES))
}
}
else -> return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_NOT_SUPPORTED))
}
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
}
override fun onAddMediaItems(
mediaSession: MediaSession, controller: MediaSession.ControllerInfo, mediaItems: MutableList<MediaItem>,
): ListenableFuture<MutableList<MediaItem>> {
if (!isOwner(controller)) return Futures.immediateFailedFuture(SecurityException("Only DroidDeck can queue soundtrack files"))
val resolved = mediaItems.mapNotNull { item ->
val file = File(item.mediaId)
if (Soundtrack.isAudio(file)) item.buildUpon().setUri(Uri.fromFile(file)).build() else null
}.toMutableList()
return Futures.immediateFuture(resolved)
}
}
}
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.playback
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
object SoundtrackSettings {
const val MIN_RATE = 0.5f
const val MAX_RATE = 2f
var speed by mutableFloatStateOf(1f)
private set
var pitch by mutableFloatStateOf(1f)
private set
var skipSilence by mutableStateOf(false)
private set
var eqOn by mutableStateOf(false)
private set
var bands by mutableStateOf<List<Int>>(emptyList())
private set
var bass by mutableIntStateOf(0)
private set
class Resume(val root: String, val id: String, val positionMs: Long)
private var loaded = false
private fun prefs(context: Context) = context.applicationContext.getSharedPreferences("soundtrack_settings", Context.MODE_PRIVATE)
@Synchronized
fun load(context: Context) {
if (loaded) return
loaded = true
val p = prefs(context)
speed = p.getFloat("speed", 1f).coerceIn(MIN_RATE, MAX_RATE)
pitch = p.getFloat("pitch", 1f).coerceIn(MIN_RATE, MAX_RATE)
skipSilence = p.getBoolean("skipSilence", false)
eqOn = p.getBoolean("eqOn", false)
bands = p.getString("bands", "").orEmpty().split(',').mapNotNull { it.trim().toIntOrNull() }
bass = p.getInt("bass", 0).coerceIn(0, 1000)
}
fun setSpeed(context: Context, value: Float) {
speed = value.coerceIn(MIN_RATE, MAX_RATE)
prefs(context).edit().putFloat("speed", speed).apply()
}
fun setPitch(context: Context, value: Float) {
pitch = value.coerceIn(MIN_RATE, MAX_RATE)
prefs(context).edit().putFloat("pitch", pitch).apply()
}
fun setSkipSilence(context: Context, on: Boolean) {
skipSilence = on
prefs(context).edit().putBoolean("skipSilence", on).apply()
}
fun setEqualizer(context: Context, on: Boolean, levels: List<Int>, bassStrength: Int) {
eqOn = on
bands = levels
bass = bassStrength.coerceIn(0, 1000)
prefs(context).edit().putBoolean("eqOn", on).putString("bands", levels.joinToString(",")).putInt("bass", bass).apply()
}
fun resume(context: Context): Resume? {
val p = prefs(context)
val root = p.getString("resumeRoot", null) ?: return null
val id = p.getString("resumeId", null) ?: return null
return Resume(root, id, p.getLong("resumePosition", 0L))
}
fun saveResume(context: Context, root: String, id: String, positionMs: Long) {
prefs(context).edit().putString("resumeRoot", root).putString("resumeId", id).putLong("resumePosition", positionMs.coerceAtLeast(0L)).apply()
}
}
@@ -232,11 +232,24 @@ object BattleNet {
}
internal fun hostFolder(context: Context, path: String): File? {
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
val drive = Regex("""^([A-Za-z]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
if (relative.isEmpty() || relative.split('/').any { it == ".." }) return null
return if (drive.groupValues[1].equals("c", ignoreCase = true)) File(prefix(context), "pfx/drive_c/$relative")
else com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "/$relative")
val letter = drive.groupValues[1].lowercase()
if (letter == "c") return File(prefix(context), "pfx/drive_c/$relative")
val link = File(prefix(context), "pfx/dosdevices/$letter:").toPath()
val mapped = runCatching { java.nio.file.Files.readSymbolicLink(link).toString() }.getOrNull()
val target = when {
mapped == null -> if (letter == "z") "/" else return null
mapped.startsWith("/") -> mapped
else -> {
val rootfs = LinuxRuntime.rootDir(context).toPath().toAbsolutePath().normalize()
val resolved = link.toAbsolutePath().parent.resolve(mapped).normalize()
if (!resolved.startsWith(rootfs)) return null
"/" + rootfs.relativize(resolved).joinToString("/")
}
}.trimEnd('/')
return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative")
}
private val KEY = Regex("""^\[(.+)\](?:\s+\d+)?\s*$""")
@@ -361,7 +374,7 @@ object BattleNet {
val guestPrefix = added.guestPath(context, prefix(context)) ?: return null
val crc = java.util.zip.CRC32().apply { update("\"$guestExe\"${game.name}".toByteArray()) }.value
val appId = com.droiddeck.launcher.session.SessionPrefs.addedGameAppId(context, game.folder.path, crc or 0x80000000L)
val exe = added.candidates(game.folder).firstOrNull() ?: client
val exe = added.candidates(game.folder, reuse = true).firstOrNull() ?: client
return com.droiddeck.launcher.frontend.AddedGames.Game(
game.folder, game.name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, listOf(exe),
source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = game.uid,
@@ -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()
@@ -157,9 +157,7 @@ class LinuxNetworkLinkComponent(
synchronized(lock) {
try {
file.parentFile?.mkdirs()
val staged = File(file.path + ".staged")
staged.writeText(describe(properties, capabilities))
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
replace(file, describe(properties, capabilities))
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network link", e)
}
@@ -241,9 +239,7 @@ class LinuxNetworkLinkComponent(
}
try {
val file = File(rootDir, "etc/droiddeck-network.json")
val staged = File(file.path + ".staged")
staged.writeText(state.toString())
if (!staged.renameTo(file)) throw IOException("Could not replace network state")
replace(file, state.toString())
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network state", e)
}
@@ -272,6 +268,19 @@ class LinuxNetworkLinkComponent(
return Pair(servers.sortedWith(order), gateways.sortedWith(order))
}
/**
* Writes [text] to [file] through a staged copy. The copy is synced before the rename, or a
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
*/
private fun replace(file: File, text: String) {
val staged = File(file.path + ".staged")
java.io.FileOutputStream(staged).use { out ->
out.write(text.toByteArray())
out.fd.sync()
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
}
private fun writeResolver(properties: LinkProperties?) {
val own = properties?.dnsServers.orEmpty()
.filter { !it.isLinkLocalAddress && !it.isLoopbackAddress && !it.isAnyLocalAddress }
@@ -286,9 +295,7 @@ class LinuxNetworkLinkComponent(
}
try {
val etc = File(rootDir, "etc")
val staged = File(etc, "resolv.conf.staged")
staged.writeText(text)
if (!staged.renameTo(File(etc, "resolv.conf"))) throw IOException("Could not replace resolv.conf")
replace(File(etc, "resolv.conf"), text)
val hosts = File(etc, "hosts")
if (!hosts.isFile || !hosts.readText().contains("localhost")) {
hosts.writeText("127.0.0.1 localhost\n::1 localhost\n")
@@ -139,15 +139,26 @@ public final class LinuxRuntime {
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
File externalStorage, List<String> extraBinds,
List<String> guestCommand) {
return command(context, sessionRoot, runtimeDir, externalStorage, extraBinds, guestCommand, false);
}
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
File externalStorage, List<String> extraBinds,
List<String> guestCommand, boolean fakeRoot) {
File root = rootDir(context);
List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds);
if (sessionRoot != null) lastBinds = binds;
return commandWithBinds(context, root, binds, guestCommand);
return commandWithBinds(context, root, binds, guestCommand, fakeRoot);
}
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
List<String> guestCommand) {
List<String> cmd = prootPrefix(context, root, "/root");
return commandWithBinds(context, root, binds, guestCommand, false);
}
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
List<String> guestCommand, boolean fakeRoot) {
List<String> cmd = fakeRoot ? rootPrefix(context, root, "/root") : prootPrefix(context, root, "/root");
for (String spec : binds) bind(cmd, spec);
cmd.addAll(guestCommand);
return cmd;
@@ -155,6 +166,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;
@@ -165,6 +181,12 @@ public final class LinuxRuntime {
return prootPrefix(context, root, cwd, false);
}
public static List<String> rootPrefix(Context context, File root, String cwd) {
List<String> cmd = prootPrefix(context, root, cwd, true);
cmd.add(1, "--link2symlink");
return cmd;
}
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
List<String> cmd = new ArrayList<>();
cmd.add(prootBinary(context).getPath());
@@ -306,7 +328,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;
}
@@ -70,6 +70,7 @@ public final class LinuxRuntimeInstaller {
volatile Step step = Step.OTHER;
volatile int percent = -1;
volatile boolean ok;
volatile String failure;
final boolean removal;
boolean maintenance;
Job(boolean removal, String stage) { this.removal = removal; this.stage = stage; }
@@ -78,6 +79,9 @@ public final class LinuxRuntimeInstaller {
private static final Object JOB_LOCK = new Object();
private static Job running;
private static volatile String removalError;
private static final ThreadLocal<Job> LAST_INSTALL = new ThreadLocal<>();
private static final ThreadLocal<Job> CURRENT_INSTALL = new ThreadLocal<>();
private static final ThreadLocal<String> CATALOG_ERROR = new ThreadLocal<>();
private LinuxRuntimeInstaller() {}
@@ -105,34 +109,66 @@ public final class LinuxRuntimeInstaller {
}
public static Release fetchRelease() {
String body = Downloader.downloadString(catalogUrl());
if (body == null || body.isEmpty()) return null;
return fetchRelease(catalogUrl());
}
public static String catalogError() { return CATALOG_ERROR.get(); }
static Release fetchRelease(String catalogUrl) {
CATALOG_ERROR.remove();
String body = Downloader.downloadString(catalogUrl);
if (body == null) return catalogFailed(Downloader.lastFailure());
if (body.isEmpty()) return catalogFailed("empty catalog");
try {
JSONObject json = new JSONObject(body);
String version = json.optString("version", "");
String url = json.optString("url", "");
String sha256 = json.optString("sha256", "");
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) return null;
if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) {
return catalogFailed("catalog lacks version, url or sha256");
}
return new Release(version, url, sha256, json.optLong("size", 0L));
} catch (Exception e) {
Log.w(TAG, "catalog: " + e);
return null;
return catalogFailed("invalid catalog: " + e);
}
}
private static Release catalogFailed(String reason) {
CATALOG_ERROR.set(reason);
Log.w(TAG, "catalog: " + reason);
return null;
}
private static final String USER_DATA = "root";
public static boolean install(Context context, Release release, ProgressListener listener) {
Job job;
boolean owner;
synchronized (JOB_LOCK) {
if (running != null && (running.removal || running.maintenance)) return false;
if (running != null && (running.removal || running.maintenance)) {
Job rejected = new Job(false, null);
rejected.failure = running.removal ? "Runtime busy: removal in progress" : "Runtime busy: maintenance in progress";
Log.w(TAG, rejected.failure);
LAST_INSTALL.set(rejected);
return false;
}
owner = running == null;
if (owner) { running = new Job(false, context.getString(R.string.user_apps_starting)); removalError = null; }
job = running;
if (listener != null) job.listeners.add(listener);
}
if (!owner) return join(job, listener);
if (!owner) {
Boolean ok = await(job, listener);
if (ok != null) {
LAST_INSTALL.set(job);
return ok;
}
Job interrupted = new Job(false, null);
interrupted.failure = "Runtime install interrupted while waiting for the running install";
LAST_INSTALL.set(interrupted);
return false;
}
CURRENT_INSTALL.set(job);
try {
Context app = context.getApplicationContext();
ProgressListener progress = new ProgressListener() {
@@ -156,9 +192,10 @@ public final class LinuxRuntimeInstaller {
if (job.ok && desktop) keepDesktop(app, progress);
return job.ok;
} finally {
synchronized (JOB_LOCK) {
running = null;
}
CURRENT_INSTALL.remove();
LAST_INSTALL.set(job);
synchronized (JOB_LOCK) { running = null; }
if (listener != null) job.listeners.remove(listener);
job.done.countDown();
}
}
@@ -247,6 +284,21 @@ public final class LinuxRuntimeInstaller {
public static String removalError() { return removalError; }
public static String installError() {
Job job = LAST_INSTALL.get();
return job == null ? null : job.failure;
}
private static boolean fail(String step, String detail) {
String reason = detail == null || detail.isEmpty() ? step : step + ": " + detail;
Job job = CURRENT_INSTALL.get();
if (job != null) job.failure = reason;
Log.w(TAG, reason);
return false;
}
private static final String SWAP_FAILED = "Cannot replace the previous runtime";
public static boolean hasRemovalPending(Context context) {
return removalDirectory(LinuxRuntime.rootDir(context)).exists();
}
@@ -266,13 +318,17 @@ public final class LinuxRuntimeInstaller {
}
private static boolean join(Job job, ProgressListener listener) {
return Boolean.TRUE.equals(await(job, listener));
}
private static Boolean await(Job job, ProgressListener listener) {
try {
if (listener != null) listener.onProgress(job.step, job.stage, job.percent);
job.done.await();
return job.ok;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
return null;
} finally {
if (listener != null) job.listeners.remove(listener);
}
@@ -329,8 +385,9 @@ public final class LinuxRuntimeInstaller {
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context, () -> true, packProgress(listener, downloading))
&& !SessionPrefs.allowStockProot(context))
throw new IOException("Cannot download proot");
if (!AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading))) throw new IOException("Cannot download DirectAudio");
return fail("Cannot download proot", AddonPack.PROOT.getFailure());
if (!AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading)))
return fail("Cannot download DirectAudio", AddonPack.DIRECTAUDIO.getFailure());
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
if (listener != null) {
listener.onProgress(Step.DOWNLOADING, downloading,
@@ -338,39 +395,36 @@ public final class LinuxRuntimeInstaller {
}
});
if (!ok) {
Log.w(TAG, "download failed");
keepPartial = true;
return false;
return fail("Cannot download the runtime", Downloader.lastFailure());
}
if (listener != null) listener.onProgress(Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1);
String actual = Hashes.sha256(archive);
if (!release.sha256.equalsIgnoreCase(actual)) {
Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual);
return false;
}
if (!release.sha256.equalsIgnoreCase(actual))
return fail("Runtime checksum mismatch", "wanted " + release.sha256 + ", got " + actual);
File root = LinuxRuntime.rootDir(context);
File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new");
File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old");
recoverInterruptedSwap(root, staging, old);
if (!discard(staging, null) || !staging.mkdirs()) return false;
if (!discard(staging, null) || !staging.mkdirs()) return fail("Cannot prepare " + staging.getName(), null);
if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1);
if (!extract(context, archive, staging, root, listener)) {
RuntimeFileTree.delete(staging, null);
return false;
return fail("Cannot unpack the runtime", null);
}
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
if (!discard(old, null)) {
discard(staging, null);
return false;
return fail(SWAP_FAILED, null);
}
java.util.List<String> carryPaths = root.isDirectory()
? RuntimeFileTree.existingUserPaths(root, staging) : java.util.Collections.emptyList();
if (root.isDirectory() && !root.renameTo(old)) {
RuntimeFileTree.delete(staging, null);
return false;
return fail(SWAP_FAILED, null);
}
File carryMarker = new File(staging, CARRY_MARKER);
java.util.List<String> encodedPaths = new java.util.ArrayList<>();
@@ -379,7 +433,7 @@ public final class LinuxRuntimeInstaller {
if (old.isDirectory() && !old.renameTo(root))
Log.w(TAG, "could not restore the previous runtime; retained at " + old);
discard(staging, null);
return false;
return fail(SWAP_FAILED, null);
}
java.util.List<String> carried;
@@ -396,7 +450,7 @@ public final class LinuxRuntimeInstaller {
} else {
Log.w(TAG, "incomplete rollback; retaining user data in " + staging);
}
return false;
return fail("Cannot carry user data into the new runtime", e.getMessage());
}
if (!staging.renameTo(root)) {
@@ -407,7 +461,7 @@ public final class LinuxRuntimeInstaller {
} catch (IOException e) { Log.w(TAG, "could not move all user data back after a failed swap", e); }
old.renameTo(root);
}
return false;
return fail(SWAP_FAILED, null);
}
new File(root, CARRY_MARKER).delete();
try { RuntimeFileTree.dropStaleState(root); }
@@ -415,10 +469,10 @@ public final class LinuxRuntimeInstaller {
discard(old, null);
try { com.droiddeck.launcher.session.SessionFiles.INSTANCE.stage(context, root, false); }
catch (Exception e) { Log.w(TAG, "could not stage the session files into the new runtime", e); }
return LinuxRuntime.isInstalled(context);
return LinuxRuntime.isInstalled(context) || fail("The runtime is incomplete after unpacking", null);
} catch (Exception e) {
Log.e(TAG, "install", e);
return false;
return fail("Install stopped", e.toString());
} finally {
if (!keepPartial) archive.delete();
}
@@ -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
}
Loaded 100 of 562 files, more files were not shown because too many files have changed in this diff. Show more