Compare commits

..
Author SHA1 Message Date
Kurt Himebauch 6ece38ddb8 Merge branch 'main' into feat/flatpak-support 2026-09-30 00:35:21 -04:00
xXJsonDeruloXx 9a4eeb3d06 feat: put the Flathub Store and AppImage import behind beta toggles in Setup 2026-09-30 00:08:57 -04:00
xXJsonDeruloXx 85add46809 docs: AppImage import and what x86 apps would take 2026-09-30 00:00:05 -04:00
xXJsonDeruloXx b78b06b78d fix: keep failed Flatpak extensions non-fatal, give Electron AppImages a bus, X11 and time to relaunch 2026-09-29 23:59:07 -04:00
xXJsonDeruloXx 58ec3609b6 Merge remote-tracking branch 'origin/main' into feat/flatpak-support 2026-09-29 22:59:11 -04:00
MaxsTechReview abb3f5582b Merge branch 'main' into feat/flatpak-support 2026-09-29 20:43:37 -04:00
xXJsonDeruloXx f5dfc946f2 Merge main into PR #77 2026-09-29 18:28:48 -04:00
Kurt Himebauch a38952378d Merge pull request #82 from maxjivi05/fix/droiddeck-flatpak-fix 2026-09-29 15:32:45 -04:00
maxjivi05 29dc88dce1 fix: point store commands at the current network's DNS 2026-09-29 15:23:29 -04:00
maxjivi05 56889fe2ba fix: let Flatpak create its repo where Android denies hard links 2026-09-29 15:04:07 -04:00
xXJsonDeruloXx 463291d655 fix: report failed Flatpak installs as failures and deploy runtimes that ship a resolv.conf link 2026-09-29 13:54:02 -04:00
xXJsonDeruloXx b0e02124d8 feat: import ARM64 AppImages from storage and run them from the Desktop page 2026-09-29 13:33:29 -04:00
xXJsonDeruloXx 34640e83cb fix: add Flathub without a download, log store commands, keep Electron apps on X11 under gamescope 2026-09-29 13:17:09 -04:00
MaxsTechReview 4e9cc0bb36 Merge branch 'main' into feat/flatpak-support 2026-09-29 10:50:25 -04:00
xXJsonDeruloXx 5c1b29f47a fix: fetch Flatpak's supporting libraries when the runtime lacks them 2026-09-29 09:03:44 -04:00
xXJsonDeruloXx 672b5dc74c fix: let Chromium, Electron and Firefox Flatpaks start without their own sandboxes 2026-09-29 08:57:24 -04:00
xXJsonDeruloXx 76c82ee3ff fix: keep controller focus through Store tabs and app pages; show progress per Flatpak step 2026-09-29 08:46:45 -04:00
xXJsonDeruloXx 15a541d745 test: cover the sandbox planner and store helpers; docs: explain Flatpak on DroidDeck 2026-09-29 08:39:30 -04:00
xXJsonDeruloXx fe04315461 feat: Flatpak games on the desktop, Store apps on the Desktop page, safer remove 2026-09-29 08:29:09 -04:00
xXJsonDeruloXx 4fef38e87e feat: give Flatpak apps the KGSL GPU, the controllers and a CPU LLVM can target 2026-09-29 08:18:26 -04:00
xXJsonDeruloXx c63355be6c feat: run Flatpak apps through a proot bwrap stand-in and add a Flathub store 2026-09-29 08:06:50 -04:00
186 changed files with 2053 additions and 14070 deletions

No files matched your search

+1 -4
View File
@@ -42,7 +42,4 @@ jobs:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
gh release create "${{ inputs.tag }}" --latest=false --prerelease=false --title "${{ inputs.tag }}" --notes "gamescope 3.16.29 with tools/gamescope/patches; staged by the apk over /usr/local/bin/gamescope. sha256 $(cut -d' ' -f1 gamescope.tzst.sha256)" gamescope.tzst gamescope.tzst.sha256 || gh release upload "${{ inputs.tag }}" gamescope.tzst gamescope.tzst.sha256 --clobber
# A component the apk fetches by tag, never something users install: it must not
# become the repo's Latest release or appear as a pre-release, also when re-uploaded.
gh release edit "${{ inputs.tag }}" --latest=false --prerelease=false
gh release create "${{ inputs.tag }}" --title "${{ inputs.tag }}" --notes "gamescope 3.16.29 with tools/gamescope/patches; staged by the apk over /usr/local/bin/gamescope. sha256 $(cut -d' ' -f1 gamescope.tzst.sha256)" gamescope.tzst gamescope.tzst.sha256 || gh release upload "${{ inputs.tag }}" gamescope.tzst gamescope.tzst.sha256 --clobber
+1 -4
View File
@@ -43,7 +43,4 @@ jobs:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
gh release create "${{ inputs.tag }}" --latest=false --prerelease=false --title "${{ inputs.tag }}" --notes "wlroots 0.20.2 with tools/wlroots/patches (Vulkan DMA-BUF allocator for non-DRM GPU nodes); staged by the apk at /usr/local/lib/droiddeck-wlroots for the desktop's GPU renderers. sha256 $(cut -d' ' -f1 wlroots.tzst.sha256)" wlroots.tzst wlroots.tzst.sha256 || gh release upload "${{ inputs.tag }}" wlroots.tzst wlroots.tzst.sha256 --clobber
# A component the apk fetches by tag, never something users install: it must not
# become the repo's Latest release or appear as a pre-release, also when re-uploaded.
gh release edit "${{ inputs.tag }}" --latest=false --prerelease=false
gh release create "${{ inputs.tag }}" --title "${{ inputs.tag }}" --notes "wlroots 0.20.2 with tools/wlroots/patches (Vulkan DMA-BUF allocator for non-DRM GPU nodes); staged by the apk at /usr/local/lib/droiddeck-wlroots for the desktop's GPU renderers. sha256 $(cut -d' ' -f1 wlroots.tzst.sha256)" wlroots.tzst wlroots.tzst.sha256 || gh release upload "${{ inputs.tag }}" wlroots.tzst wlroots.tzst.sha256 --clobber
+3 -29
View File
@@ -148,8 +148,6 @@ jobs:
label="${BUILD_REF} at ${BUILD_SHA:0:7}"
fi
echo "label=$label" >> "$GITHUB_OUTPUT"
echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV"
echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV"
echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY"
- name: Cache the preloads
@@ -157,7 +155,7 @@ jobs:
uses: actions/cache@v4
with:
path: app/src/main/assets/linuxfs
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
if: steps.preloads.outputs.cache-hit != 'true'
@@ -176,9 +174,6 @@ jobs:
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so"
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
done
@@ -211,13 +206,9 @@ jobs:
rm mango-pkgs/pkg.tar.zst
done
install -m644 mango-pkgs/usr/bin/mangoapp "$M/mangoapp"
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1 libtracefs.so.1; do
cp -L "mango-pkgs/usr/lib/$so" "$M/$so"
done
# Ours, not the package's: GPU memory without tracefs (tools/mangoapp/libtracefs-shim.c).
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
-o "$M/libtracefs.so.1" tools/mangoapp/libtracefs-shim.c
aarch64-linux-gnu-strip --strip-unneeded "$M/libtracefs.so.1"
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
rm -rf mango-pkgs
ls -l "$M"
@@ -381,7 +372,6 @@ jobs:
PR: ${{ github.event.pull_request.number }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
BUILD_OUTCOME: ${{ steps.build.outcome }}
SAME_REPO: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
run: |
set -uo pipefail
MARK="<!-- droiddeck-pr-build -->"
@@ -395,15 +385,7 @@ jobs:
success)
echo "### Build passed"
echo
echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key."
echo
if [ "$SAME_REPO" = true ]; then
echo "A release-signed tester build that installs over Stable or Preview is being published now and will appear in DroidDeck's **Test builds** list. Label the PR \`no-test-build\` to skip that."
else
echo "**Maintainer:** add the \`publish-test\` label to publish a release-signed tester build that installs over Stable or Preview and appears in DroidDeck's **Test builds** list. The label is removed automatically after publishing."
fi
echo
echo "Fallback: [open **PR Release Publish**]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/workflows/pr-release-publish.yml) on \`main\` and enter PR \`$PR\`."
echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key. After approval, a maintainer can run **PR Release Publish** from \`main\` to create an APK that installs over the release."
;;
failure)
echo "### ERROR: Build failed"
@@ -531,8 +513,6 @@ jobs:
notes="$(cat notes-head.md)
Signed build of $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA - in main, not yet in a DroidDeck release; for testing.
Commit: $GITHUB_SHA
VersionCode: $(sed -n 's/^ *versionCode \([0-9][0-9]*\)$/\1/p' app/build.gradle)
Each apk installs over a DroidDeck release and keeps its data. \`standard\` is the normal app; the others are the same app under another package name, installed beside it.
SHA-256:
@@ -594,9 +574,3 @@ jobs:
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
echo "Posted: $content"
catalog:
needs: announce
if: ${{ always() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && needs.announce.result != 'skipped' }}
uses: ./.github/workflows/update-catalog.yml
secrets: inherit
-49
View File
@@ -1,49 +0,0 @@
name: PR Release Cleanup
run-name: remove PR #${{ github.event.pull_request.number }}'s test build
# A merged or closed PR's test build leaves DroidDeck-CI, so the app's Updates page stops offering it
# (a merged fix is in the next Preview). pull_request_target for the publisher app's secrets; nothing
# from the PR is checked out or run.
on:
pull_request_target:
types: [ closed ]
branches: [ main ]
permissions:
contents: read
pull-requests: read
jobs:
cleanup:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
# A token of the org's "DroidDeck CI Publisher" app, as build.yml's announce job uses.
- uses: actions/create-github-app-token@v2
id: ci-token
with:
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-CI
- name: Delete the test build
env:
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
found=0
for tag in "pr-$PR_NUMBER" "pr-$PR_NUMBER.0"; do
if gh release view "$tag" -R Droid-Deck/DroidDeck-CI >/dev/null 2>&1; then
gh release delete "$tag" -R Droid-Deck/DroidDeck-CI --yes --cleanup-tag
echo "Deleted $tag"
found=1
fi
done
[ "$found" = 1 ] || echo "No test build for PR #$PR_NUMBER"
catalog:
needs: cleanup
if: ${{ always() }}
uses: ./.github/workflows/update-catalog.yml
secrets: inherit
+55 -225
View File
@@ -1,159 +1,100 @@
name: PR Release Publish
run-name: "sign PR #${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }} with the release key"
run-name: sign PR #${{ inputs.pr_number }} with the release key
on:
workflow_dispatch:
inputs:
pr_number:
description: Open pull request number
description: Open, approved pull request
required: true
type: string
pull_request_target:
types: [labeled]
branches: [main]
# A PR from a branch of this repo is signed on its own after each green build: only people who
# can push here can change it. A fork's PR waits for a maintainer's publish-test label.
workflow_run:
workflows: [Build APK]
types: [completed]
type: number
permissions:
actions: read
contents: read
issues: write
pull-requests: write
pull-requests: read
concurrency:
group: pr-release-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
group: pr-release-${{ inputs.pr_number }}
cancel-in-progress: false
jobs:
authorize:
if: >-
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') ||
(github.event_name == 'pull_request_target' && github.event.label.name == 'publish-test') ||
(github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.head_repository.full_name == github.repository &&
github.event.workflow_run.pull_requests[0] != null)
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
timeout-minutes: 45
outputs:
pr_number: ${{ steps.gate.outputs.pr_number }}
run_id: ${{ steps.gate.outputs.run_id }}
head_sha: ${{ steps.gate.outputs.head_sha }}
base_sha: ${{ steps.gate.outputs.base_sha }}
version_code: ${{ steps.gate.outputs.version_code }}
label: ${{ steps.gate.outputs.label }}
skip: ${{ steps.gate.outputs.skip }}
automatic: ${{ steps.gate.outputs.automatic }}
variants: ${{ steps.variants.outputs.list }}
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
# Every variant a main build ships, so a PR build can be tried under any of them.
- name: The packages a signed build ships as
id: variants
run: echo "list=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT"
- name: Check the requester, PR, and build
- name: Check the PR, review, and build
id: gate
env:
GH_TOKEN: ${{ github.token }}
EVENT_NAME: ${{ github.event_name }}
REQUESTER: ${{ github.actor }}
PR_NUMBER: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
BUILT_SHA: ${{ github.event.workflow_run.head_sha }}
PR_NUMBER: ${{ inputs.pr_number }}
run: |
set -euo pipefail
[[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "::error::Invalid PR number '$PR_NUMBER'"; exit 1; }
# The automatic path stands down quietly, never failing: a draft, a PR labelled
# no-test-build, or a build that a later push has already overtaken.
skip() { echo "::notice::Not publishing PR #$PR_NUMBER: $1"; echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0; }
if [ "$EVENT_NAME" = workflow_run ]; then
echo "automatic=true" >> "$GITHUB_OUTPUT"
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
[ "$(jq -r .state <<<"$pr")" = open ] || skip "it is not open"
[ "$(jq -r .draft <<<"$pr")" = false ] || skip "it is a draft"
[ "$(jq -r .base.ref <<<"$pr")" = main ] || skip "it does not target main"
[ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
[ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
fi
if [ "$EVENT_NAME" = pull_request_target ]; then
permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$REQUESTER/permission" --jq .permission)
case "$permission" in
admin|maintain|write) ;;
*) echo "::error::@$REQUESTER does not have permission to publish release-signed test builds"; exit 1 ;;
esac
fi
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null ||
{ echo "::error::PR #$PR_NUMBER must be open, ready for review, and target main"; exit 1; }
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null
head=$(jq -r '.head.sha' <<<"$pr")
base=$(jq -r '.base.sha' <<<"$pr")
# The label is often added while the PR's build is still running, or just after a push
# before it has started: wait for the latest build of the head commit to finish (a PR
# build takes about 4 minutes) rather than fail and need the label added again.
run_id=
for attempt in $(seq 1 60); do
latest=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \
--event pull_request --commit "$head" \
--json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 |
jq -c --arg head "$head" '[.[] | select(.headSha == $head)] |
sort_by([.createdAt, .attempt]) | last // empty')
if [[ -n "$latest" && $(jq -r .status <<<"$latest") == completed ]]; then
conclusion=$(jq -r .conclusion <<<"$latest")
[[ "$conclusion" == success ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
run_id=$(jq -r .databaseId <<<"$latest")
break
fi
status=not-started
[[ -z "$latest" ]] || status=$(jq -r .status <<<"$latest")
echo "Waiting for the PR build of ${head:0:7} to finish ($status)"
sleep 30
done
[[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 30 minutes'; exit 1; }
# GitHub leaves a run's pull_requests empty when its head is in a fork, so the build is
# tied to this PR by its head repository, branch and commit instead.
run_id=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \
--event pull_request --commit "$head" \
--json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 |
jq -r --arg head "$head" '[.[] | select(.headSha == $head)] |
sort_by([.createdAt, .attempt]) | last |
select(.status == "completed" and .conclusion == "success") | .databaseId // empty')
[[ -n "$run_id" ]] || { echo '::error::The latest PR build is not green'; exit 1; }
run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")
jq -e --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
jq -e --arg head "$head" --arg base "$base" --argjson number "$PR_NUMBER" '
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
.head_repository.full_name == $repo and .head_branch == $ref
' <<<"$run" >/dev/null ||
{ echo "::error::Build run $run_id is not a green build of PR #$PR_NUMBER at ${head:0:7}"; exit 1; }
any(.pull_requests[]?; .number == $number and .head.sha == $head and .base.sha == $base)
' <<<"$run" >/dev/null
approved=$(gh api --paginate --slurp \
"repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/reviews?per_page=100" |
jq -r --arg head "$head" '[.[][] | select(.commit_id == $head)] |
group_by(.user.login) | map(max_by(.id)) | .[] |
select(.state == "APPROVED") | .user.login')
maintainer_approved=false
while IFS= read -r reviewer; do
[[ -n "$reviewer" ]] || continue
permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$reviewer/permission" --jq .permission)
[[ "$permission" == write || "$permission" == admin ]] && maintainer_approved=true
done <<<"$approved"
[[ "$maintainer_approved" == true ]] || { echo '::error::A maintainer must approve this commit'; exit 1; }
sdk=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}
tools=$(find "$sdk/build-tools" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -1)
# A PR build is made from the PR merged onto main, so it must install over main's own
# build. main is what this job checked out; no release has to exist or be marked latest.
main_code=$(sed -n 's/^[[:space:]]*versionCode[[:space:]][[:space:]]*\([0-9][0-9]*\)[[:space:]]*$/\1/p' app/build.gradle)
[[ "$main_code" =~ ^[0-9]+$ ]] || { echo "::error::No numeric versionCode in main's app/build.gradle"; exit 1; }
mkdir -p "$RUNNER_TEMP/pr"
stable_tag=$(gh api repos/The412Banner/DroidDeck/releases/latest --jq .tag_name)
mkdir -p "$RUNNER_TEMP/stable" "$RUNNER_TEMP/pr"
gh release download "$stable_tag" -R The412Banner/DroidDeck \
-p "DroidDeck-$stable_tag.apk" -D "$RUNNER_TEMP/stable"
gh run download "$run_id" -R "$GITHUB_REPOSITORY" -n droiddeck-apk -D "$RUNNER_TEMP/pr"
mapfile -t apks < <(find "$RUNNER_TEMP/pr" -type f -name '*.apk')
[[ ${#apks[@]} == 1 ]] || { echo '::error::Expected one PR APK'; exit 1; }
package_line() {
"$tools/aapt" dump badging "$1" | sed -n "s/^package: name='\\([^']*\\)' versionCode='\\([^']*\\)'.*/\\1 \\2/p"
}
stable=$(package_line "$RUNNER_TEMP/stable/DroidDeck-$stable_tag.apk")
candidate=$(package_line "${apks[0]}")
[[ "$candidate" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && ${candidate##* } -ge $main_code ]] || {
echo "::error::PR package/versionCode '$candidate' cannot install over main (versionCode $main_code)"; exit 1;
[[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" =~ ^com\.droiddeck\.launcher\ [0-9]+$ &&
${candidate##* } -ge ${stable##* } ]] || {
echo "::error::PR package/versionCode '$candidate' cannot install over stable '$stable'"; exit 1;
}
current=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
jq -e --arg head "$head" --arg base "$base" '
.state == "open" and .draft == false and .base.ref == "main" and
.head.sha == $head and .base.sha == $base
' <<<"$current" >/dev/null ||
{ echo "::error::PR #$PR_NUMBER moved on while its build was checked; publish again"; exit 1; }
' <<<"$current" >/dev/null
[[ $(gh pr view "$PR_NUMBER" -R "$GITHUB_REPOSITORY" --json reviewDecision --jq .reviewDecision) == APPROVED ]] || {
echo '::error::The current PR revision still needs approval'; exit 1;
}
{
echo "pr_number=$PR_NUMBER"
echo "run_id=$run_id"
echo "head_sha=$head"
echo "base_sha=$base"
echo "version_code=${candidate##* }"
echo "label=PR.$PR_NUMBER-${head:0:7}"
} >> "$GITHUB_OUTPUT"
@@ -162,12 +103,11 @@ jobs:
uses: ./.github/workflows/sign.yml
with:
environment: signing-main
variants: ${{ needs.authorize.outputs.variants }}
variants: '["standard"]'
run_id: ${{ needs.authorize.outputs.run_id }}
label: ${{ needs.authorize.outputs.label }}
artifact: droiddeck-pr-signed
secrets: inherit
if: ${{ needs.authorize.outputs.skip != 'true' }}
publish:
needs: [authorize, sign]
@@ -175,20 +115,18 @@ jobs:
permissions:
actions: read
contents: read
issues: write
pull-requests: write
pull-requests: read
steps:
- uses: actions/download-artifact@v4
with:
pattern: droiddeck-pr-signed-*
merge-multiple: true
name: droiddeck-pr-signed-standard
path: signed
# What this build is, for the top of the release notes: the PR's title and the first
# paragraph of its description.
- name: Describe the change
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
PR_NUMBER: ${{ inputs.pr_number }}
run: |
set -euo pipefail
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
@@ -212,137 +150,29 @@ jobs:
owner: Droid-Deck
repositories: DroidDeck-CI
- name: Publish to DroidDeck-CI
id: publish
env:
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
PR_NUMBER: ${{ inputs.pr_number }}
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
BASE_SHA: ${{ needs.authorize.outputs.base_sha }}
VERSION_CODE: ${{ needs.authorize.outputs.version_code }}
LABEL: ${{ needs.authorize.outputs.label }}
run: |
set -euo pipefail
repo=Droid-Deck/DroidDeck-CI
tag="pr-$PR_NUMBER"
cat signed/SHA256SUMS-*.txt > signed/SHA256SUMS.txt
rm signed/SHA256SUMS-*.txt
apk="DroidDeck-$LABEL.apk"
sha=$(sha256sum "signed/$apk" | cut -d ' ' -f 1)
notes="$(cat notes-head.md)
Source: https://github.com/$GITHUB_REPOSITORY/pull/$PR_NUMBER
Commit: $HEAD_SHA
Base: $BASE_SHA
VersionCode: $VERSION_CODE
Each apk installs over a DroidDeck release and keeps its data. \`standard\` is the normal app; the others are the same app under another package name, installed beside it.
SHA-256:
\`\`\`
$(cat signed/SHA256SUMS.txt)
\`\`\`"
first=false
APK SHA-256: $sha"
if ! gh release view "$tag" -R "$repo" >/dev/null 2>&1; then
gh release create "$tag" -R "$repo" --target main --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
first=true
fi
echo "first=$first" >> "$GITHUB_OUTPUT"
gh release upload "$tag" signed/* -R "$repo" --clobber
gh release upload "$tag" "signed/$apk" -R "$repo" --clobber
gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
# Drop the previous build's files: anything this build did not just upload.
keep=$(cd signed && ls | jq -R . | jq -sc .)
gh api "repos/$repo/releases/tags/$tag" |
jq -r --argjson keep "$keep" '.assets[] | select(.name as $n | $keep | index($n) | not) | .id' |
jq -r --arg keep "$apk" '.assets[] | select(.name | endswith(".apk")) | select(.name != $keep) | .id' |
while IFS= read -r id; do
gh api --method DELETE "repos/$repo/releases/assets/$id" >/dev/null
done
published=$(gh release view "$tag" -R "$repo" --json tagName,assets)
jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<<"$published" >/dev/null
release="$GITHUB_SERVER_URL/$repo/releases/tag/$tag"
apk=$(cd signed && ls DroidDeck-*.apk | awk 'length(a) == 0 || length($0) < length(a) { a = $0 } END { print a }')
echo "release=$release" >> "$GITHUB_OUTPUT"
echo "apk=$GITHUB_SERVER_URL/$repo/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
- name: Whether the PR's branch is in this repo
id: same-repo
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
run: |
head_repo=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .head.repo.full_name)
echo "same=$([ "$head_repo" = "$GITHUB_REPOSITORY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
- name: Clear the publish request label
if: ${{ github.event_name == 'pull_request_target' && steps.publish.outcome == 'success' }}
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
run: |
gh api --method DELETE "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/labels/publish-test"
- name: Report the signed build on the PR
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
RELEASE: ${{ steps.publish.outputs.release }}
APK: ${{ steps.publish.outputs.apk }}
SAME_REPO: ${{ steps.same-repo.outputs.same }}
run: |
set -euo pipefail
short=${HEAD_SHA:0:7}
mark='<!-- droiddeck-pr-release -->'
if [ "$SAME_REPO" = true ]; then
NEXT='Each green build of a new push is signed and published here on its own. Label the PR `no-test-build` to stop that.'
else
NEXT='Pushes to this PR do not re-sign automatically. After a new green build, a maintainer can add the `publish-test` label again.'
fi
body=$(cat <<EOF
$mark
## Signed test build
A release-signed build of this PR at \`$short\` is ready. It installs over Stable or Preview and keeps app data.
[Download the standard APK]($APK) · [All variants and checksums]($RELEASE)
It is also available in **DroidDeck → Updates → Test builds → PR #$PR_NUMBER**.
$NEXT
EOF
)
id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --paginate \
--jq ".[] | select(.body | startswith(\"$mark\")) | .id" | head -1 || true)
if [ -n "$id" ]; then
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -f body="$body" >/dev/null
else
gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" -f body="$body" >/dev/null
fi
# Asked for (the label, a manual run): always announced. Signed on its own after a push:
# only a PR's first test build is, and later ones update its release quietly.
- name: Post to Discord
if: ${{ always() && steps.publish.outcome == 'success' && (needs.authorize.outputs.automatic != 'true' || steps.publish.outputs.first == 'true') }}
env:
WEBHOOK: ${{ secrets.DISCORD_BUILDS_WEBHOOK }}
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
RELEASE: ${{ steps.publish.outputs.release }}
APK: ${{ steps.publish.outputs.apk }}
run: |
set -euo pipefail
if [ -z "$WEBHOOK" ]; then
echo "::notice::No DISCORD_BUILDS_WEBHOOK secret; nothing posted"
exit 0
fi
short=${HEAD_SHA:0:7}
title=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .title)
what="[#$PR_NUMBER]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$PR_NUMBER): $title"
get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
content=$(printf '**New signed PR test build** \`pr-%s\` · \`%s\`\n%s\n_Not merged — for testing._\n%s' "$PR_NUMBER" "$short" "$what" "$get")
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
echo "Posted: $content"
catalog:
needs: publish
if: ${{ always() && needs.publish.result != 'skipped' }}
uses: ./.github/workflows/update-catalog.yml
secrets: inherit
-56
View File
@@ -62,59 +62,3 @@ jobs:
label: ${{ inputs.version }}
artifact: droiddeck-release
secrets: inherit
# The release is made here, from the apks this run signed, so it traces back to its Build APK run.
publish:
name: publish the release
needs: [find, sign]
runs-on: ubuntu-24.04
timeout-minutes: 10
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/download-artifact@v4
with:
pattern: droiddeck-release-*
merge-multiple: true
path: out
- name: Publish
env:
GH_TOKEN: ${{ github.token }}
VERSION: ${{ inputs.version }}
BUILD_RUN: ${{ needs.find.outputs.run_id }}
run: |
set -euo pipefail
notes="docs/releases/$VERSION.md"
[ -f "$notes" ] || { echo "::error::$notes is missing: add the release notes first"; exit 1; }
if gh release view "$VERSION" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
echo "::error::release $VERSION already exists"; exit 1
fi
# The notes' first line is the title; media paths become raw URLs at this release's tag.
title=$(sed -n '1s/^# *//p' "$notes")
[ -n "$title" ] || title="DroidDeck $VERSION"
raw="https://raw.githubusercontent.com/$GITHUB_REPOSITORY/$VERSION/docs/releases/media/"
{
sed '1{/^# /d;}' "$notes" | sed -E "s#(\]\(|src=\")media/#\1$raw#g"
echo
echo "---"
echo
echo "Built by [Build APK run $BUILD_RUN]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN) from \`$GITHUB_SHA\`, signed and published by [Release APKs run $GITHUB_RUN_ID]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID)."
} > "$RUNNER_TEMP/body.md"
( cd out && cat SHA256SUMS-*.txt | sort -k2 > SHA256SUMS.txt && rm SHA256SUMS-*.txt && cat SHA256SUMS.txt )
gh release create "$VERSION" -R "$GITHUB_REPOSITORY" out/*.apk out/SHA256SUMS.txt \
--target "$GITHUB_SHA" --title "$title" --notes-file "$RUNNER_TEMP/body.md" --latest
echo "Published [$title]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/releases/tag/$VERSION)" >> "$GITHUB_STEP_SUMMARY"
# A release made with this run's token fires no release event, so the in-app catalog is refreshed here.
catalog:
needs: publish
uses: ./.github/workflows/update-catalog.yml
permissions:
contents: read
pull-requests: read
secrets: inherit
-42
View File
@@ -1,42 +0,0 @@
name: Update app catalog
on:
workflow_call:
workflow_dispatch:
release:
types: [published, edited, deleted, unpublished]
permissions:
contents: read
pull-requests: read
concurrency:
group: update-app-catalog
cancel-in-progress: false
jobs:
catalog:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
# Always use the current trusted generator, even when a release event points at an older tag.
- uses: actions/checkout@v4
with:
ref: main
persist-credentials: false
- uses: actions/create-github-app-token@v2
id: ci-token
with:
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-CI
- name: Regenerate catalog.json
env:
SOURCE_GITHUB_TOKEN: ${{ github.token }}
CI_GITHUB_TOKEN: ${{ steps.ci-token.outputs.token }}
run: |
set -euo pipefail
python3 tools/release/update_catalog.py
+2 -8
View File
@@ -7,20 +7,14 @@
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton.
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
## Requirements and install
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; see [docs/development/flatpak.md](docs/development/flatpak.md).
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/The412Banner/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; see [docs/development/flatpak.md](docs/development/flatpak.md).
On Android 12+, if Steam exits without a log, turn off **Restrict child processes** in Developer options.
## Community
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the session folder from `Download/DroidDeck/` so the logs come with it.
## Build
Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, and `zstd` installed. It builds the ARM64 audio sinks from PulseAudio 13.0 and packages them into the APK at `app/build/outputs/apk/release/app-release.apk`. Set `DROIDDECK_PA13_SOURCE_DIR` to an existing PulseAudio 13.0 source directory to skip downloading it. To install the APK on an attached device, run `tools/deploy_local.sh`.
@@ -31,4 +25,4 @@ Compatibility and performance vary by device; hardware validation is limited. De
## Credits and licence
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
+2 -25
View File
@@ -49,22 +49,6 @@ if (!(treeState in ['clean', 'dirty'])) {
buildLabel = "${buildOrigin} ${treeState} · ${buildLabel}"
def escapedBuildLabel = buildLabel.replace('\\', '\\\\').replace('"', '\\"')
// What the in-app updater compares against the published builds: the commit this build is of (a PR
// build's head, not the merge CI makes of it), its PR, and whether CI made it at all.
def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getOrNull()
?: providers.environmentVariable('GITHUB_SHA').getOrNull() ?: gitValue(['rev-parse', 'HEAD']) ?: ''
def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' }
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
// The release key's certificate: a build signed with it, from CI or a computer, updates in place.
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
// When the source was committed, for "built 3 hours ago": fixed per commit, so it costs no rebuilds.
def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with { it.isLong() ? it : '0' }
// tools/release/variants.txt as "package=suffix;...", so the updater picks the apk of the package it runs as.
def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
.findAll { it.trim() && !it.startsWith('#') }
.collect { def f = it.trim().split(/\s+/); "${f[1]}=${f[2] == '-' ? '' : f[2]}" }
.join(';')
android {
namespace 'com.droiddeck.launcher'
compileSdk 34
@@ -79,15 +63,9 @@ android {
// file out of its own data directory, and this app's entire job is to exec a rootfs:
// proot, gamescope, the Steam client and everything it launches all live under files/.
targetSdkVersion 28
versionCode 10
versionName "0.3.0"
versionCode 9
versionName "0.2.0"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}"
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
ndk {
abiFilters 'arm64-v8a'
@@ -190,7 +168,6 @@ dependencies {
// copies on. Same versions as Bannerlator so the screen stays a straight copy.
implementation 'androidx.compose.material:material-icons-extended'
implementation 'io.coil-kt:coil-compose:2.6.0'
implementation 'com.caverock:androidsvg-aar:1.4'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
// ADB-over-Wi-Fi pairing and authenticated shell client. Users still approve pairing from
// Android's Wireless debugging screen; DroidDeck only runs its one fixed setting command.
-3
View File
@@ -22,15 +22,12 @@
relay helper opens the input stream under this uid, and PulseAudio exposes it to the
Steam client as DirectAudioMic. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Installs DroidDeck's own updates (Updates page) over itself, after the user allows it. -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
<uses-feature android:name="android.hardware.gamepad" android:required="false" />
<application
android:name=".App"
android:localeConfig="@xml/locales_config"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
+17 -195
View File
@@ -8,7 +8,6 @@
* a game become more of these nodes instead of vanishing.
*/
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <climits>
#include <cstdint>
@@ -39,9 +38,6 @@
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <time.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
@@ -299,52 +295,21 @@ static void controller_fork_child() {
namespace Logger {
int log_enabled;
// FAKE_EVDEV_LOG_FILE: the session's pad.log, shared by every process the library is loaded in
// (the client, each game), so a pad report has the guest side in one file of the session folder.
// Opened with the raw syscall: open() is this library's own hook.
static int log_fd = -1;
static char log_name[17];
void init() {
log_enabled = getenv("FAKE_EVDEV_LOG") && atoi(getenv("FAKE_EVDEV_LOG"));
const char *path = getenv("FAKE_EVDEV_LOG_FILE");
if (log_enabled && path && *path)
log_fd = static_cast<int>(syscall(SYS_openat, AT_FDCWD, path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644));
if (prctl(PR_GET_NAME, log_name) != 0) strcpy(log_name, "?");
}
void log(const char *message, ...) {
if (!log_enabled)
return;
if (log_fd < 0) {
va_list args;
va_start(args, message);
vfprintf(stderr, message, args);
va_end(args);
std::cerr.flush();
return;
}
// One write per line: O_APPEND keeps lines from different processes whole.
char line[512];
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
struct tm local;
localtime_r(&now.tv_sec, &local);
int n = snprintf(line, sizeof(line), "%02d:%02d:%02d.%03ld %d %s: ", local.tm_hour, local.tm_min,
local.tm_sec, now.tv_nsec / 1000000, getpid(), log_name);
va_list args;
va_start(args, message);
if (n > 0 && n < static_cast<int>(sizeof(line)))
n += vsnprintf(line + n, sizeof(line) - n, message, args);
vfprintf(stderr, message, args);
va_end(args);
if (n <= 0) return;
if (n >= static_cast<int>(sizeof(line))) {
n = sizeof(line) - 1;
line[n - 1] = '\n';
}
ssize_t ignored = write(log_fd, line, n);
(void)ignored;
std::cerr.flush();
}
} // namespace Logger
@@ -684,43 +649,31 @@ open_fake_input_ring(const char *event, int flags) {
// does not exist here, so the game was left with no controller at all. With
// FAKE_EVDEV_STEAM_VIRTUAL set the pad carries the virtual gamepad's identity for every process
// but the client's own, which must keep seeing the pad as the physical one it reads.
// Whether this process is the Steam client itself. Asked once: a process never becomes another.
__attribute__((visibility("hidden"))) static bool is_steam_client() {
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
static int known;
if (known == 0) {
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
char exe[PATH_MAX];
ssize_t length = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
ssize_t length = enabled && atoi(enabled) ? readlink("/proc/self/exe", exe, sizeof(exe) - 1) : -1;
bool client = false;
if (length > 0) {
exe[length] = '\0';
const char *name = strrchr(exe, '/');
client = !strncmp(name ? name + 1 : exe, "steam", 5);
}
known = client ? 1 : -1;
known = length > 0 && !client ? 1 : -1;
}
return known == 1;
}
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
static int known;
if (known == 0) {
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
// The virtual gamepad is an X-Box 360 pad, whose triggers are ABS_Z and ABS_RZ. Wine and SDL place
// a gamepad's axes by their position among the ones it advertises, so the triggers have to sit
// The virtual gamepad is an X-Box 360 pad, whose triggers are ABS_Z and ABS_RZ. Wine places a
// gamepad's axes by their position among the ones it advertises, so the triggers have to sit
// where that pad has them: as ABS_GAS and ABS_BRAKE they follow the sticks, the right stick
// lands on the left trigger, and a released right trigger reads as the right stick held up. That
// is every reader but the Steam client, which maps the pad from what it finds (controller.txt)
// and has always been shown ABS_GAS/ABS_BRAKE: a game Steam Input is off for reads this pad
// itself (the Xbox 360 setting), and so do the desktop's programs. A pad made through
// /dev/uinput is that pad for real, whoever reads it.
// lands on the left trigger, and a released right trigger reads as the right stick held up.
// A pad made through /dev/uinput is that pad for real, whoever reads it.
__attribute__((visibility("hidden"))) static bool
presents_xbox_triggers(const FakeController &fake) {
return fake.uinput || !is_steam_client();
return fake.uinput || presents_steam_virtual();
}
__attribute__((visibility("hidden"))) static uint16_t
@@ -1303,14 +1256,6 @@ __attribute__((visibility("hidden"))) static bool process_is_steam_client() {
return known == 1;
}
// What the client starts with, so a pad log says whether it was offered a Deck at all.
__attribute__((constructor)) static void log_client_start() {
config();
if (process_is_steam_client())
Logger::log("loaded in the Steam client: deck %s, ring slot 0 %s\n", fake_deck_enabled() ? "on" : "off",
get_ring_path_for_slot(0).empty() ? "(none configured)" : get_ring_path_for_slot(0).c_str());
}
__attribute__((visibility("hidden"))) static bool is_deck_hidraw_path(const char *pathname) {
return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH);
}
@@ -1419,16 +1364,12 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
if (!process_is_steam_client()) {
// Only the client reads the Deck; a game sees Steam Input's virtual pad instead.
Logger::log("deck: %s refused: not the Steam client\n", DECK_HIDRAW_PATH);
errno = ENOENT;
return -1;
}
std::string ring_path = get_ring_path_for_slot(0);
int ring_fd = ring_path.empty() ? -1 : my_open(ring_path.c_str(), O_RDONLY | O_CLOEXEC);
if (ring_fd < 0) {
Logger::log("deck: %s refused: ring %s not openable (%s)\n", DECK_HIDRAW_PATH,
ring_path.empty() ? "(none configured)" : ring_path.c_str(), strerror(errno));
errno = ENODEV;
return -1;
}
@@ -1441,15 +1382,12 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) {
void *mapping = mmap(nullptr, mapping_size, PROT_READ, MAP_SHARED, ring_fd, 0);
syscall(SYS_close, ring_fd);
if (mapping == MAP_FAILED || !ring_header_is_valid(static_cast<FakeInputRingHeader *>(mapping))) {
Logger::log("deck: %s refused: ring %s %s\n", DECK_HIDRAW_PATH, ring_path.c_str(),
mapping == MAP_FAILED ? "could not be mapped" : "has no valid header");
if (mapping != MAP_FAILED) munmap(mapping, mapping_size);
errno = ENODEV;
return -1;
}
int pair[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, pair) < 0) {
Logger::log("deck: %s refused: socketpair failed (%s)\n", DECK_HIDRAW_PATH, strerror(errno));
munmap(mapping, mapping_size);
return -1;
}
@@ -1488,18 +1426,8 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) {
// into /sys, so those paths are said to be sysfs; nothing else is touched.
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
// FAKE_DECK_SYSFS_LISTING: stand-ins for the listings of /sys, /sys/class and /sys/bus
// (SteamDeckPad.listingDir), for a client that is not allowed to list the real ones.
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
return dir && *dir ? dir : nullptr;
}
__attribute__((visibility("hidden"))) static bool is_deck_sysfs_path(const char *path) {
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));
return path && (!strncmp(path, "/sys/devices/droiddeck", 22) || !strncmp(path, "/sys/class/hidraw", 17));
}
__attribute__((visibility("hidden"))) static bool is_deck_sysfs_fd(int fd) {
@@ -1511,32 +1439,17 @@ __attribute__((visibility("hidden"))) static bool is_deck_sysfs_fd(int fd) {
return is_deck_sysfs_path(path);
}
// Once per process: proof the client's enumeration reached the Deck's sysfs at all. No line here
// and no open of /dev/hidraw16 means the client never looked; a line here and no open means it
// looked and turned the device down.
__attribute__((visibility("hidden"))) static void note_deck_sysfs(const char *how, int result) {
static std::atomic<bool> noted{false};
if (!noted.exchange(true))
Logger::log("deck: sysfs checked (%s%s)\n", how, result == 0 ? "" : ", failed");
}
EXPORT int fstatfs(int fd, struct statfs *buf) {
static auto real = reinterpret_cast<int (*)(int, struct statfs *)>(dlsym(RTLD_NEXT, "fstatfs"));
int result = real(fd, buf);
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
note_deck_sysfs("fstatfs", result);
if (result == 0) buf->f_type = SYSFS_FS_MAGIC;
}
if (result == 0 && fake_deck_enabled() && is_deck_sysfs_fd(fd)) buf->f_type = SYSFS_FS_MAGIC;
return result;
}
EXPORT int statfs(const char *path, struct statfs *buf) {
static auto real = reinterpret_cast<int (*)(const char *, struct statfs *)>(dlsym(RTLD_NEXT, "statfs"));
int result = real(path, buf);
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
note_deck_sysfs(path, result);
if (result == 0) buf->f_type = SYSFS_FS_MAGIC;
}
if (result == 0 && fake_deck_enabled() && is_deck_sysfs_path(path)) buf->f_type = SYSFS_FS_MAGIC;
return result;
}
@@ -1558,15 +1471,6 @@ __attribute__((visibility("hidden"))) static int copy_ioctl_string(ioctl_request
}
// Feature reports carry the report id (0) first, then the Valve message: type, length, payload.
// The client repeats some feature reports (settings, rumble) for as long as it has the pad; each
// is logged the first time and then at 2, 4, 8... so the log shows what it asked and how often
// without a line per report.
__attribute__((visibility("hidden"))) static void log_deck_feature(const char *what, uint8_t feature) {
static std::atomic<unsigned> counts[2][256];
unsigned n = ++counts[what[0] == 's'][feature];
if ((n & (n - 1)) == 0) Logger::log("deck: feature 0x%02x %s (x%u)\n", feature, what, n);
}
__attribute__((visibility("hidden"))) static int
deck_feature(DeckHidraw &deck, ioctl_request_t op, uint8_t *buf, bool set) {
size_t size = _IOC_SIZE(op);
@@ -1580,7 +1484,7 @@ deck_feature(DeckHidraw &deck, ioctl_request_t op, uint8_t *buf, bool set) {
int left = buf[6] | buf[7] << 8, right = buf[8] | buf[9] << 8;
send_vibration(left, right, left || right ? 1000 : 0, 0);
}
log_deck_feature("set", buf[1]);
Logger::log("deck: feature 0x%02x set\n", buf[1]);
return static_cast<int>(size);
}
uint8_t reply[DECK_REPORT_BYTES + 1] = {};
@@ -1610,7 +1514,7 @@ deck_feature(DeckHidraw &deck, ioctl_request_t op, uint8_t *buf, bool set) {
reply[1] = deck.pending_feature;
break;
}
log_deck_feature("read", deck.pending_feature);
Logger::log("deck: feature 0x%02x read\n", deck.pending_feature);
size_t length = std::min(size, sizeof(reply));
memcpy(buf, reply, length);
return static_cast<int>(length);
@@ -1654,80 +1558,6 @@ ioctl_deck(DeckHidraw &deck, ioctl_request_t op, void *argp) {
}
}
// A device scan that fails on a phone and not on the Thor: libudev gives up its whole scan on any
// sysfs directory it cannot read for a reason other than its absence, and a phone's SELinux policy
// denies directories a permissive device lets through. The client's /sys failures that are not
// ENOENT are logged, each path once, so pad.log names the directory that stopped the scan.
__attribute__((visibility("hidden"))) static std::string note_sys_failure(int dirfd, const char *pathname) {
int saved_errno = errno;
std::string path;
if (saved_errno == ENOENT || !pathname || !process_is_steam_client()) {
errno = saved_errno;
return path;
}
if (pathname[0] == '/' || dirfd == AT_FDCWD) {
path = pathname;
} else {
char link[64], dir[PATH_MAX];
snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd);
ssize_t length = readlink(link, dir, sizeof(dir) - 1);
if (length <= 0) {
errno = saved_errno;
return path;
}
path.assign(dir, length);
path += '/';
path += pathname;
}
if (path.compare(0, 5, "/sys/") != 0 && path != "/sys") {
errno = saved_errno;
return {};
}
static std::mutex mutex;
static std::vector<std::string> *seen = new std::vector<std::string>();
bool first = false;
{
std::lock_guard<std::mutex> guard(mutex);
if (seen->size() < 64 && std::find(seen->begin(), seen->end(), path) == seen->end()) {
seen->push_back(path);
first = true;
}
}
if (first) Logger::log("sysfs: %s not readable (%s)\n", path.c_str(), strerror(saved_errno));
errno = saved_errno;
return path;
}
// An enforcing SELinux policy (every retail phone; the Thor only with it forced on) refuses an app
// a listing of /sys, /sys/class and /sys/bus. libudev lists /sys/class to find the subsystems to
// descend into and gives up its whole scan when it cannot, so the client never reached hidraw and
// found no Deck. The client is listed the stand-ins instead - hidraw under class - and opens
// /sys/class/hidraw itself, which is ours and readable. Only on that refusal, only for the client.
__attribute__((visibility("hidden"))) static std::string deck_listing_for(const char *path) {
const char *listing = deck_listing_dir();
if (!path || !listing || errno != EACCES || !fake_deck_enabled() || !process_is_steam_client()) return {};
std::string p(path);
while (p.size() > 1 && p.back() == '/') p.pop_back();
int which = p == "/sys" ? 0 : p == "/sys/class" ? 1 : p == "/sys/bus" ? 2 : -1;
if (which < 0) return {};
static const char *const names[] = {"sys", "class", "bus"};
static std::atomic<int> logged{0};
if (!(logged.fetch_or(1 << which) & (1 << which)))
Logger::log("sysfs: %s listed from the Deck's stand-in\n", p.c_str());
return std::string(listing) + "/" + names[which];
}
EXPORT DIR *opendir(const char *name) {
static auto real = reinterpret_cast<DIR *(*)(const char *)>(dlsym(RTLD_NEXT, "opendir"));
DIR *dir = real(name);
if (!dir) {
note_sys_failure(AT_FDCWD, name);
std::string listing = deck_listing_for(name);
if (!listing.empty()) dir = real(listing.c_str());
}
return dir;
}
EXPORT int open(const char *pathname, int flags, ...) {
va_list va;
mode_t mode;
@@ -1791,10 +1621,6 @@ EXPORT int open(const char *pathname, int flags, ...) {
fd = my_open(pathname, flags, mode);
else
fd = my_open(pathname, flags);
if (fd < 0) {
std::string listing = deck_listing_for(note_sys_failure(AT_FDCWD, pathname).c_str());
if (!listing.empty()) fd = my_open(listing.c_str(), flags);
}
if (fake_path)
free(fake_path);
@@ -1865,10 +1691,6 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
fd = my_openat(dirfd, pathname, flags, mode);
else
fd = my_openat(dirfd, pathname, flags);
if (fd < 0) {
std::string listing = deck_listing_for(note_sys_failure(dirfd, pathname).c_str());
if (!listing.empty()) fd = my_openat(AT_FDCWD, listing.c_str(), flags);
}
if (fake_path)
free(fake_path);
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_alpha.hpp"
#include "lsfg_shaders.hpp"
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
+4 -3
View File
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_beta.hpp"
#include "lsfg_shaders.hpp"
+4 -3
View File
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_chain.hpp"
#include "lsfg_shaders.hpp"
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_common.hpp"
#include "lsfg_shaders.hpp"
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_delta.hpp"
#include "lsfg_shaders.hpp"
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
+33 -3
View File
@@ -1,9 +1,9 @@
// See lsfg_dll.h. PE resource walk + on-device SPIR-V cache for the Lossless
// Scaling frame-generation chain.
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk (PancakeTAS). Ported to WinNative (lsfg_dll.c) and DroidDeck
// by @maxjivi05. GPL-3.0-or-later.
// Derived from WinNative's lsfg_dll.c (GPL-3.0-or-later), LSFG port credited to
// Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk
// (PancakeTAS). Bannerlator is GPL-3.0.
#include "lsfg_dll.h"
#include "lsfg_dxbc.h"
@@ -478,6 +478,20 @@ DllStatus validateDll(const std::string& dllPath) {
return status;
}
Variant dllVariant(const std::string& dllPath, bool preferFp16) {
if (dllPath.empty()) return Variant::None;
PeImage img;
if (!img.open(dllPath)) return Variant::None;
ResourceTable table;
if (parseResources(img, table) != DllStatus::Ok) return Variant::None;
Variant v = selectVariant(table, preferFp16);
if (v == Variant::None && hasBaseChain(table)) v = Variant::DxbcTranslated;
return v;
}
DllStatus buildCache(const std::string& dllPath, const std::string& cachePath, bool preferFp16) {
if (dllPath.empty() || cachePath.empty()) return DllStatus::NotInstalled;
@@ -533,6 +547,22 @@ DllStatus buildCache(const std::string& dllPath, const std::string& cachePath, b
return DllStatus::Ok;
}
DllStatus cacheMatchesSource(const std::string& cachePath, const std::string& dllPath,
bool& outMatches) {
outMatches = false;
if (cachePath.empty() || dllPath.empty()) return DllStatus::CacheUnusable;
CacheHeader header{};
if (!readCacheHeader(cachePath, header)) return DllStatus::CacheUnusable;
PeImage img;
if (!img.open(dllPath)) return DllStatus::NotInstalled;
outMatches = header.sourceSize == (uint64_t)img.size()
&& header.sourceHash == fnv1a64(img.data(), img.size());
return DllStatus::Ok;
}
DllStatus cacheVariant(const std::string& cachePath, Variant& outVariant) {
outVariant = Variant::None;
CacheHeader header{};
+11 -4
View File
@@ -7,7 +7,7 @@
// ship as RCDATA resources inside Lossless.dll from the user's own paid copy
// of Lossless Scaling (Steam app 993090). Every implementation - upstream
// lsfg-vk, LSFG-Android, eden, WinNative - requires the user to supply their
// own DLL and extracts the resources on device. DroidDeck does the same, and
// own DLL and extracts the resources on device. Bannerlator does the same, and
// bundles nothing.
//
// The DLL is mmap'd READ-ONLY and parsed as data. It is never loaded as a
@@ -26,9 +26,9 @@
// Both producers fill the same shader-id -> SPIR-V words map, so everything
// downstream of this file is source-agnostic.
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk (PancakeTAS). Ported to WinNative (lsfg_dll.c) and DroidDeck
// by @maxjivi05. GPL-3.0-or-later.
// Derived from WinNative's lsfg_dll.c (GPL-3.0-or-later), whose LSFG port is
// credited to Camille LaVey / the Eden Emulator Project, and which follows
// upstream lsfg-vk (PancakeTAS). Bannerlator is GPL-3.0; see THIRD-PARTY-LICENSES.md.
// ============================================================================
#include <cstdint>
@@ -98,11 +98,18 @@ const char* variantName(Variant v);
// reported as valid - the translator handles it.
DllStatus validateDll(const std::string& dllPath);
// Which producer would be used for this DLL.
Variant dllVariant(const std::string& dllPath, bool preferFp16);
// Parse the DLL, produce all 25 SPIR-V modules, and write them to cachePath
// (via temp file + rename, so a failed build cannot leave a half-written
// cache behind). Records which producer ran in the cache header.
DllStatus buildCache(const std::string& dllPath, const std::string& cachePath, bool preferFp16);
// Is the cache current for this DLL? Compares source size + content hash.
DllStatus cacheMatchesSource(const std::string& cachePath, const std::string& dllPath,
bool& outMatches);
// Load a previously built cache.
DllStatus loadModules(const std::string& cachePath, ModuleSet& outSet);
+3 -4
View File
@@ -1,10 +1,9 @@
// See lsfg_dxbc.h. DXBC -> SPIR-V via DXVK's vendored translator.
//
// Follows upstream lsfg-vk's src/extract/trans.cpp, including its
// encounter-order binding renumber. Ported to WinNative (lsfg_dxbc.cpp) and
// DroidDeck by @maxjivi05 from the work of Camille LaVey / the Eden Emulator
// Project (GPL-3.0-or-later); the translator itself is DXVK's, zlib licensed,
// vendored under cpp/thirdparty/dxbc.
// encounter-order binding renumber. Derived from WinNative's lsfg_dxbc.cpp
// (GPL-3.0-or-later); the translator itself is DXVK's, zlib licensed, vendored
// under cpp/thirdparty/dxbc.
#include "lsfg_dxbc.h"
@@ -1,8 +1,7 @@
// See lsfg_engine.h.
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative (vkr_lsfg.cpp) and DroidDeck by
// @maxjivi05, where it runs on gamescope's output in the compositor.
// Ported from WinNative's vkr_lsfg.cpp (GPL-3.0-or-later), LSFG port credited
// to Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk.
#include "lsfg_engine.h"
@@ -270,7 +269,7 @@ void Engine::process(VkCommandBuffer cmd, VkImage source, uint32_t width, uint32
// nothing. Copy only when generating, on the one priming frame that
// precedes generation, or while the governor is warming up towards a
// probe - so the ring is populated by the time it is needed.
const bool needHistory = generations > 0 || primeHistory_ || followEveryFrame()
const bool needHistory = generations > 0 || primeHistory_
|| (governorEnabled_ && governor_.wantsHistory());
if (needHistory) {
copyPresentedFrame(cmd, source, chain_->Input(count), VkExtent2D{width, height});
@@ -285,7 +284,7 @@ void Engine::process(VkCommandBuffer cmd, VkImage source, uint32_t width, uint32
// regardless of the game's own settings, and it fed straight back into the
// governor: the chain made the source rate collapse, the governor saw the
// collapse and refused to generate, and refusing did not stop the chain.
if (warm_ && (generations > 0 || followEveryFrame())) chain_->DispatchShared(cmd, count);
if (warm_ && generations > 0) chain_->DispatchShared(cmd, count);
}
void Engine::generateInto(VkCommandBuffer cmd, uint32_t generation, uint32_t targetIndex,
+2 -7
View File
@@ -16,9 +16,8 @@
// unavoidable cost of interpolating rather than extrapolating; no placement of
// this code changes it.
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative (vkr_lsfg.cpp) and DroidDeck by
// @maxjivi05, where it runs on gamescope's output in the compositor.
// Ported from WinNative's vkr_lsfg.cpp (GPL-3.0-or-later), LSFG port credited
// to Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk.
// ============================================================================
#include <cstdint>
@@ -110,10 +109,6 @@ private:
// generation last stopped.
bool historyFresh() const { return haveCopied_ && lastCopiedCount_ + 1 == frameCount_; }
// With a target rate the pacer plans 0..3 generations frame by frame, so the ring and the
// shared chain have to follow every frame it keeps warm, not just the ones that generate.
bool followEveryFrame() const { return warm_ && pacer_.Config().target_rate != 0; }
Device device_{};
std::string cachePath_;
std::unique_ptr<LsfgShaders> shaders_;
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_gamma.hpp"
#include "lsfg_shaders.hpp"
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_generate.hpp"
#include "lsfg_dll.h"
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
@@ -27,6 +27,12 @@ Java_com_droiddeck_launcher_gpu_LsfgNative_nativeValidateDll(JNIEnv* env, jclass
return (jint)lsfg::validateDll(toStdString(env, dllPath));
}
extern "C" JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_gpu_LsfgNative_nativeDllVariant(JNIEnv* env, jclass, jstring dllPath,
jboolean preferFp16) {
return (jint)lsfg::dllVariant(toStdString(env, dllPath), preferFp16 == JNI_TRUE);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_gpu_LsfgNative_nativeBuildCache(JNIEnv* env, jclass, jstring dllPath,
jstring cachePath, jboolean preferFp16) {
@@ -34,6 +40,16 @@ Java_com_droiddeck_launcher_gpu_LsfgNative_nativeBuildCache(JNIEnv* env, jclass,
preferFp16 == JNI_TRUE);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_gpu_LsfgNative_nativeCacheMatchesSource(JNIEnv* env, jclass,
jstring cachePath,
jstring dllPath) {
bool matches = false;
const lsfg::DllStatus status = lsfg::cacheMatchesSource(toStdString(env, cachePath),
toStdString(env, dllPath), matches);
return (jboolean)(status == lsfg::DllStatus::Ok && matches);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_gpu_LsfgNative_nativeCacheVariant(JNIEnv* env, jclass, jstring cachePath) {
lsfg::Variant variant = lsfg::Variant::None;
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_mipmaps.hpp"
#include "lsfg_dll.h"
@@ -4,9 +4,10 @@
// SPDX-FileCopyrightText: Copyright 2025 lsfg-vk
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
@@ -1,9 +1,10 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_pacer.hpp"
@@ -21,8 +22,6 @@ constexpr float SOURCE_SMOOTHING = 0.15f;
constexpr float SOURCE_STALE_SECONDS = 0.5f;
constexpr float DISCONTINUITY_SECONDS = 0.25f;
constexpr float HEADROOM_EPSILON = 0.02f;
// A target is aimed just under, so rounding never puts output past the panel's refresh rate.
constexpr float TARGET_MARGIN = 0.1f;
constexpr float CREDIT_EPSILON = 1.0e-4f;
constexpr float SOURCE_ACCUM_FLOOR = 0.01f;
constexpr uint32_t MIN_RATE_SAMPLES = 12;
@@ -118,7 +117,6 @@ LsfgPlan LsfgPacer::Plan(size_t capacity, uint64_t source_frames) {
if (target_rate > 0.0f && config.refresh_rate > 0.0f) {
target_rate = std::min(target_rate, config.refresh_rate);
}
if (target_rate > 0.0f) target_rate -= TARGET_MARGIN;
if (target_rate == 0.0f) {
// No explicit target rate: the multiplier is the multiplier, full stop.
@@ -1,9 +1,10 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
@@ -1,9 +1,10 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#include "lsfg_shaders.hpp"
#include "lsfg_common.hpp"
@@ -1,9 +1,10 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
//
// LSFG from the work of Camille LaVey / the Eden Emulator Project, following
// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the
// Vulkan dispatch differs here (see lsfg_vkd.h).
// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later),
// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and
// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator
// resolves entry points through the renderer's own table (see lsfg_vkd.h).
#pragma once
+2 -2
View File
@@ -2,10 +2,10 @@
// ============================================================================
// lsfg_vkd - the Vulkan entry points the LSFG chain calls, as a single global.
//
// Two dispatch styles meet here. DroidDeck's compositor resolves Vulkan
// Two dispatch styles meet here. Bannerlator's compositor resolves Vulkan
// through a per-context VkTable (`vk_`), because an adrenotools-loaded driver
// lives in an isolated linker namespace and shares no global symbols with the
// system loader. The LSFG chain, ported from Eden by way of WinNative, calls
// system loader. The LSFG chain, ported from eden by way of WinNative, calls
// through a file-scope `vkd`. Rather than rewrite ~2,300 lines of proven chain
// code to thread a table through every call, this shim exposes exactly the 34
// entry points the chain uses and is filled from the renderer's own table when
+2 -19
View File
@@ -541,13 +541,6 @@ static void cursor_publish_shm(struct wl_shm_buffer *shm, int hx, int hy) {
wl_shm_buffer_end_access(shm);
}
/* The serial alone, without the lock: the app asks on every pointer move, and the snapshot below
* copies up to 256 KB of pixels across JNI and holds the lock the compositor thread takes to
* change the cursor. A torn read is only a missed or an extra snapshot. */
int banner_cursor_serial(void) {
return __atomic_load_n(&g_cursor_serial, __ATOMIC_RELAXED);
}
/* Read by the app (UI thread). out = [serial, hidden, w, h, hotspotX, hotspotY, pixels...].
* Returns the number of ints written, or 0 if out is too small. */
int banner_cursor_snapshot(int *out, int cap) {
@@ -750,8 +743,6 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
static struct surface *g_hud_surface;
/* When the HUD's window last presented a frame (now_ns), to let a replacement take over. */
static int64_t g_hud_last_ns;
/* That window committed a frame the screen has not drawn yet. */
static int g_hud_fresh;
extern void banner_on_game_surface(const char *window, const char *gpu); /* window NULL = gone */
extern void banner_on_game_frame(void);
/* The program behind that window: its Linux pid (the Wayland client's credentials) and executable name
@@ -854,7 +845,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
* Asking whether the compositor could import it, as this used to, is a question about the
* copy path and not about whether a frame happened: a game whose buffers go straight to
* the display layer draws on screen while the counter sat at 0.0 fps and 1000.0 ms. */
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); g_hud_fresh = 1; banner_on_game_frame(); }
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); banner_on_game_frame(); }
}
/* ---- hooks for ahb_swapchain.c (zero-copy layers) */
@@ -2023,7 +2014,6 @@ static void render_scene(void) {
int copy = 0; /* this scene went through the screen swapchain (the perf line's "copy") */
g_dirty = 0;
g_hud_fresh = 0;
g_hdr_unimported = NULL; /* found again while the scene is built (HDR gate open only) */
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
scene_size(&w, &h);
@@ -2239,13 +2229,6 @@ static void schedule_render(void) {
wl_event_source_timer_update(g_fallback_timer, 8);
}
/* With frame generation on, every scene is the engine's next source frame, so one drawn for
* another window (Steam's overlay) counted as a game frame and took its present slots. Such a
* change waits for the game's next frame, unless the game has been still for 100 ms. */
static int scene_waits_for_game(int64_t now) {
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
}
/* A screen refresh (Choreographer tick): draw the newest state once. */
static void on_vsync(int64_t frame_time_ns) {
int64_t now = now_ns();
@@ -2261,7 +2244,7 @@ static void on_vsync(int64_t frame_time_ns) {
if (vkp_apply_window_request()) g_dirty = 1;
/* A screen-effect setting changed (JNI, any thread): redraw so it shows on a static scene too. */
if (vkp_effects_sync()) g_dirty = 1;
if (g_dirty && !scene_waits_for_game(now)) render_scene();
if (g_dirty) render_scene();
}
/* ------------------------------------------------------------------ wl_seat */
@@ -19,7 +19,6 @@ void banner_log(const char *tag, const char *fmt, ...) __attribute__((format(pri
static _Atomic int g_kind = VKP_FG_ENGINE_LSFG;
static _Atomic int g_armed;
static _Atomic int g_mult = 2;
static _Atomic int g_target; /* LSFG adaptive fps, 0 = fixed multiplier */
static _Atomic int g_model = 3;
static _Atomic int g_preset = 2;
static _Atomic int g_cfg_dirty = 1;
@@ -52,7 +51,6 @@ static struct {
/* ---- engine + generation ring (compositor thread) ------------------------------------ */
static int g_engine_kind = -1; /* kind of the running engine, -1 = none */
static int g_engine_cache_gen = -1; /* the LSFG cache it loaded */
static int g_engine_ok;
/* The engine of this kind (with this cache) could not start or build its chain; not retried
* every frame - a new engine selection or a new cache clears it. */
@@ -94,20 +92,15 @@ static int64_t now_ns(void) {
void vkp_framegen_set_engine(int kind) {
if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_WINFG) kind = VKP_FG_ENGINE_LSFG;
atomic_store(&g_kind, kind);
atomic_store(&g_failed_kind, -1);
atomic_store(&g_cfg_dirty, 1);
}
void vkp_framegen_set_armed(int armed, int multiplier, int target_fps) {
if (target_fps < 0) target_fps = 0;
/* Adaptive sizes the ring and the swapchain for the most it may ever generate. */
if (target_fps) multiplier = VKP_FG_MAX_GENERATIONS + 1;
void vkp_framegen_set_armed(int armed, int multiplier) {
if (multiplier < 2) multiplier = 2;
if (multiplier > VKP_FG_MAX_GENERATIONS + 1) multiplier = VKP_FG_MAX_GENERATIONS + 1;
if (atomic_exchange(&g_mult, multiplier) != multiplier) atomic_store(&g_cfg_dirty, 1);
if (atomic_exchange(&g_target, target_fps) != target_fps) atomic_store(&g_cfg_dirty, 1);
atomic_store(&g_armed, armed ? 1 : 0);
LOGD("framegen: set_armed(%d, x%d, target %d fps)", armed, multiplier, target_fps);
LOGD("framegen: set_armed(%d, x%d)", armed, multiplier);
}
void vkp_framegen_set_lsfg_cache_path(const char *path) {
@@ -292,9 +285,7 @@ int vkp_framegen_extra_images(void) {
}
static int ensure_engine(int kind) {
const int cache_gen = atomic_load(&g_cache_gen);
if (g_engine_ok && g_engine_kind == kind && (kind != VKP_FG_ENGINE_LSFG || g_engine_cache_gen == cache_gen))
return 1;
if (g_engine_ok && g_engine_kind == kind) return 1;
if (start_failed_for(kind)) return 0;
if (g_engine_ok) { destroy_ring(); fge_stop(); g_engine_ok = 0; g_engine_kind = -1; }
char *path = NULL;
@@ -302,7 +293,7 @@ static int ensure_engine(int kind) {
if (g_cache_path) path = strdup(g_cache_path);
pthread_mutex_unlock(&g_lock);
if (kind == VKP_FG_ENGINE_LSFG && !path) {
FGLOG("LSFG Native can't start: no shader cache from Lossless.dll");
FGLOG("LSFG Native can't start: no shader cache (import Lossless.dll in Settings)");
mark_failed(kind);
return 0;
}
@@ -314,39 +305,29 @@ static int ensure_engine(int kind) {
mark_failed(kind);
return 0;
}
g_engine_ok = 1; g_engine_kind = kind; g_engine_cache_gen = cache_gen;
g_engine_ok = 1; g_engine_kind = kind;
atomic_store(&g_cfg_dirty, 1);
g_built_w = g_built_h = 0;
FGLOG("%s engine ready (%s)", fge_engine_name(kind), fge_build_info());
return 1;
}
/* "x3 (2 interpolated frames per game frame)" or "adaptive to 90 fps (up to 3 ...)". */
static const char *describe_mode(char *buf, size_t n, int mult, int target) {
if (target) snprintf(buf, n, "adaptive to %d fps (up to %d interpolated frames per game frame)", target, mult - 1);
else snprintf(buf, n, "x%d (%d interpolated frame%s per game frame)", mult, mult - 1, mult == 2 ? "" : "s");
return buf;
}
static int g_logged_mult, g_logged_target;
static int g_logged_mult;
static void log_arm_transition(int armed, int kind, int mult) {
const int target = atomic_load(&g_target);
char mode[96];
if (armed == g_was_armed) {
if (armed && (mult != g_logged_mult || target != g_logged_target)) {
g_logged_mult = mult; g_logged_target = target;
FGLOG("%s now %s", fge_engine_name(kind), describe_mode(mode, sizeof(mode), mult, target));
if (armed && mult != g_logged_mult) {
g_logged_mult = mult;
FGLOG("%s multiplier changed to x%d (%d interpolated frames per game frame)", fge_engine_name(kind), mult, mult - 1);
}
return;
}
g_was_armed = armed;
if (armed) {
g_logged_mult = mult; g_logged_target = target;
g_logged_mult = mult;
float flow, hz;
pthread_mutex_lock(&g_lock); flow = g_flow; hz = g_refresh_hz; pthread_mutex_unlock(&g_lock);
FGLOG("%s %s armed (flow scale %.2f, panel %.0f Hz): real frames are presented one slot late "
"with the interpolated frames ahead of them", fge_engine_name(kind),
describe_mode(mode, sizeof(mode), mult, target), (double)flow, (double)hz);
FGLOG("%s x%d armed (flow scale %.2f, panel %.0f Hz): real frames are presented one slot late "
"with the interpolated frames ahead of them", fge_engine_name(kind), mult, (double)flow, (double)hz);
} else {
FGLOG("frame generation off (%llu frames generated this session)", (unsigned long long)g_total_generated);
g_generating_logged = 0;
@@ -367,8 +348,7 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
if (atomic_exchange(&g_cfg_dirty, 0)) {
float flow, hz;
pthread_mutex_lock(&g_lock); flow = g_flow; hz = g_refresh_hz; pthread_mutex_unlock(&g_lock);
fge_configure((uint32_t)mult, (uint32_t)atomic_load(&g_target), flow, hz,
atomic_load(&g_model), atomic_load(&g_preset));
fge_configure((uint32_t)mult, flow, hz, atomic_load(&g_model), atomic_load(&g_preset));
}
if (!fge_prepare((uint32_t)w, (uint32_t)h, fmt)) {
if (fmt != VK_FORMAT_R8G8B8A8_UNORM && fge_unavailable()) {
@@ -446,9 +426,8 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
0, 0, NULL, 0, NULL, nb, bars);
if (!g_generating_logged) {
g_generating_logged = 1;
char mode[96];
FGLOG("generating: %s %s at %dx%d%s", fge_engine_name(kind),
describe_mode(mode, sizeof(mode), mult, atomic_load(&g_target)), w, h,
FGLOG("generating: %s x%d at %dx%d (%u interpolated frame%s per game frame%s)",
fge_engine_name(kind), mult, w, h, n_gen, n_gen == 1 ? "" : "s",
fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? ", FP16: the HDR picture" : "");
}
}
@@ -34,10 +34,9 @@ enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_WINFG = 1 };
/* ---- app controls (any thread) ------------------------------------------------------- */
void vkp_framegen_set_engine(int kind);
/* multiplier 2..4, or target_fps > 0 for LSFG's adaptive mode (up to 4x, as the target needs);
* armed = 0 stops generating (the ring and the engine stay for a re-arm). */
void vkp_framegen_set_armed(int armed, int multiplier, int target_fps);
/* LSFG Native: the SPIR-V cache built from the user's Lossless.dll (Lossless.sync); a new path reloads the engine. */
/* multiplier 2..4; armed = 0 stops generating (the ring and the engine stay for a re-arm). */
void vkp_framegen_set_armed(int armed, int multiplier);
/* LSFG Native: the SPIR-V cache built from the user's Lossless.dll (LsfgNative.ensureCache). */
void vkp_framegen_set_lsfg_cache_path(const char *path);
/* Flow scale 0.25..1.0 and the panel's real refresh rate (the pacer never generates above it). */
void vkp_framegen_set_tuning(float flow_scale, float refresh_hz);
@@ -197,11 +197,11 @@ int fge_unavailable(void) {
return g_lsfg && g_lsfg->unavailable() ? 1 : 0;
}
void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz,
int model, int perf_preset) {
void fge_configure(uint32_t multiplier, float flow_scale, float refresh_hz, int model,
int perf_preset) {
if (multiplier < 2) multiplier = 2;
if (g_kind == 1 && g_winfg) g_winfg->configure(multiplier, model, perf_preset, flow_scale);
else if (g_lsfg) g_lsfg->configure(multiplier, target_fps, flow_scale, refresh_hz);
else if (g_lsfg) g_lsfg->configure(multiplier, 0, flow_scale, refresh_hz);
}
int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) {
@@ -45,9 +45,8 @@ int fge_start(int kind, const char *cache_path);
void fge_stop(void);
/* The engine came up but later found it cannot generate (chain build failed). */
int fge_unavailable(void);
/* target_fps > 0: LSFG picks 0..3 generations per frame to reach it (Win-FG ignores it). */
void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz,
int model, int perf_preset);
void fge_configure(uint32_t multiplier, float flow_scale, float refresh_hz, int model,
int perf_preset);
/* Build/rebuild the chain for this extent; the guest extent for the flow pyramid is the same
* (the Wayland scene is the game's own size in fullscreen). 1 = chain valid. */
int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt);
@@ -17,9 +17,8 @@ int fge_format_ok(VkFormat fmt) { (void)fmt; return 0; }
int fge_start(int kind, const char *cache_path) { (void)kind; (void)cache_path; return -1; }
void fge_stop(void) {}
int fge_unavailable(void) { return 1; }
void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz, int model,
int perf_preset) {
(void)multiplier; (void)target_fps; (void)flow_scale; (void)refresh_hz; (void)model; (void)perf_preset;
void fge_configure(uint32_t multiplier, float flow_scale, float refresh_hz, int model, int perf_preset) {
(void)multiplier; (void)flow_scale; (void)refresh_hz; (void)model; (void)perf_preset;
}
int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { (void)w; (void)h; (void)fmt; return 0; }
uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) {
@@ -14,9 +14,9 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenEngine(JN
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenArmed(JNIEnv *env, jclass clazz,
jboolean armed, jint multiplier, jint targetFps) {
jboolean armed, jint multiplier) {
(void)env; (void)clazz;
vkp_framegen_set_armed(armed ? 1 : 0, (int)multiplier, (int)targetFps);
vkp_framegen_set_armed(armed ? 1 : 0, (int)multiplier);
}
JNIEXPORT void JNICALL
@@ -6,7 +6,6 @@
*/
#include <jni.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <pthread.h>
#include <stdlib.h>
@@ -26,7 +25,6 @@ extern int banner_wayland_run(void);
extern void banner_wayland_send_pointer(int action, int x, int y);
extern void banner_wayland_send_touch(int action, int pointer_id, int x, int y);
extern int banner_cursor_snapshot(int *out, int cap);
extern int banner_cursor_serial(void);
extern void banner_wayland_send_key(int evdev, int state);
extern void banner_wayland_send_scene_input(int type, int a, int b);
extern void banner_wayland_vsync(int64_t frame_time_ns);
@@ -296,13 +294,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
return n;
}
/* The serial nativeCursorSnapshot would return, without copying anything. */
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
(void)env; (void)clazz;
return banner_cursor_serial();
}
/* Inject a key event. evdev = Linux input keycode (KEY_A=30…); state 1=down 0=up. */
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
@@ -679,29 +670,3 @@ JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIEnv *env, jclass clazz, jint before, jint after) {
banner_host_text_delete(before, after);
}
/* KGSL's power control, off (the GPU held at its top clock) or back on. The property is the
* device's, not this process's: it outlives the fd and the app, so the caller clears it at stop
* and again at every app start. No root; the kernel's thermal limits still apply. */
extern void adrenotools_set_turbo(bool turbo);
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
(void)env; (void)clazz;
adrenotools_set_turbo(on == JNI_TRUE);
}
/* Raises one of our own processes or threads to `nice` with a bare setpriority(), never lowering
* it. android.os.Process.setThreadPriority is not used for this: it also moves the thread between
* scheduling groups by priority, and a guest process must stay where Android put the app. Returns
* the nice value it is left at, or 100 when it could not be read. */
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeRaisePriority(JNIEnv *env, jclass clazz, jint tid, jint nice) {
(void)env; (void)clazz;
errno = 0;
int before = getpriority(PRIO_PROCESS, (id_t)tid);
if (before == -1 && errno != 0) return 100;
if (before > nice) setpriority(PRIO_PROCESS, (id_t)tid, nice);
errno = 0;
int after = getpriority(PRIO_PROCESS, (id_t)tid);
return after == -1 && errno != 0 ? 100 : after;
}
@@ -3,22 +3,15 @@ package com.droiddeck.launcher
import android.app.Application
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.session.CrashHandler
import com.droiddeck.launcher.session.GpuClockPin
/**
* Process-wide setup: the crash handler, so a session's folder is finished even when we die, and
* the GPU clock pin cleared in case a killed process left it set, and the socket Flatpak's
* sandboxes are started through (BwrapSpawner).
* the socket Flatpak's sandboxes are started through (BwrapSpawner).
*/
class App : Application() {
override fun onCreate() {
super.onCreate()
CrashHandler.install(this)
// Before anything else touches the session prefs, so the first session already runs in Deck mode.
com.droiddeck.launcher.session.SessionPrefs.settleDeckModeDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.update.AppUpdates.init(this)
GpuClockPin.clearLeftover(this)
BwrapSpawner.start(this)
}
}
@@ -16,7 +16,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
var compCatalogAt by mutableStateOf(0L)
var compProton by mutableStateOf<String?>(null)
var compComp by mutableStateOf(com.droiddeck.launcher.ui.GPU_TAB)
var compComp by mutableStateOf("dxvk")
var compChecking by mutableStateOf(false)
var compBusy by mutableStateOf<String?>(null)
var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
@@ -10,10 +10,6 @@ import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableIntStateOf
import com.droiddeck.launcher.gpu.DriverBundle
import com.droiddeck.launcher.gpu.DriverPairs
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.TurnipDriver
@@ -21,16 +17,11 @@ import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.DriverRow
import com.droiddeck.launcher.ui.GpuDriversState
import com.droiddeck.launcher.ui.PairRow
import com.droiddeck.launcher.wayland.CompositorHost
/**
* The GPU drivers: what this GPU is, the matched driver pairs the release repos offer for it, and
* - in Auto, the default - keeping the recommended pair installed and set. Under Advanced, the
* Linux (runtime) and Android (display) lists as before, each picked on its own - except a
* bundle's two halves (DriverBundle), which are always picked, and deleted, together. The launcher
* screen keeps one and hands it to the Components page's GPU drivers tab.
* The Linux and Android driver menus: the drivers each can pick from, the release downloads the
* last check found, and what each mode is set to. The launcher screen keeps one and hands its
* rows to the mode settings dialog.
*/
internal class DriverMenus(private val activity: Activity, private val ui: Handler) {
var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
@@ -42,42 +33,17 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
var canRestoreBundled by mutableStateOf(false)
/** Asset name -> download percent, while it downloads. */
private val releaseProgress = HashMap<String, Int>()
var linuxSelected by mutableStateOf("")
val gpu: GpuInfo = GpuInfo.detect()
// Read in refreshDrivers/ensureAuto: the activity has no context yet while its fields are made.
var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO)
var pairRows by mutableStateOf<List<PairRow>>(emptyList())
/** The pair being installed, and how far along. */
var pairBusy by mutableStateOf<String?>(null)
var pairPercent by mutableIntStateOf(-1)
/** What Auto last did or found, for the line under the pair in use. */
var autoStatus by mutableStateOf("")
/** The bundle both drivers are set to, as "DD-Turnip 0.1.0", or null when they are not one. */
var activeBundle by mutableStateOf<String?>(null)
private var autoCheckedThisProcess = false
fun state() = GpuDriversState(
gpuName = gpu.name, gpuFamily = gpu.family.label, soc = gpu.soc, supportText = gpu.supportText,
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
autoStatus = autoStatus, releaseStatus = releaseStatus, checking = releaseChecking,
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
activeBundle = activeBundle,
)
var linuxSteam by mutableStateOf("")
var linuxDesktop by mutableStateOf("")
var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
var androidSelected by mutableStateOf("")
fun refreshDrivers() {
val lm = LinuxVulkanDriverManager(activity)
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
val bundles = DriverBundle.all(activity)
fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let {
DriverRow(id, it.label, "Android + Linux: sets the ${if (linux) "display" else "runtime"} driver with it", true, DriverRow.BUNDLE)
}
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
else bundleRow(id, linux = true) ?: DriverRow(
else DriverRow(
id, lm.getDriverName(id),
listOfNotNull(
lm.getDriverVersion(id).takeIf { it.isNotEmpty() },
@@ -86,8 +52,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
true, origin(id),
)
}
linuxSelected = SessionPrefs.linuxDriver(activity)
mode = SessionPrefs.gpuDriverMode(activity)
linuxSteam = SessionPrefs.linuxDriver(activity, SessionService.MODE_STEAM)
linuxDesktop = SessionPrefs.linuxDriver(activity, SessionService.MODE_DESKTOP)
val td = TurnipDriver(activity)
val auto = td.autoId()
androidRows = buildList {
@@ -97,211 +63,23 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
false,
))
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
for (id in td.enumerateImported()) add(bundleRow(id, linux = false) ?: DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
}
canRestoreBundled = td.hiddenBundled().isNotEmpty()
androidSelected = SessionPrefs.androidDriver(activity)
activeBundle = DriverBundle.active(activity)?.label
refreshReleaseRows()
refreshPairs()
}
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
fun summary(): String {
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
return (if (mode == SessionPrefs.GPU_DRIVERS_AUTO) "Auto" else "Manual") + (active?.let { " · $it" } ?: "")
}
/** The pairs the last check found, with what is installed and in use; this GPU's first. */
fun refreshPairs() {
val lm = LinuxVulkanDriverManager(activity)
val td = TurnipDriver(activity)
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val recommended = DriverPairs.recommendedKey(gpu, pairs)
pairRows = pairs.map { p ->
val bundle = p.bundle?.let { installedBundle(it) }
val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) }
val linuxId = if (p.bundle != null) bundle?.linuxId else p.linux?.let { TurnipReleases.installedId(activity, it, lm::isInstalled) }
val mb = p.assets.sumOf { it.size } / 1_048_576.0
PairRow(
key = p.key, name = p.name, version = p.version,
detail = if (!p.complete) "Only one half is published right now" else "%.0f MB for both".format(mb),
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
installed = displayId != null && linuxId != null,
active = displayId != null && linuxId != null &&
SessionPrefs.androidDriver(activity) == displayId && SessionPrefs.linuxDriver(activity) == linuxId,
)
}.sortedByDescending { it.recommended }
}
fun setMode(auto: Boolean) {
mode = if (auto) SessionPrefs.GPU_DRIVERS_AUTO else SessionPrefs.GPU_DRIVERS_MANUAL
SessionPrefs.setGpuDriverMode(activity, mode)
autoStatus = ""
if (auto) ensureAuto(force = false)
}
/**
* Auto: make the recommended pair for this GPU the one installed and set. Looks online when
* [force]d (refresh), or when the last check is a day old - Banners-Turnip rebuilds hourly, and
* a new pair a day is plenty - otherwise works from the last check. Once per app start on its
* own; the pair it replaces is removed, anything the user imported or picked is left alone.
*/
fun ensureAuto(force: Boolean) {
mode = SessionPrefs.gpuDriverMode(activity)
if (mode != SessionPrefs.GPU_DRIVERS_AUTO || pairBusy != null || releaseChecking) return
if (!force && autoCheckedThisProcess) return
autoCheckedThisProcess = true
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
autoStatus = "No drivers to set: ${gpu.supportText.lowercase()}"
return
}
releaseChecking = true
autoStatus = "Checking for the latest drivers…"
Thread({
val cached = TurnipReleases.cached(activity)
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L ||
cached.assets.none { it.pair.isNotEmpty() }
val problem = if (force || stale) runCatching { TurnipReleases.refresh(activity) }.exceptionOrNull()?.message else null
ui.post {
releaseChecking = false
refreshReleaseRows()
refreshPairs()
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val key = DriverPairs.recommendedKey(gpu, pairs)
val pair = pairs.firstOrNull { it.key == key }
val row = pairRows.firstOrNull { it.key == key }
when {
row?.active == true -> autoStatus = "Up to date" + (problem?.let { " (couldn't check: $it)" } ?: "")
pair == null || !pair.complete ->
autoStatus = problem?.let { "Couldn't check: $it" } ?: "The recommended drivers aren't published right now"
else -> installPair(pair, auto = true)
}
}
}, "gpu-driver-auto").start()
}
/** Manual: install (if need be) and set both halves of a pair. */
fun selectPair(key: String) {
if (pairBusy != null) return
val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
installPair(pair, auto = false)
}
/**
* Download what is missing of [pair], then set both halves - only once both are in, so a
* failed download never leaves a half-changed pair. Auto's own downloads are recorded, and the
* ones the new pair replaces are removed.
*/
private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean) {
if (!pair.complete) return
pairBusy = pair.key
pairPercent = 0
if (auto) autoStatus = "Downloading ${pair.name} ${pair.version}…"
Thread({
val lm = LinuxVulkanDriverManager(activity)
val td = TurnipDriver(activity)
var downloaded = false
val result = runCatching {
val zips = pair.assets
val ids = zips.mapIndexed { i, asset ->
installedIdOf(asset)
?: installAsset(asset) { pct -> ui.post { pairPercent = (i * 100 + pct) / zips.size } }.also { downloaded = true }
}
if (pair.bundle != null) DriverBundle.get(activity, ids[0])!!.let { listOf(it.androidId, it.linuxId) } else ids
}
ui.post {
pairBusy = null
pairPercent = -1
result.onSuccess { (displayId, linuxId) ->
val displayChanged = SessionPrefs.androidDriver(activity) != displayId
SessionPrefs.setAndroidDriver(activity, displayId)
SessionPrefs.setLinuxDriver(activity, linuxId)
val restart = if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
if (auto) {
val previous = SessionPrefs.gpuAutoInstalled(activity)
for (id in previous - setOf(displayId, linuxId)) {
val bundle = DriverBundle.containing(activity, id, lm.isInstalled(id))
when {
bundle != null -> { DriverBundle.remove(activity, bundle); TurnipReleases.forget(activity, bundle.id) }
lm.isInstalled(id) -> lm.removeDriver(id)
else -> td.remove(id)
}
TurnipReleases.forget(activity, id)
}
SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId))
autoStatus = (if (downloaded) "Updated to" else "Switched to") + " ${pair.name} ${pair.version}.$restart"
} else {
android.widget.Toast.makeText(activity, "Using ${pair.name} ${pair.version}.$restart", android.widget.Toast.LENGTH_LONG).show()
}
}.onFailure { e ->
Log.w(TAG, "driver pair ${pair.key}", e)
val why = if (e is IllegalArgumentException) e.message else "Download failed: ${e.message}"
if (auto) autoStatus = why ?: "Download failed"
else android.widget.Toast.makeText(activity, why, android.widget.Toast.LENGTH_LONG).show()
}
refreshDrivers()
}
}, "gpu-driver-pair").start()
}
/** The bundle a release bundle was downloaded as, while both its halves are installed. */
private fun installedBundle(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
TurnipReleases.installedId(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
/** The id a release asset was installed as (a bundle's id for a bundle), or null when it is not installed. */
private fun installedIdOf(asset: TurnipReleases.Asset): String? = when {
asset.bundle -> installedBundle(asset)?.id
asset.linux -> TurnipReleases.installedId(activity, asset, LinuxVulkanDriverManager(activity)::isInstalled)
else -> TurnipReleases.installedId(activity, asset, TurnipDriver(activity)::isInstalled)
}
/**
* One release asset, downloaded, checked and installed through the importer; returns its id,
* a bundle's id for a bundle.
*/
private fun installAsset(asset: TurnipReleases.Asset, progress: (Int) -> Unit): String {
var file: File? = null
try {
file = TurnipReleases.download(activity, asset, progress)
val uri = Uri.fromFile(file)
val id = when {
asset.bundle -> DriverBundle.install(activity, uri).id
asset.linux -> LinuxVulkanDriverManager(activity).installDriver(uri, asset.name)
else -> TurnipDriver(activity).installFromZip(uri, asset.name)
}
TurnipReleases.recordDownload(activity, asset, id)
return id
} finally {
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
}
}
/**
* Import off the main thread - a driver zip is a few MB and the glibc check reads the whole
* library - then say what happened. A refusal's message is the user-facing reason. A bundle,
* from any import, installs both halves and is set as both drivers at once. [linux] null (the
* tab's own Import .zip) takes a single driver to whichever list its libc belongs in.
* library - then say what happened. A refusal's message is the user-facing reason.
*/
fun importDriver(uri: Uri, linux: Boolean?) {
fun importDriver(uri: Uri, linux: Boolean) {
val name = activity.displayNameOf(uri)
Thread({
var bundle: DriverBundle.Bundle? = null
val problem = try {
when {
DriverBundle.isBundle(activity, uri) -> bundle = DriverBundle.install(activity, uri)
linux == true -> LinuxVulkanDriverManager(activity).installDriver(uri, name)
linux == false -> TurnipDriver(activity).installFromZip(uri, name)
else -> try {
TurnipDriver(activity).installFromZip(uri, name)
} catch (display: IllegalArgumentException) {
try {
LinuxVulkanDriverManager(activity).installDriver(uri, name)
} catch (runtime: IllegalArgumentException) {
throw IllegalArgumentException("Not a driver zip: neither an AdrenoTools driver, a -Linux Turnip nor an Android + Linux bundle")
}
}
}
if (linux) LinuxVulkanDriverManager(activity).installDriver(uri, name)
else TurnipDriver(activity).installFromZip(uri, name)
null
} catch (e: IllegalArgumentException) {
e.message
@@ -310,57 +88,26 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
"Import failed: ${e.message}"
}
ui.post {
val done = bundle?.let { useBundle(it) } ?: "Imported ${name ?: "driver"}"
android.widget.Toast.makeText(
activity, problem ?: done,
if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
activity, problem ?: "Imported ${name ?: "driver"}",
if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
).show()
refreshDrivers()
}
}, "import-driver").start()
}
/**
* Pick one driver from a list, which is Manual (Auto would put its pair back). A bundle's half
* sets the bundle's other half in the other list as well.
*/
fun selectDriver(id: String, linux: Boolean) {
val bundle = DriverBundle.containing(activity, id, linux)
when {
bundle != null -> useBundle(bundle)
linux -> SessionPrefs.setLinuxDriver(activity, id)
else -> SessionPrefs.setAndroidDriver(activity, id)
}
setMode(false)
refreshDrivers()
}
/** Set both halves of [bundle] as the drivers in use; returns what to tell the user. */
private fun useBundle(bundle: DriverBundle.Bundle): String {
val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId
DriverBundle.select(activity, bundle)
if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false)
return "Using ${bundle.label} as both the runtime and display driver." +
if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
}
/**
* Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a
* session never starts on a driver that is gone; a release download is forgotten, so the menu
* offers it again.
*/
fun deleteDriver(id: String, linux: Boolean) {
val bundle = DriverBundle.containing(activity, id, linux)
if (bundle != null) {
DriverBundle.remove(activity, bundle)
TurnipReleases.forget(activity, bundle.id)
android.widget.Toast.makeText(activity, "Deleted ${bundle.label} (both drivers)", android.widget.Toast.LENGTH_SHORT).show()
refreshDrivers()
return
}
if (linux) {
LinuxVulkanDriverManager(activity).removeDriver(id)
if (SessionPrefs.linuxDriver(activity) == id) SessionPrefs.setLinuxDriver(activity, "")
for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
if (SessionPrefs.linuxDriver(activity, mode) == id) SessionPrefs.setLinuxDriver(activity, mode, "")
}
} else {
val td = TurnipDriver(activity)
if (id in TurnipDriver.BUNDLED) td.hideBundled(id) else td.remove(id)
@@ -374,9 +121,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
/** The download entries and the refresh line, from what the last check found. */
fun refreshReleaseRows() {
val check = TurnipReleases.cached(activity)
val lm = LinuxVulkanDriverManager(activity)
val td = TurnipDriver(activity)
fun rows(linux: Boolean) = check?.assets.orEmpty()
.filter { it.bundle || it.linux == linux }
.filter { a -> installedIdOf(a) == null }
.filter { it.linux == linux }
.filter { a -> TurnipReleases.installedId(activity, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null }
.map { a ->
val mb = "%.1f MB".format(a.size / 1_048_576.0)
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
@@ -405,7 +154,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
fun checkLatestTurnip() {
if (releaseChecking) return
releaseChecking = true
releaseStatus = "Checking Banners-Turnip, WinNative and DroidDeck…"
releaseStatus = "Checking Banners-Turnip and WinNative…"
Thread({
val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) {
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
@@ -413,7 +162,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
ui.post {
releaseChecking = false
refreshReleaseRows()
refreshPairs()
if (problem != null) releaseStatus = "Couldn't check: $problem"
}
}, "turnip-release-check").start()
@@ -426,20 +174,28 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
releaseProgress[assetName] = 0
refreshReleaseRows()
Thread({
var file: java.io.File? = null
val problem = try {
installAsset(asset) { pct -> ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() } }
file = TurnipReleases.download(activity, asset) { pct ->
ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() }
}
val uri = Uri.fromFile(file)
val id = if (asset.linux) LinuxVulkanDriverManager(activity).installDriver(uri, asset.name)
else TurnipDriver(activity).installFromZip(uri, asset.name)
TurnipReleases.recordDownload(activity, asset, id)
null
} catch (e: IllegalArgumentException) {
e.message
} catch (e: Exception) {
Log.w(TAG, "release driver download", e)
"Download failed: ${e.message}"
} finally {
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
}
ui.post {
releaseProgress.remove(assetName)
val pick = if (asset.bundle) "pick it in either list to set both drivers" else "pick it in the menu"
android.widget.Toast.makeText(
activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - $pick",
activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu",
android.widget.Toast.LENGTH_LONG,
).show()
refreshDrivers()
@@ -1,6 +1,5 @@
package com.droiddeck.launcher
import androidx.compose.foundation.layout.fillMaxSize
import android.Manifest
import android.app.ActivityOptions
import android.content.Intent
@@ -28,7 +27,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.toArgb
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.gpu.LsfgNative
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.DesktopCatalog
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
@@ -58,6 +57,7 @@ import com.droiddeck.launcher.ui.ControllerActions
import com.droiddeck.launcher.ui.ControllerMappingPage
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.ControllerEditorActivity
import com.droiddeck.launcher.ui.CreditsDialog
import com.droiddeck.launcher.ui.FrontEndScreen
import com.droiddeck.launcher.ui.FrontEndState
import com.droiddeck.launcher.ui.FrontEndActions
@@ -82,7 +82,6 @@ class MainActivity : ComponentActivity() {
private val drivers = DriverMenus(this, ui)
private val components = ComponentsMenu(this, ui)
private val decky = DeckyMenu(this, ui)
private val updates = UpdatesMenu(this, ui)
private val protons = ProtonMenu(this, ui)
// The screen's state. Compose redraws whatever reads these when they change.
@@ -101,14 +100,13 @@ class MainActivity : ComponentActivity() {
private var percent by mutableIntStateOf(-1)
private var failed by mutableStateOf(false)
private var frameGenLabel by mutableStateOf("Off")
private var lossless by mutableStateOf(Lossless.State.NONE)
private var showRemove by mutableStateOf(false)
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true)
private var steamDeckMode by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var showCredits by mutableStateOf(false)
private var showProtons by mutableStateOf(false)
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
private var showComponents by mutableStateOf(false)
@@ -135,9 +133,7 @@ class MainActivity : ComponentActivity() {
private var zinkLazy by mutableStateOf(false)
private var noXalia by mutableStateOf(true)
private var gamescopeRealtime by mutableStateOf(false)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
@@ -145,9 +141,9 @@ class MainActivity : ComponentActivity() {
private var directAudio by mutableStateOf(false)
private var clientDirectAudio by mutableStateOf(false)
private var forceFullscreen by mutableStateOf(true)
private var stretch16x9 by mutableStateOf(false)
private var launcherFullscreen by mutableStateOf(true)
private var storeEnabled by mutableStateOf(false)
private var appImagesEnabled by mutableStateOf(false)
private var mic by mutableStateOf(false)
// The app's own picker (files/), once per kind of pick: the two driver lists validate
@@ -161,12 +157,6 @@ class MainActivity : ComponentActivity() {
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = false) }
}
private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) }
}
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private val pickSaveZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
@@ -176,26 +166,6 @@ class MainActivity : ComponentActivity() {
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
}
/** Takes a new or updated Lossless Scaling from Steam and shows what LSFG can use. */
private fun syncLossless() {
Thread({
Lossless.sync(this)
val state = Lossless.state(this)
ui.post { lossless = state }
}, "lossless-sync").start()
}
private fun importLossless(dll: File) {
Thread({
val message = Lossless.message(this, Lossless.import(this, dll))
val state = Lossless.state(this)
ui.post {
lossless = state
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
}
}, "lossless-import").start()
}
/** Import a save zip into [game]: pick it in the app's file picker, then back up and unzip off the main thread. */
private fun importSaves(name: String, game: () -> GameSaves.Game) {
if (SessionState.running) {
@@ -246,6 +216,9 @@ class MainActivity : ComponentActivity() {
private var addedGamesArt by mutableStateOf(true)
@Volatile private var artFetchRunning = false
private var addedGames by mutableStateOf<List<com.droiddeck.launcher.ui.AddedGameRow>>(emptyList())
private val pickAppImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { com.droiddeck.launcher.store.AppImageState.import(this, it) }
}
private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
SessionPrefs.setRomsDir(this, path)
@@ -262,7 +235,6 @@ class MainActivity : ComponentActivity() {
private var theme by mutableStateOf("graphite")
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
private var hdrOn by mutableStateOf(false)
private var fpsLimit by mutableStateOf(0)
private var hdrReason by mutableStateOf<String?>(null)
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
@@ -337,16 +309,13 @@ class MainActivity : ComponentActivity() {
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
theme = SessionPrefs.theme(this)
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
steamGames = com.droiddeck.launcher.frontend.LibraryCache.load(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
storeEnabled = SessionPrefs.storeEnabled(this)
appImagesEnabled = SessionPrefs.appImagesEnabled(this)
applyLauncherFullscreen()
updates.start()
setContent {
DroidDeckTheme(theme) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
val sm = settingsMode
val page: (@Composable () -> Unit)? = when {
sm != null -> { { ModeSettingsHost(sm) } }
@@ -365,8 +334,8 @@ class MainActivity : ComponentActivity() {
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this),
lossless = lossless,
frameGenEngine = FrameGen.engine(this), frameGenMultiplier = FrameGen.multiplier(this),
lsfgReady = LsfgNative.isInstalled(this),
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
theme = theme,
isHomeApp = homeAppSelected,
@@ -384,11 +353,11 @@ class MainActivity : ComponentActivity() {
buildLabel = BuildConfig.BUILD_LABEL,
oscMode = oscMode,
controller = controllerSettings,
updates = updates.state(),
phantomProcessStatus = phantomProcessStatus,
showPhantomGate = showPhantomGate,
launcherFullscreen = launcherFullscreen,
storeEnabled = storeEnabled,
appImagesEnabled = appImagesEnabled,
),
FrontEndActions(
onPlay = { startSteamSession() },
@@ -408,15 +377,18 @@ class MainActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP))
},
onEmulator = { e -> launchProgram(e.program) },
// An app added on the Desktop page, full screen under gamescope like an emulator.
onUserApp = { app ->
app.args.firstOrNull()?.let { Library.flatpakNames[it] = app.name }
// A Flatpak app from the store, full screen under gamescope like an emulator.
onImportAppImage = {
pickAppImage.launch(InAppFilePicker.buildIntent(this, listOf("appimage"), "Choose an AppImage"))
},
// An imported AppImage, full screen under gamescope like an emulator.
onAppImage = { dir, name ->
Library.flatpakNames[dir] = name
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, app.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray()))
.putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, arrayOf(dir)))
},
// A Flatpak app from the store, full screen under gamescope like an emulator.
onFlatpakApp = { id, name ->
Library.flatpakNames[id] = name
startActivity(Intent(this, SessionActivity::class.java)
@@ -438,13 +410,10 @@ class MainActivity : ComponentActivity() {
onInstallPackage = { id -> installPackage(id) },
onRemovePackage = { id -> removePackage(id) },
onRuntime = { onRuntimeButton() },
onFrameGenPick = { mode ->
FrameGen.set(this, mode)
onFrameGenPick = { engine, multiplier ->
FrameGen.set(this, engine, multiplier)
frameGenLabel = FrameGen.label(this)
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(this, listOf("dll"), getString(R.string.lsfg_pick_title)))
},
onProtons = { openProtons() },
onComponents = { focusContent -> openComponents(focusContent) },
// A game page's Manage saves: the game's Proton and saves are read when the work runs, off the main thread.
@@ -470,20 +439,11 @@ class MainActivity : ComponentActivity() {
}
}, "share-logs").start()
},
onClearLogs = {
Thread({
val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0)
ui.post {
android.widget.Toast.makeText(this,
if (cleared == 0) "No session logs to clear." else "Cleared $cleared session log folder${if (cleared == 1) "" else "s"}.",
android.widget.Toast.LENGTH_SHORT).show()
}
}, "clear-logs").start()
},
onOffline = {
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
offline = OfflineMode.enabled(this)
},
onCredits = { showCredits = true },
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
onLauncherFullscreen = { on ->
@@ -492,6 +452,7 @@ class MainActivity : ComponentActivity() {
applyLauncherFullscreen()
},
onStoreEnabled = { on -> SessionPrefs.setStoreEnabled(this, on); storeEnabled = on },
onAppImagesEnabled = { on -> SessionPrefs.setAppImagesEnabled(this, on); appImagesEnabled = on },
onHomeApp = { manageHomeApp() },
onHomeScreen = { on ->
HomeApp.setHomeScreenEnabled(this, on)
@@ -502,6 +463,9 @@ class MainActivity : ComponentActivity() {
SessionPrefs.setBackActionsInverted(this, inverted)
backActionsInverted = inverted
},
onCheckLatestBuild = {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml")))
},
onRefreshPhantomStatus = { refreshPhantomStatus() },
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
onWirelessAdbPair = { host, port, code, complete ->
@@ -552,7 +516,6 @@ class MainActivity : ComponentActivity() {
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
},
updates = updates.actions(),
controller = ControllerActions(
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() },
@@ -594,6 +557,7 @@ class MainActivity : ComponentActivity() {
onConfirm = { Thread({ LinuxRuntimeInstaller.uninstall(this); ui.post { refresh() } }, "uninstall").start() },
onDismiss = { showRemove = false },
)
if (showCredits) CreditsDialog { showCredits = false }
flood?.let { f -> com.droiddeck.launcher.ui.LaunchFlood(f.from, onProgress = { floodProgress = it }) { launchFlooded(f) } }
returning?.let { r ->
com.droiddeck.launcher.ui.FloodReturn(androidx.compose.ui.graphics.Color(r.color), r.to, onProgress = { floodProgress = it }) {
@@ -604,7 +568,6 @@ class MainActivity : ComponentActivity() {
}
}
}
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
@@ -628,7 +591,6 @@ class MainActivity : ComponentActivity() {
if (!SessionState.running) Thread({
SessionArtifacts.finishAbandoned(this)
SessionArtifacts.scrubOlder(this)
SessionArtifacts.prune(this)
}, "finish-abandoned").start()
}
@@ -665,11 +627,11 @@ class MainActivity : ComponentActivity() {
}
}
/** On the Components page the pad's LB / RB step through GPU drivers, FEX, DXVK and VKD3D-Proton, wrapping around. */
/** On the Components page the pad's LB / RB step through FEX, DXVK and VKD3D-Proton, wrapping around. */
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
val all = listOf(com.droiddeck.launcher.ui.GPU_TAB) + ComponentsManager.COMPONENTS
val all = ComponentsManager.COMPONENTS
val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1
components.compComp = all[(all.indexOf(components.compComp).coerceAtLeast(0) + step) % all.size]
}
@@ -686,11 +648,6 @@ class MainActivity : ComponentActivity() {
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
}
refreshPhantomStatus()
syncLossless()
// Opening the app and coming back from a session both land here.
updates.onResume()
// Auto keeps this GPU's recommended driver pair installed and set: once per app start.
drivers.ensureAuto(force = false)
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
// session has just ended). Cheap when nothing is queued.
if (!SessionState.running) Thread({
@@ -721,11 +678,6 @@ class MainActivity : ComponentActivity() {
refreshSecondScreenDisplays()
}
override fun onDestroy() {
updates.unregister()
super.onDestroy()
}
override fun onStop() {
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
// The session covers the page by now; coming back finds it as it was.
@@ -817,16 +769,14 @@ class MainActivity : ComponentActivity() {
)
}
private fun openComponents(focusContent: Boolean = true, tab: String? = null) {
private fun openComponents(focusContent: Boolean = true) {
focusComponentsContent = focusContent
if (tab != null) components.compComp = tab
settingsMode = null
showPerformance = false
showProtons = false
showMapping = false
showComponents = true
components.refreshComponents(snapshotFirst = true)
drivers.refreshDrivers()
}
private fun importComponent(uri: Uri) {
@@ -861,22 +811,6 @@ class MainActivity : ComponentActivity() {
onRefresh = { components.refreshComponentCatalog() },
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
onBack = { showComponents = false },
gpu = drivers.state(),
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
onAuto = { on -> drivers.setMode(on) },
onPair = { key -> drivers.selectPair(key) },
onRefresh = { if (drivers.mode == SessionPrefs.GPU_DRIVERS_AUTO) drivers.ensureAuto(force = true) else drivers.checkLatestTurnip() },
// Picking one driver on its own is Manual: Auto would put its pair back.
onSelectLinux = { id -> drivers.selectDriver(id, linux = true) },
onSelectAndroid = { id -> drivers.selectDriver(id, linux = false) },
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip or Android + Linux bundle)")) },
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip or Android + Linux bundle)")) },
onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a driver zip or an Android + Linux bundle")) },
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
),
)
}
@@ -943,8 +877,10 @@ class MainActivity : ComponentActivity() {
ModeSettingsPage(
ModeSettings(
mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit,
gpuDrivers = drivers.summary(),
hdr = hdrOn, hdrReason = hdrReason,
linuxRows = drivers.linuxRows,
linuxSelected = if (mode == SessionService.MODE_STEAM) drivers.linuxSteam else drivers.linuxDesktop,
androidRows = drivers.androidRows, androidSelected = drivers.androidSelected,
touchMode = touchMode,
suspendPolicy = suspendPolicy,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
@@ -952,7 +888,6 @@ class MainActivity : ComponentActivity() {
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
clientDirectAudio = clientDirectAudio,
forceFullscreen = if (mode == SessionService.MODE_STEAM) forceFullscreen else null,
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
mic = if (mode == SessionService.MODE_STEAM) mic else null,
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
@@ -960,12 +895,13 @@ class MainActivity : ComponentActivity() {
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
addedGamesArt = addedGamesArt,
linuxDownloads = drivers.linuxDownloads, androidDownloads = drivers.androidDownloads, releaseStatus = drivers.releaseStatus,
releaseChecking = drivers.releaseChecking, canRestoreBundled = drivers.canRestoreBundled,
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
@@ -976,8 +912,15 @@ class MainActivity : ComponentActivity() {
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); drivers.refreshDrivers() },
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
onRefreshReleases = { drivers.checkLatestTurnip() },
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); drivers.refreshDrivers() },
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
@@ -988,7 +931,6 @@ class MainActivity : ComponentActivity() {
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on },
onForceFullscreen = { on -> SessionPrefs.setForceFullscreen(this, on); forceFullscreen = on },
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
onMic = { on ->
SessionPrefs.setMicEnabled(this, on)
mic = on
@@ -1010,7 +952,6 @@ class MainActivity : ComponentActivity() {
steamDeckMode = on
steamChannel = SessionPrefs.steamChannel(this)
},
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on)
@@ -1044,8 +985,7 @@ class MainActivity : ComponentActivity() {
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores,
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, guestHostname = guestHostname, phantomWarning = phantomWarning,
prootNoSeccomp = prootNoSeccomp, guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
@@ -1053,9 +993,7 @@ class MainActivity : ComponentActivity() {
onNoGlError = { on -> SessionPrefs.setNoGlError(this, on); noGlError = on },
onNoXalia = { on -> SessionPrefs.setNoXalia(this, on); noXalia = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
clientCores = if (on) clientCores + core else clientCores - core
@@ -1070,20 +1008,10 @@ class MainActivity : ComponentActivity() {
}
/** The added games as the settings page lists them; a scan of the folder, on this thread (one level, small). */
/** The added games for the session settings: a folder walk, so off the main thread. */
private fun refreshAddedGames() {
Thread({
val games = scanAddedGames()
ui.post { addedGames = games; fetchAddedGameArt() }
}, "added-games").start()
}
/** Walks the added-games folders, which can sit on slow shared storage or an SD card. */
private fun scanAddedGames() = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, g.candidates.map { c -> c.path to c.name }.distinctBy { it.first })
}
private fun fetchAddedGameArt() {
addedGames = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, g.candidates.map { c -> c.path to c.name }.distinctBy { it.first })
}
// Art the games do not have yet, from Steam's store, off the main thread; the rail
// redraws when something arrives.
if (SessionPrefs.addedGamesArt(this) && !artFetchRunning) {
@@ -1104,18 +1032,18 @@ class MainActivity : ComponentActivity() {
showProtons = false
showComponents = false
showMapping = false
drivers.refreshDrivers()
resolutionCap = SessionPrefs.resolutionCap(this, mode)
customResolution = SessionPrefs.customResolution(this, mode)
fexPreset = SessionPrefs.fexPreset(this)
steamChannel = SessionPrefs.steamChannel(this)
steamDeckMode = SessionPrefs.steamDeckMode(this)
mangoapp = SessionPrefs.mangoapp(this)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
addedGamesDirs = SessionPrefs.addedGamesDirs(this)
refreshAddedGames()
shapeMode = SessionPrefs.shapeMode(this)
hdrOn = SessionPrefs.hdr(this, mode)
fpsLimit = SessionPrefs.fpsLimit(this, mode)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
touchMode = SessionPrefs.touchMode(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
@@ -1124,30 +1052,16 @@ class MainActivity : ComponentActivity() {
directAudio = SessionPrefs.directAudio(this)
clientDirectAudio = SessionPrefs.clientDirectAudio(this)
forceFullscreen = SessionPrefs.forceFullscreen(this)
stretch16x9 = SessionPrefs.stretch16x9(this)
mic = SessionPrefs.micEnabled(this)
renderer = SessionPrefs.desktopRenderer(this)
gameStorage = SessionPrefs.gameStorage(this)
storageOptions = GameStorage.options(this).map { it.label to it.path }
if (mode == SessionService.MODE_STEAM) {
decky.deckyInstalled = DeckyManager.installed(this)
decky.deckySupervisor = DeckyManager.supervisorEnabled(this)
decky.refreshDecky()
}
settingsMode = mode
// The page opens at once, on what was last read; the slow part (driver files, a walk of the
// added-games folders, the storage volumes) lands while it animates in.
Thread({
drivers.refreshDrivers()
val games = scanAddedGames()
val storage = GameStorage.options(this).map { it.label to it.path }
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
ui.post {
addedGames = games
storageOptions = storage
if (mode == SessionService.MODE_STEAM) {
decky.deckyInstalled = deckyInstalled
decky.deckySupervisor = deckySupervisor
decky.refreshDecky()
}
fetchAddedGameArt()
}
}, "mode-settings").start()
}
/** A second Steam library, proven writable first; "" = internal only. */
@@ -1175,9 +1089,7 @@ class MainActivity : ComponentActivity() {
zinkLazy = SessionPrefs.zinkLazy(this)
noXalia = SessionPrefs.noXalia(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
}
@@ -1200,9 +1112,6 @@ class MainActivity : ComponentActivity() {
} else null
// The libraries, off the main thread: manifests and a folder scan.
Thread({
// One update with the whole list: the wall places games by their position in it, so a
// partial list first would shuffle every capsule when the rest arrived. LibraryCache
// covers the wait.
val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art ->
Library.SteamGame(
@@ -1213,9 +1122,7 @@ class MainActivity : ComponentActivity() {
}
} else emptyList()
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
val all = games.distinctBy { it.gameId }
if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all)
ui.post { steamGames = all; emulatorList = emus }
ui.post { steamGames = games.distinctBy { it.gameId }; emulatorList = emus }
// Box art for the games that have none, fetched after the list is up; the list is
// rebuilt once if any was found.
if (!OfflineMode.enabled(this) && CoverArt.fetchMissing(this, emus.flatMap { it.games })) {
@@ -1,6 +1,5 @@
package com.droiddeck.launcher
import androidx.compose.foundation.layout.fillMaxSize
import android.hardware.input.InputManager
import android.hardware.display.DisplayManager
import android.content.Intent
@@ -24,7 +23,6 @@ import android.widget.FrameLayout
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -34,10 +32,9 @@ import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.files.InAppFilePicker
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.gpu.LsfgNative
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.input.EvdevKeys
import com.droiddeck.launcher.input.KeyboardHost
@@ -98,25 +95,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var padMotion: com.droiddeck.launcher.input.PadMotion? = null
/** Between onResume and onPause. */
private var resumed = false
private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed") } }
/**
* A Deck's controller is there from the moment it boots, and the client looks for it once, as
* it starts. The ring behind the Deck (libfakeinput's /dev/hidraw16) opens on the pad's first
* input otherwise - on a phone with nothing attached, the first touch of the on-screen
* controls, seconds after the client had looked, found no controller and never set the touch
* mode, so its interface took a finger as a mouse. Opened as soon as the session settles on a
* Deck instead.
*/
private fun openDeckRing(why: String) {
val deck = SessionState.deckPad
val opened = if (deck) padBridge?.start() else null
Log.i(TAG, "deck ring ($why): deck pad $deck" + when (opened) {
null -> ", left for first input"
true -> ", ring open"
false -> ", ring NOT open"
})
}
private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion() } }
/** Motion is read while the session shows and only if the pad is a Deck controller - which
* the service can decide after this activity has resumed (SessionState.deckPadListener). */
@@ -181,10 +160,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var quitFrom by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null)
/** Left behind that flood: the front end opens on its blue, so no sink of our own. */
private var quitFlooded = false
/** Leaving behind a flood spreading out of the throbber (FloodSpread); see finish(). */
private var leaving by mutableStateOf(false)
/** Close without the leaving flood: a retry opens a fresh session at once. */
private var closeAtOnce = false
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
private var drawerPage by mutableIntStateOf(0)
@@ -194,11 +169,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var pcKeyboardOpen by mutableStateOf(false)
private var hudOn by mutableStateOf(true)
private var fillScreen by mutableStateOf(true)
private var lossless by mutableStateOf(Lossless.State.NONE)
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
private var frameGenLabel by mutableStateOf("Off")
private var frameGenEngine by mutableStateOf(FrameGen.ENGINE_OFF)
private var frameGenMultiplier by mutableStateOf(2)
private var fexPreset by mutableStateOf("")
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
@@ -213,24 +186,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayChanged(displayId: Int) {
followPanelRefresh(displayId)
refreshSecondScreenDisplays()
}
}
/**
* The panel's rate, followed for the rest of the session. It is read once at start, and a
* panel that drops from 120 to 60 Hz later (battery saver, heat, a vendor overriding the mode
* asked for) left the compositor telling gamescope every frame took 8.3 ms, so the client and
* its games paced against a vblank that no longer came. (WinNative 53836ca9.)
*/
private fun followPanelRefresh(displayId: Int) {
if (!CompositorHost.isStarted) return
val display = (if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay) ?: return
if (display.displayId != displayId) return
val hz = display.refreshRate
if (hz > 1f) WaylandCompositor.nativeSetOutputRefreshRate(hz)
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
}
private var isHomeApp by mutableStateOf(false)
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
@@ -241,24 +197,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
* press, and a user without one must not be left with no way to answer Big Picture.
*/
private val deviceListener = object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
logInputDevice("connected", deviceId)
updateOnScreenControls()
}
override fun onInputDeviceRemoved(deviceId: Int) {
Log.i(TAG, "input device $deviceId disconnected")
updateOnScreenControls()
}
override fun onInputDeviceAdded(deviceId: Int) = updateOnScreenControls()
override fun onInputDeviceRemoved(deviceId: Int) = updateOnScreenControls()
override fun onInputDeviceChanged(deviceId: Int) = updateOnScreenControls()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
// A Flatpak app or AppImage is named by its arguments, which the name lookup reads here.
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
SessionEvents.begin(this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
}
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
@@ -268,15 +215,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionEvents.record("agent.start_requested", mapOf("mode" to SessionState.mode))
}
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
// Game-tier power policy for the whole session: the panel's fastest mode (one the frame cap
// divides, when there is a cap), and the OS told it is in gameplay. Logged so a slow device
// says why. The cap is the session's: an activity re-created mid-session keeps it.
if (!SessionState.running) {
SessionState.fpsLimit = SessionPrefs.fpsLimit(
this, SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM),
)
}
Log.i(TAG, "perf: " + PerfMode.apply(this, SessionState.fpsLimit))
// Game-tier power policy for the whole session: the panel's fastest mode, and the OS told
// it is in gameplay. Logged so a slow device says why.
Log.i(TAG, "perf: " + PerfMode.apply(this))
goFullscreen()
// The device's volume keys change the stream the session plays on (the relay and
// PulseAudio are media playback); they are never forwarded to the guest.
@@ -300,7 +241,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
}
SessionState.deckPadListener = deckPadListener
openDeckRing("activity created")
// A player on the pad or the on-screen controls has no use for the mouse arrow; the next
// touchpad or mouse move brings it back (showCursor), once the pad has been quiet a moment.
bridge.setOnPlayerInput {
@@ -373,12 +313,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun createSessionOverlay(): ComposeView = ComposeView(this).apply {
isFocusable = true
isFocusableInTouchMode = true
// Compose draws each control's focus ring. Android's default highlight would cover
// this full-screen host and remain as a white veil after the drawer closes.
defaultFocusHighlightEnabled = false
setContent {
DroidDeckTheme {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (hud.text.isNotEmpty()) HudText(hud.text)
@@ -400,7 +336,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// Opening the drawer takes the controller away from the game: release its pad.
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
if (drawerOpen) {
syncLossless()
padBridge?.releaseAll()
androidx.compose.runtime.withFrameNanos { }
val requested = sessionOverlay.requestFocus()
@@ -424,8 +359,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
androidApps = androidApps,
hudOn = hudOn,
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
frameGen = frameGen,
lossless = lossless,
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
shapeMode = shapeMode, fexPreset = fexPreset,
@@ -434,15 +369,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
onFrameGenPick = { mode ->
FrameGen.set(this@SessionActivity, mode)
onFrameGenPick = { engine, multiplier ->
FrameGen.set(this@SessionActivity, engine, multiplier)
readPrefs()
applyFrameGen()
},
onImportLossless = {
pickLossless.launch(InAppFilePicker.buildIntent(
this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title)))
},
onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() },
onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
@@ -504,10 +435,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
title = pausedTitle(),
onResume = { SessionService.resume(this@SessionActivity) },
)
if (leaving) com.droiddeck.launcher.ui.FloodSpread(
com.droiddeck.launcher.ui.LocalPalette.current.signal,
ball = if (loading.visible) com.droiddeck.launcher.ui.ThrobberSpot.ball else null,
) { completeLeave() }
quitFrom?.let { from ->
val error = androidx.compose.material3.MaterialTheme.colorScheme.error
com.droiddeck.launcher.ui.LaunchFlood(
@@ -518,7 +445,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
}
}
}
private fun refreshHomeApp() {
@@ -625,9 +551,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun shareCurrentSessionLogs() {
// Once a session has ended its folder has been handed on (SessionPaths.take), and the
// ended screen's Share logs is for that one.
val folder = SessionPaths.current() ?: SessionPaths.lastEnded()
val folder = SessionPaths.current()
if (folder == null || !folder.isDirectory) {
Toast.makeText(this, "No logs for this session.", Toast.LENGTH_LONG).show()
return
@@ -654,7 +578,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
hudOn = SessionPrefs.hudEnabled(this)
fillScreen = SessionPrefs.forceFullscreen(this)
touchMode = SessionPrefs.touchMode(this)
frameGen = FrameGen.mode(this)
frameGenLabel = FrameGen.label(this)
frameGenEngine = FrameGen.engine(this)
frameGenMultiplier = FrameGen.multiplier(this)
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
oscMode = SessionPrefs.oscMode(this)
@@ -849,7 +775,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
CompositorHost.startOrAttach(
holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), SessionState.fpsLimit,
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(),
)
if (!SessionState.running) SessionEvents.record("compositor.started")
// The service owns everything below the compositor. It is started whenever no session is
@@ -958,35 +884,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val hz = refreshHz()
Thread({
val problem = FrameGen.apply(this, hz)
val state = Lossless.state(this)
runOnUiThread {
lossless = state
if (problem != null) Toast.makeText(this, problem, Toast.LENGTH_LONG).show()
}
if (problem != null) runOnUiThread { Toast.makeText(this, problem, Toast.LENGTH_LONG).show() }
}, "frame-gen").start()
}
/** A Lossless Scaling installed or updated in Steam during the session is taken when the drawer opens. */
private fun syncLossless() {
Thread({
Lossless.sync(this)
val state = Lossless.state(this)
runOnUiThread { lossless = state }
}, "lossless-sync").start()
}
private fun importLossless(dll: File) {
Thread({
val message = Lossless.message(this, Lossless.import(this, dll))
val state = Lossless.state(this)
runOnUiThread {
lossless = state
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
if (FrameGen.engine(this) == FrameGen.ENGINE_LSFG) applyFrameGen()
}
}, "lossless-import").start()
}
// ── Session state ───────────────────────────────────────────────────────────────────────
/** Keeps the loading overlay current from the session log, and its clock moving. */
@@ -1070,7 +971,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
/** The same start again, in a fresh activity: the ended one keeps no session to reuse. */
private fun retrySession() {
val again = Intent(intent)
closeAtOnce = true
finish()
startActivity(again)
}
@@ -1356,8 +1256,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
*/
private fun syncClientCursor(): Boolean {
if (!CompositorHost.isStarted) return false
// Asked on every pointer move; the image is copied only when the client has changed it.
if (WaylandCompositor.nativeCursorSerial() == cursorSerial) return false
val n = WaylandCompositor.nativeCursorSnapshot(cursorBuf)
if (n < 6) return false
val serial = cursorBuf[0]
@@ -1568,14 +1466,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
/** The mode decides which controls appear; `droiddeck-osc` in Downloads still overrides. */
/** Which controller the session has, so a pad report says what was plugged in and when. */
private fun logInputDevice(what: String, deviceId: Int) {
val d = InputDevice.getDevice(deviceId) ?: return
if (!PadBridge.isFromController(d)) return
Log.i(TAG, String.format(java.util.Locale.ROOT, "controller %s: \"%s\" (%04x:%04x, id %d, sources 0x%x)",
what, d.name, d.vendorId, d.productId, d.id, d.sources))
}
private fun updateOnScreenControls() {
val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc")
.takeIf { it.isFile }
@@ -1744,41 +1634,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
finish()
}
/**
* Every way out on screen (backing out of the loading screen, closing the ended screen, the
* session ending) leaves as a session arrives, in reverse: the blue spreads out of the
* throbber's ball, or the middle of the screen once a game is up, and the front end opens on it
* and draws it back into the button the session came from. Off screen, or with animations
* off, it just closes.
*/
/** Leaving the session sinks its surface back down onto the front end. */
override fun finish() {
if (!quitFlooded && !closeAtOnce && com.droiddeck.launcher.ui.Motion.scale != 0f &&
lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) {
if (!leaving) {
leaving = true
// Should the flood never get its frames, the session still closes.
uiHandler.postDelayed({ completeLeave() }, LEAVE_TIMEOUT_MS)
}
return
}
super.finish()
if (quitFlooded) overridePendingTransition(0, 0)
else overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
}
/** The screen is all blue: close onto the front end, which opens on the same blue. */
private fun completeLeave() {
if (isFinishing) return
val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal
com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb())
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb()))
quitFlooded = true
finish()
}
companion object {
/** How long the leaving flood may take before the session closes without it. */
private const val LEAVE_TIMEOUT_MS = 1_500L
private const val TAG = "SessionActivity"
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
private const val CURSOR_PAD_HOLD_MS = 1200L
@@ -1,142 +0,0 @@
package com.droiddeck.launcher
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageInstaller
import android.os.Build
import android.os.Handler
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.ui.UpdatesActions
import com.droiddeck.launcher.ui.UpdatesState
import com.droiddeck.launcher.update.AppUpdates
import com.droiddeck.launcher.update.SelfInstaller
/**
* The Updates page's state: the channels' latest builds, the one followed, and an update being
* downloaded or installed. Checked when the launcher comes to the front - opening the app, and
* coming back from a session - at most once a minute.
*/
internal class UpdatesMenu(private val activity: Activity, private val ui: Handler) {
// Read in start(): the activity has no context yet while its fields are made.
var catalog by mutableStateOf<AppUpdates.Catalog?>(null)
var follow by mutableStateOf(AppUpdates.Follow(AppUpdates.Channel.STABLE))
var checking by mutableStateOf(false)
var error by mutableStateOf<String?>(null)
var stage by mutableStateOf<String?>(null)
var percent by mutableIntStateOf(-1)
var askPermission by mutableStateOf(false)
// An install waiting for the user to allow "Install unknown apps"; it goes on when they come back.
private var pending: AppUpdates.Release? = null
private var lastCheck = 0L
private var request = 0
fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission)
fun actions() = UpdatesActions(
onCheck = { check(force = true) },
onFollow = ::choose,
onInstall = ::install,
onAllowInstalls = {
askPermission = false
runCatching { activity.startActivity(SelfInstaller.permissionIntent(activity)) }
.onFailure { error = "Couldn't open Android's \"Install unknown apps\" setting"; pending = null }
},
onDismissPermission = { askPermission = false; pending = null },
)
val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow)
/** On every return to the launcher: go on with an install the user just allowed, and check if due. */
fun onResume() {
pending?.let { r ->
if (SelfInstaller.canInstall(activity)) { pending = null; install(r) }
}
if (!SessionState.running) check(force = false)
}
fun check(force: Boolean) {
if (checking || stage != null) return
val now = System.currentTimeMillis()
if (!force && now - lastCheck < 60_000) return
lastCheck = now
val id = ++request
checking = true
Thread({
val result = runCatching { AppUpdates.refresh(activity) }
ui.post {
if (id != request) return@post
checking = false
result.onSuccess {
catalog = it
follow = AppUpdates.follow(activity, it)
error = null
}.onFailure { if (force) error = "Couldn't check: ${it.message ?: it.javaClass.simpleName}" }
}
}, "app-updates").start()
}
private fun choose(f: AppUpdates.Follow) {
AppUpdates.setFollow(activity, f)
follow = f
error = null
}
private fun install(r: AppUpdates.Release) {
if (stage != null) return
val apk = r.apk ?: run { error = "This build has no download for this copy of DroidDeck"; return }
AppUpdates.installBlock(r)?.let { error = it; return }
if (SessionState.running) { error = "Stop the running session first, then update"; return }
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
error = null
stage = "Downloading"
percent = 0
Thread({
val result = runCatching {
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
ui.post { stage = "Installing"; percent = -1 }
SelfInstaller.install(activity, file)
}
result.onFailure { e -> ui.post { stage = null; error = e.message ?: "The update failed" } }
}, "app-update-install").start()
}
/** PackageInstaller's answer: Android's confirm prompt to show, or why it failed. Success restarts the app. */
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
if (confirm == null) { stage = null; error = "Android didn't offer to install the update"; return }
stage = "Waiting for you to confirm"
activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
PackageInstaller.STATUS_SUCCESS -> stage = null
else -> {
stage = null
error = SelfInstaller.describeFailure(status, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE))
}
}
}
}
/** From onCreate: the last check, the channel followed, and PackageInstaller's answers. */
fun start() {
catalog = AppUpdates.cached(activity)
follow = AppUpdates.follow(activity, catalog)
val filter = IntentFilter(SelfInstaller.ACTION_STATUS)
if (Build.VERSION.SDK_INT >= 33) activity.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
else activity.registerReceiver(receiver, filter)
}
fun unregister() {
runCatching { activity.unregisterReceiver(receiver) }
}
}
@@ -113,24 +113,19 @@ object DeviceReport {
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
h("Drivers")
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
k("Driver mode", SessionPrefs.gpuDriverMode(context) +
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)))?.let { " (recommended pair: $it)" } ?: ""))
val turnip = TurnipDriver(context)
val androidChoice = SessionPrefs.androidDriver(context)
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice)
k(" name / version", "${turnip.displayName(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)} ${turnip.driverVersion(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)}".trim())
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
val lm = LinuxVulkanDriverManager(context)
run {
val id = SessionPrefs.linuxDriver(context)
for (m in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
val id = SessionPrefs.linuxDriver(context, m)
val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() +
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]"
k("Linux driver", label)
k("Linux driver ($m)", label)
}
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
@@ -154,11 +149,9 @@ object DeviceReport {
k("Skip xalia", SessionPrefs.noXalia(context))
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
k("Guest host name", SessionPrefs.guestHostname(context))
k("DirectAudio for games", SessionPrefs.directAudio(context))
k("Stretch games to fill", SessionPrefs.forceFullscreen(context))
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic")
k("Microphone", SessionPrefs.micEnabled(context))
k("On-screen controls", SessionPrefs.oscMode(context))
@@ -175,7 +168,7 @@ object DeviceReport {
h("Device switch files in Download")
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
"droiddeck-osc", "droiddeck-no-pad",
"droiddeck-osc", "droiddeck-no-pad", "droiddeck-pad-log",
"droiddeck-no-hud", "droiddeck-wlr-renderer")) {
val f = File(Environment.getExternalStorageDirectory(), "Download/$name")
if (f.isFile) k(name, FileUtils.readString(f)?.trim()?.replace('\n', ' ')?.ifEmpty { "(present, empty)" } ?: "(present)")
@@ -12,8 +12,6 @@ import java.util.zip.CRC32
/** Windows game folders shared with the Steam session. */
object AddedGames {
private const val TAG = "AddedGames"
private const val LIBRARY = "/mnt/droiddeck-sd"
private const val LEGACY_LIBRARY = "/mnt/bannerlator-sd"
class Game(
val folder: File, val name: String, val exe: File, val guestExe: String, val guestDir: String,
@@ -67,7 +65,7 @@ object AddedGames {
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
}
GameStorage.effective(context)?.let { lib ->
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
if (path.startsWith("${lib.path}/")) return "/mnt/bannerlator-sd/" + path.removePrefix("${lib.path}/")
}
return null
}
@@ -96,33 +94,11 @@ object AddedGames {
)
for (dir in folders.distinctBy { it.absolutePath }) {
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
val steamInstalls = steamInstallDirs(dir)
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
if (folder.name.lowercase() in steamInstalls) continue
scanGame(context, folder, out)
}
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) scanGame(context, folder, out)
}
return out.distinctBy { it.folder.canonicalPath }
}
/**
* The folders under a library's steamapps/common that a manifest beside it already claims.
* Steam lists those itself, so a shortcut would only add a non-Steam copy of the game. Steam
* may lowercase installdir on Android's case-insensitive storage, so names compare lowercased.
*/
internal fun steamInstallDirs(dir: File): Set<String> {
val steamapps = dir.parentFile?.takeIf { dir.name == "common" && it.name == "steamapps" } ?: return emptySet()
return steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }
.orEmpty()
.mapNotNull { manifest ->
runCatching { INSTALL_DIR.find(manifest.readText())?.groupValues?.get(1)?.trim()?.lowercase() }.getOrNull()
}
.filter { it.isNotEmpty() }
.toSet()
}
private val INSTALL_DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
run {
val candidates = candidates(folder)
@@ -132,8 +108,7 @@ object AddedGames {
if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return }
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
val name = folder.name
// Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put.
val crc = CRC32().apply { update(("\"${guestExe.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
val crc = CRC32().apply { update(("\"$guestExe\"" + name).toByteArray()) }.value
val appId = crc or 0x80000000L
val steamRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
val steamId = steamRoute(steamRoot, appId)
@@ -5,7 +5,6 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SecondaryLibrary
import java.io.File
/**
@@ -85,11 +84,7 @@ object Library {
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
fun protonPrefix(context: Context, appId: Long, preferredLibrary: File? = null): File? {
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
val secondary = GameStorage.effective(context)?.let { File(it.path) }
fun prefixRoot(root: File): File = if (secondary != null && root.canonicalPath == secondary.canonicalPath)
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
else root
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first }).map(::prefixRoot)
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first })
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
return roots.asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
@@ -172,12 +167,11 @@ object Library {
/** The emulator's name for a program path from the rail ("ARMSX2"), or null. */
fun nameForProgram(program: String?): String? =
if (program == com.droiddeck.launcher.runtime.FlatpakManager.LAUNCHER || program == com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER ||
program == com.droiddeck.launcher.runtime.UserApps.SCRIPT_LAUNCHER) {
if (program == com.droiddeck.launcher.runtime.FlatpakManager.LAUNCHER || program == com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER) {
com.droiddeck.launcher.session.SessionState.programArgs.firstOrNull()?.let { flatpakNames[it] ?: it.substringAfterLast('.') }
} else specs.firstOrNull { it.program == program }?.name
/** Added apps' names by Flatpak id or directory, as launched: the session only knows that. */
/** Flatpak apps' and AppImages' names by id or directory, as launched: the session only knows that. */
val flatpakNames = java.util.concurrent.ConcurrentHashMap<String, String>()
/**
@@ -1,49 +0,0 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* The last game list the front end showed, kept in the app's files so the next start draws the
* Steam wall on its first frame. Building the list reads every manifest and walks the added-games
* folders, which can take a second or more; the fresh list replaces this one when it is ready.
*/
object LibraryCache {
private const val TAG = "LibraryCache"
private fun file(context: Context) = File(context.filesDir, "library-cache.json")
fun load(context: Context): List<Library.SteamGame> = runCatching {
val f = file(context)
if (!f.isFile) return emptyList()
val array = JSONArray(f.readText())
List(array.length()) { i ->
val o = array.getJSONObject(i)
Library.SteamGame(
appId = o.getInt("appId"), name = o.getString("name"), art = o.file("art"),
library = o.getString("library"), gameId = o.getLong("gameId"), hero = o.file("hero"),
lastPlayed = o.optLong("lastPlayed"), gameFiles = o.file("gameFiles"), protonPrefix = o.file("protonPrefix"),
)
}
}.getOrElse { e -> Log.w(TAG, "unreadable, ignored: ${e.message}"); emptyList() }
fun save(context: Context, games: List<Library.SteamGame>) {
runCatching {
val array = JSONArray()
for (g in games) array.put(
JSONObject().put("appId", g.appId).put("name", g.name).put("library", g.library).put("gameId", g.gameId)
.put("lastPlayed", g.lastPlayed).putFile("art", g.art).putFile("hero", g.hero)
.putFile("gameFiles", g.gameFiles).putFile("protonPrefix", g.protonPrefix),
)
val f = file(context)
val tmp = File(f.path + ".tmp")
tmp.writeText(array.toString())
tmp.renameTo(f)
}.onFailure { e -> Log.w(TAG, "not saved: ${e.message}") }
}
private fun JSONObject.file(key: String): File? = optString(key).takeIf { it.isNotEmpty() }?.let(::File)
private fun JSONObject.putFile(key: String, f: File?): JSONObject = if (f == null) this else put(key, f.path)
}
@@ -1,196 +0,0 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.net.Uri
import android.util.Log
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.util.zip.ZipInputStream
/**
* An all-in-one driver package: one zip carrying both halves of a matched pair, the display
* (Android, bionic) driver in one directory and the runtime (Linux, glibc) driver in another,
* indexed by a root `manifest.json` - DroidDeck's own DD-Turnip releases (Droid-Deck/Drivers):
*
* ```
* manifest.json {"package", "version", "drivers": {"android": {"path"}, "linux": {"path"}}}
* android/ meta.json (AdrenoTools) + libvulkan_freedreno.so
* linux/ meta.json + libvulkan_freedreno.so
* ```
*
* Installing one puts each half through its own importer, with that importer's checks, and
* remembers the two as one bundle: picking either half sets both, and deleting either deletes both,
* so a bundle is always used whole. Zips of the older kind, one driver each, never reach this.
*/
object DriverBundle {
private const val TAG = "DriverBundle"
private const val PREFS = "driver_bundles"
private const val MANIFEST = "manifest.json"
/** Refuses a zip that unpacks to more than this: both halves together are about 30 MB. */
private const val MAX_BYTES = 512L shl 20
class Manifest(val name: String, val version: String, val tag: String, val androidPath: String, val linuxPath: String)
/** An installed bundle: [androidId] in TurnipDriver's list, [linuxId] in LinuxVulkanDriverManager's. */
class Bundle(val id: String, val name: String, val version: String, val androidId: String, val linuxId: String) {
/** "DD-Turnip 0.1.0". */
val label: String get() = if (version.isEmpty()) name else "$name $version"
}
/** The manifest of a bundle, or null when [json] is not one (both halves, in two directories). */
fun parseManifest(json: JSONObject): Manifest? {
val drivers = json.optJSONObject("drivers") ?: return null
val android = cleanPath(drivers.optJSONObject("android")?.optString("path").orEmpty()) ?: return null
val linux = cleanPath(drivers.optJSONObject("linux")?.optString("path").orEmpty()) ?: return null
if (android == linux) return null
return Manifest(
json.optString("package").ifEmpty { "Driver bundle" }, json.optString("version"),
json.optString("tag"), android, linux,
)
}
private fun cleanPath(path: String): String? {
val p = path.trim().trim('/')
return p.takeIf { it.isNotEmpty() && it.split('/').none { part -> part.isEmpty() || part == "." || part == ".." } }
}
/** True when the zip at [uri] is a bundle rather than a single driver. */
fun isBundle(context: Context, uri: Uri): Boolean = try {
context.contentResolver.openInputStream(uri)?.use { input ->
ZipInputStream(input).use { zip ->
generateSequence { zip.nextEntry }.firstOrNull { !it.isDirectory && it.name == MANIFEST }
?.let { parseManifest(JSONObject(zip.readBytes().toString(Charsets.UTF_8))) } != null
}
} ?: false
} catch (e: Exception) {
Log.w(TAG, "reading $uri as a bundle", e)
false
}
/**
* Install both halves of the bundle at [uri]. Both or neither: a half that is refused removes
* the one already in. Throws [IllegalArgumentException] with a user-facing reason when the zip
* is not a usable bundle, [IOException] on read failures.
*/
fun install(context: Context, uri: Uri): Bundle {
val work = File(context.cacheDir, "bundle-${System.nanoTime()}")
val td = TurnipDriver(context)
val lm = LinuxVulkanDriverManager(context)
var androidId: String? = null
try {
unzip(context, uri, work)
val manifest = File(work, MANIFEST).takeIf { it.isFile }
?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() }
?: throw IllegalArgumentException("Not a driver bundle: no manifest.json naming an android and a linux driver")
val androidDir = File(work, manifest.androidPath)
val linuxDir = File(work, manifest.linuxPath)
val androidStage = td.newStagingDir()
androidId = try {
androidDir.listFiles()?.filter { it.isFile }?.forEach { it.copyTo(File(androidStage, it.name)) }
td.adopt(androidStage, manifest.name)
} catch (e: Exception) {
FileUtils.delete(androidStage)
throw e
}
val linuxStage = lm.newStagingDir()
val linuxId = try {
val library = linuxDir.listFiles()?.firstOrNull { it.isFile && it.name.startsWith("libvulkan_freedreno") && it.name.endsWith(".so") }
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.LIB_NAME))
val meta = File(linuxDir, LinuxVulkanDriverManager.META_NAME).takeIf { it.isFile }
?.let { runCatching { JSONObject(FileUtils.readString(it)) }.getOrNull() }
lm.adopt(linuxStage, library?.name, meta, manifest.name)
} catch (e: Exception) {
FileUtils.delete(linuxStage)
throw e
}
val base = LinuxVulkanDriverManager.sanitizeId(manifest.tag.ifEmpty { "${manifest.name}-${manifest.version}" })
val saved = registry(context)
var id = base
var n = 2
while (saved.contains(id)) id = "$base-${n++}"
val bundle = Bundle(id, manifest.name, manifest.version, androidId, linuxId)
saved.edit().putString(id, JSONObject().put("name", bundle.name).put("version", bundle.version)
.put("android", androidId).put("linux", linuxId).toString()).apply()
Log.i(TAG, "installed bundle $id: display $androidId, runtime $linuxId")
return bundle
} catch (e: Exception) {
androidId?.let { td.remove(it) }
throw e
} finally {
FileUtils.delete(work)
}
}
private fun unzip(context: Context, uri: Uri, dest: File) {
val root = dest.canonicalFile
var total = 0L
context.contentResolver.openInputStream(uri)?.use { input ->
ZipInputStream(input).use { zip ->
for (entry in generateSequence { zip.nextEntry }) {
if (entry.isDirectory) continue
val out = File(root, entry.name).canonicalFile
if (!out.path.startsWith(root.path + File.separator)) throw IllegalArgumentException("Not a driver bundle: ${entry.name} points outside it")
out.parentFile?.mkdirs()
out.outputStream().use { sink ->
val buf = ByteArray(1 shl 16)
while (true) {
val r = zip.read(buf)
if (r <= 0) break
total += r
if (total > MAX_BYTES) throw IllegalArgumentException("Not a driver bundle: it unpacks to more than ${MAX_BYTES shr 20} MB")
sink.write(buf, 0, r)
}
}
}
}
} ?: throw IOException("cannot open $uri")
}
/** Every installed bundle whose two halves are both still there. */
fun all(context: Context): List<Bundle> {
val td = TurnipDriver(context)
val lm = LinuxVulkanDriverManager(context)
return registry(context).all.mapNotNull { (id, raw) ->
runCatching {
val j = JSONObject(raw as String)
Bundle(id, j.getString("name"), j.optString("version"), j.getString("android"), j.getString("linux"))
}.getOrNull()
}.filter { td.isInstalled(it.androidId) && lm.isInstalled(it.linuxId) }.sortedBy { it.id }
}
fun get(context: Context, id: String): Bundle? = all(context).firstOrNull { it.id == id }
/** The bundle [driverId] is a half of, in the runtime list when [linux], else the display list. */
fun containing(context: Context, driverId: String, linux: Boolean): Bundle? =
all(context).firstOrNull { (if (linux) it.linuxId else it.androidId) == driverId }
/** The bundle both drivers are set to right now, if they are one. */
fun active(context: Context): Bundle? {
val android = SessionPrefs.androidDriver(context)
val linux = SessionPrefs.linuxDriver(context)
return all(context).firstOrNull { it.androidId == android && it.linuxId == linux }
}
/** Set both halves as the drivers in use. */
fun select(context: Context, bundle: Bundle) {
SessionPrefs.setAndroidDriver(context, bundle.androidId)
SessionPrefs.setLinuxDriver(context, bundle.linuxId)
}
/** Delete both halves; a driver still set to either goes back to its default. */
fun remove(context: Context, bundle: Bundle) {
TurnipDriver(context).remove(bundle.androidId)
LinuxVulkanDriverManager(context).removeDriver(bundle.linuxId)
if (SessionPrefs.linuxDriver(context) == bundle.linuxId) SessionPrefs.setLinuxDriver(context, "")
registry(context).edit().remove(bundle.id).apply()
Log.i(TAG, "removed bundle ${bundle.id}")
}
private fun registry(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}
@@ -1,112 +0,0 @@
package com.droiddeck.launcher.gpu
import com.droiddeck.launcher.gpu.GpuInfo.Family
/**
* The release drivers as matched pairs: a display build (the app's compositor, bionic) and a Linux
* build (the runtime, glibc) that were made to run together. Mixing a runtime driver carrying a
* patch with a display driver that lacks it is where the hard-to-read bugs come from, so the app
* installs and selects both halves of one pair at once.
*
* - Banners-Turnip publishes each variant as a set in every release (`Turnip-<tag><variant>.zip`
* and `...-Linux.zip`), rebuilt from upstream Mesa as it moves: the pair is one variant of the
* newest release that carries both halves.
* - WinNative ships its display (`v1.x`) and Linux (`linux-v0.x`) builds as two release lines with
* their own numbers: the pair is the newest of each, of one flavour (Balanced or Performance).
* - DroidDeck's DD-Turnip ships both halves in one zip per release (DriverBundle): the pair is the
* newest bundle, and it can never be mixed.
*/
object DriverPairs {
const val BANNER = "banner"
const val BANNER_A8XX = "banner-a8xx"
const val BANNER_710 = "banner-710-720-test"
const val BANNER_ONEUI = "banner-8g2-oneui"
const val WN_BALANCED = "wn-b"
const val WN_PERFORMANCE = "wn-p"
const val DD_TURNIP = "dd-turnip"
/** Each DD-Turnip release is its own pair: "dd-turnip:DD-Turnip-v0.1.0". */
fun ddTurnip(tag: String) = "$DD_TURNIP:$tag"
class DriverPair(
val key: String,
/** "Banners-Turnip · Adreno 6xx/7xx", "WinNative · Balanced". */
val name: String,
/** The families the pair is built for; the list only offers it on those unless asked. */
val families: Set<Family>,
val display: TurnipReleases.Asset?,
val linux: TurnipReleases.Asset?,
/** Both halves in one zip, instead of [display] and [linux]. */
val bundle: TurnipReleases.Asset? = null,
) {
val complete: Boolean get() = bundle != null || (display != null && linux != null)
/** The zips to download for the pair: the bundle, or the two halves. */
val assets: List<TurnipReleases.Asset> get() = listOfNotNull(bundle ?: display, if (bundle == null) linux else null)
/** "r4 · 1.19 + 0.1.2": the build of each half. */
val version: String
get() = listOfNotNull(bundle?.tag, display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-").removePrefix("DD-Turnip-") }
fun suits(gpu: GpuInfo) = gpu.family in families ||
(gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families))
}
private val ALL_ADRENO = setOf(Family.A6XX, Family.A7XX, Family.A7XX_LOW, Family.A8XX, Family.ADRENO_UNKNOWN)
private fun describe(key: String): Pair<String, Set<Family>> = when {
key.startsWith(DD_TURNIP) -> "DroidDeck · DD-Turnip" to ALL_ADRENO
else -> describeFixed(key)
}
private fun describeFixed(key: String): Pair<String, Set<Family>> = when (key) {
BANNER -> "Banners-Turnip · Adreno 6xx/7xx" to setOf(Family.A6XX, Family.A7XX)
BANNER_A8XX -> "Banners-Turnip · Adreno 8xx" to setOf(Family.A8XX)
BANNER_710 -> "Banners-Turnip · Adreno 710/720/722 (test)" to setOf(Family.A7XX_LOW)
BANNER_ONEUI -> "Banners-Turnip · 8 Gen 2 on One UI" to setOf(Family.A7XX)
WN_BALANCED -> "WinNative · Balanced" to ALL_ADRENO
WN_PERFORMANCE -> "WinNative · Performance" to ALL_ADRENO
else -> key to ALL_ADRENO
}
/** Every pair the last release check found, in the order the list shows them. */
fun from(check: TurnipReleases.Check?): List<DriverPair> {
val assets = check?.assets.orEmpty().filter { it.pair.isNotEmpty() }
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE)
return assets.map { it.pair }.distinct()
.sortedBy { key -> order.indexOf(key.substringBefore(':')).let { i -> if (i < 0) order.size else i } }
.map { key ->
val (name, families) = describe(key)
val halves = assets.filter { it.pair == key }
halves.firstOrNull { it.bundle }?.let { return@map DriverPair(key, name, families, null, null, it) }
// The list keeps the newest release of each half; for Banners-Turnip the two halves
// must come from the same release, so a set missing one half in its newest release
// is offered incomplete rather than mixed with an older one.
val display = halves.firstOrNull { !it.linux }
val linux = halves.firstOrNull { it.linux }
val sameRelease = !key.startsWith(BANNER) || display?.tag == linux?.tag
DriverPair(key, name, families, display, if (sameRelease) linux else null)
}
}
/**
* The pair Auto sets for [gpu], among the [pairs] the last release check found: the newest
* official DD-Turnip release on the Adreno 840 (840 and 840v2), WinNative Balanced on the other
* 8xx (Banners' A8xx builds still break on some first boots) and on an 840 while no DD-Turnip
* release is listed, the OneUI build for an 8 Gen 2 under One UI, the patched test builds for
* the 710/720/722, and upstream Banners-Turnip for the rest. Null when nothing fits (not Adreno).
*/
fun recommendedKey(gpu: GpuInfo, pairs: List<DriverPair>): String? = when (gpu.family) {
Family.NOT_ADRENO -> null
Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED
Family.A7XX_LOW -> BANNER_710
Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER
Family.A6XX -> BANNER
// KGSL gave no model: Android 16 arrived with the 8xx, so a device that new is taken as one.
Family.ADRENO_UNKNOWN -> if (android.os.Build.VERSION.SDK_INT >= 36) WN_BALANCED else BANNER
}
/** The complete DD-Turnip pair with the highest version, or null when none is listed. */
fun newestDdTurnip(pairs: List<DriverPair>): String? = pairs
.filter { it.key.startsWith("$DD_TURNIP:") && it.complete }
.maxByOrNull { p ->
Regex("""(\d+)\.(\d+)\.(\d+)$""").find(p.key)?.destructured
?.let { (major, minor, patch) -> major.toLong() * 1_000_000_000_000 + minor.toLong() * 1_000_000 + patch.toLong() } ?: -1L
}?.key
}
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.gpu
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.wayland.WaylandCompositor
/**
@@ -10,7 +9,7 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
*
* Both engines generate on gamescope's final output inside our compositor, so they work for any
* game with nothing changed in the runtime. Win-FG is our own and needs nothing; LSFG needs the
* shader chain from the user's copy of Lossless Scaling (see [Lossless]). Every compositor
* shader chain from the user's copy of Lossless Scaling (see [LsfgNative]). Every compositor
* setter is a value store on the native side, so this can be applied before the compositor is
* up and changed live from the main screen while a session runs.
*/
@@ -27,77 +26,62 @@ object FrameGen {
private const val FLOW_SCALE_WINFG = 0.60f
private const val FLOW_SCALE_LSFG = 0.80f
/** LSFG's adaptive targets: it generates as many frames as it takes to reach one. */
val ADAPTIVE_TARGETS = listOf(120, 90, 60)
private const val PREFS = "frame_gen"
/** A fixed [multiplier] (2..4), or for LSFG a [target] frame rate (0 = fixed). */
data class Mode(val engine: String, val multiplier: Int = 2, val target: Int = 0) {
companion object {
val OFF = Mode(ENGINE_OFF)
}
}
fun engine(context: Context): String =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("engine", ENGINE_OFF) ?: ENGINE_OFF
fun engine(context: Context): String = mode(context).engine
fun multiplier(context: Context): Int =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getInt("multiplier", 2).coerceIn(2, 4)
fun mode(context: Context): Mode {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val engine = prefs.getString("engine", ENGINE_OFF) ?: ENGINE_OFF
val target = prefs.getInt("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))
}
fun set(context: Context, mode: Mode) {
fun set(context: Context, engine: String, multiplier: Int) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply()
.putString("engine", engine).putInt("multiplier", multiplier).apply()
}
/** "Off", "Win-FG 2×", "LSFG 3×", "LSFG Adaptive 90". */
fun label(context: Context): String = label(context, mode(context))
/** "Off", "Win-FG 2×", "LSFG 3×" - for the main screen. */
fun label(context: Context): String = label(engine(context), multiplier(context))
fun label(context: Context, mode: Mode): String = when {
mode.engine == ENGINE_WINFG -> context.getString(R.string.frame_gen_winfg, mode.multiplier)
mode.engine == ENGINE_LSFG && mode.target > 0 -> context.getString(R.string.frame_gen_lsfg_adaptive, mode.target)
mode.engine == ENGINE_LSFG -> context.getString(R.string.frame_gen_lsfg, mode.multiplier)
else -> context.getString(R.string.frame_gen_off)
fun label(engine: String, multiplier: Int): String = when (engine) {
ENGINE_WINFG -> "Win-FG $multiplier×"
ENGINE_LSFG -> "LSFG $multiplier×"
else -> "Off"
}
/**
* Pushes the saved setting into the compositor. Returns a message for the user when the
* engine cannot run (LSFG without Lossless Scaling), or null. Blocks while a new or updated
* Lossless.dll is prepared.
* engine cannot run (LSFG without Lossless Scaling), or null.
*/
fun apply(context: Context, refreshHz: Float): String? {
val mode = mode(context)
when (mode.engine) {
val engine = engine(context)
val multiplier = multiplier(context)
var problem: String? = null
when (engine) {
ENGINE_LSFG -> {
val status = Lossless.sync(context)
val cache = Lossless.cacheFile(context)
if (status != LsfgNative.STATUS_OK || cache == 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,
)
Log.w(TAG, "$problem (status $status)")
val status = LsfgNative.ensureCache(context)
if (status != LsfgNative.STATUS_OK) {
problem = if (status == LsfgNative.STATUS_NOT_INSTALLED)
"LSFG needs Lossless Scaling installed from the Steam client"
else "LSFG: " + LsfgNative.statusName(status)
Log.w(TAG, problem)
WaylandCompositor.nativeSetFrameGenArmed(false, 0)
return problem
}
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG)
WaylandCompositor.nativeSetLsfgCachePath(cache.absolutePath)
WaylandCompositor.nativeSetLsfgCachePath(LsfgNative.cacheFile(context).absolutePath)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, mode.target)
WaylandCompositor.nativeSetFrameGenArmed(true, multiplier)
}
ENGINE_WINFG -> {
WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_WINFG)
WaylandCompositor.nativeSetWinFgTuning(WINFG_MODEL, WINFG_PERF_PRESET)
WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_WINFG, refreshHz)
WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0)
WaylandCompositor.nativeSetFrameGenArmed(true, multiplier)
}
else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0)
else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0)
}
Log.i(TAG, "frame generation: $mode at ${refreshHz}Hz")
return null
Log.i(TAG, "frame generation: $engine x$multiplier at ${refreshHz}Hz")
return problem
}
private const val TAG = "FrameGen"
@@ -1,80 +0,0 @@
package com.droiddeck.launcher.gpu
import android.os.Build
import com.droiddeck.launcher.core.FileUtils
import java.io.File
/**
* What GPU this is, in the terms the driver lists are sorted by. KGSL names the model
* ("Adreno740v2", "Adreno825"); the family decides which Turnip builds run on it at all, and the
* support level is what the app has actually been tested on (Adreno 725 and up) - an Adreno 610
* may start, but it is not "supported" just because it is a Qualcomm chip.
*/
data class GpuInfo(
/** "Adreno 740", or the vendor's own name when this is not an Adreno. */
val name: String,
/** The three-digit Adreno model (740, 825), or 0 when KGSL does not say. */
val model: Int,
val family: Family,
/** The SoC as the device reports it ("SM8550", "QCS8550"), or "" when it does not. */
val soc: String,
/** Samsung's One UI on an 8 Gen 2: its Turnip needs the OneUI build, or frames tear and flicker. */
val oneUi8Gen2: Boolean,
) {
enum class Family(val label: String) {
A8XX("Adreno 8xx"),
/** Adreno 710/720/722: gen 7 cores cut down enough to need their own patches. */
A7XX_LOW("Adreno 710/720/722"),
A7XX("Adreno 7xx"),
A6XX("Adreno 6xx"),
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
ADRENO_UNKNOWN("Adreno"),
NOT_ADRENO("Not an Adreno GPU"),
}
enum class Support { TESTED, UNTESTED, UNSUPPORTED }
val support: Support
get() = when {
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
family == Family.A8XX -> Support.TESTED
family == Family.A7XX && model >= 725 -> Support.TESTED
else -> Support.UNTESTED
}
/** One line for the device card and the system check. */
val supportText: String
get() = when (support) {
Support.TESTED -> "Supported"
Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
else "Below tested hardware (Adreno 725 and newer): it may not run"
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
}
companion object {
fun detect(): GpuInfo {
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
.firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) }
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN }.orEmpty() else ""
val model = raw?.let { Regex("""(\d{3})""").find(it)?.groupValues?.get(1)?.toIntOrNull() } ?: 0
val family = familyOf(adreno, model)
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
name = if (!adreno) Build.HARDWARE.ifBlank { "this GPU" } else if (model > 0) "Adreno $model" else "Adreno",
model = model, family = family, soc = soc,
oneUi8Gen2 = samsung && model == 740,
)
}
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
!adreno -> Family.NOT_ADRENO
model == 0 -> Family.ADRENO_UNKNOWN
model >= 800 -> Family.A8XX
model in listOf(710, 720, 722) -> Family.A7XX_LOW
model >= 700 -> Family.A7XX
model >= 600 -> Family.A6XX
else -> Family.ADRENO_UNKNOWN
}
}
}
@@ -126,7 +126,9 @@ public class LinuxVulkanDriverManager {
* Linux driver; {@link IOException} on read/extract failures.
*/
public String installDriver(Uri zipUri, String displayName) throws IOException {
File tmpDir = newStagingDir();
File tmpDir = new File(rootDir, ".tmp-" + System.currentTimeMillis());
FileUtils.delete(tmpDir);
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
boolean keep = false;
try {
String soName = null;
@@ -154,32 +156,9 @@ public class LinuxVulkanDriverManager {
}
}
// The zip's own freedreno_icd.aarch64.json is dropped on purpose: its
// library_path is relative to itself, and adopt() writes an absolute one.
// library_path is relative to itself, and we write an absolute one below.
}
}
String id = adopt(tmpDir, soName, zipMeta, displayName);
keep = true;
return id;
} finally {
if (!keep) FileUtils.delete(tmpDir);
}
}
/** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */
File newStagingDir() throws IOException {
File tmpDir = new File(rootDir, ".tmp-" + System.nanoTime());
FileUtils.delete(tmpDir);
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
return tmpDir;
}
/**
* Check a staged driver ({@link #LIB_NAME} in {@code tmpDir}, copied from {@code soName} in
* the zip), write its manifest and meta.json, and move it in. Returns the id; the caller
* deletes {@code tmpDir} when this throws.
*/
String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException {
try {
if (soName == null) {
throw new IllegalArgumentException("No libvulkan_freedreno*.so in this zip. An Android "
+ "(AdrenoTools) or -Wayland Turnip zip is not a Linux runtime driver.");
@@ -233,10 +212,13 @@ public class LinuxVulkanDriverManager {
if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json");
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
keep = true;
Log.i(TAG, "imported Linux Vulkan driver " + id + " (" + soName + ", minGlibc=" + minGlibc + ") -> " + dir);
return id;
} catch (org.json.JSONException e) {
throw new IOException("manifest write failed: " + e.getMessage());
} finally {
if (!keep) FileUtils.delete(tmpDir);
}
}
@@ -1,187 +0,0 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.DigestOutputStream
import java.security.MessageDigest
/**
* LSFG's shader chain, from the user's own Lossless Scaling (Steam app 993090).
*
* The copy the Steam client installs, in any library it installs to, is taken by
* itself and taken again whenever the client updates it. Once the session has seen the account
* own the app, a Lossless.dll can also be imported by hand; it stays until the Steam copy changes
* or another is imported. The DLL is copied in and its shaders are built into a cache named after
* its contents, so a different DLL hands the compositor a different path and its engine reloads.
* Everything here blocks: call it off the main thread.
*/
object Lossless {
enum class Source { NONE, STEAM, IMPORT }
enum class ImportResult { UPDATED, UNCHANGED, NOT_OWNED, INVALID, FAILED }
data class State(val owned: Boolean, val ready: Boolean, val source: Source) {
companion object {
val NONE = State(owned = false, ready = false, source = Source.NONE)
}
}
private const val TAG = "Lossless"
private const val PREFS = "lossless"
private const val KEY_OWNED = "owned"
private const val KEY_ID = "id"
private const val KEY_SOURCE = "source"
private const val KEY_STEAM_STAMP = "steamStamp"
private const val STEAM_DLL = "steamapps/common/Lossless Scaling/Lossless.dll"
private const val UNCHANGED = -1
fun state(context: Context): State {
val source = prefs(context).getString(KEY_SOURCE, null)
?.let { name -> Source.entries.firstOrNull { it.name == name } } ?: Source.NONE
return State(owned(context), cacheFile(context)?.isFile == true, source)
}
/** Recorded once: by the session's ownership check (a flag in the guest's home) or a Steam copy. */
fun owned(context: Context): Boolean {
if (prefs(context).getBoolean(KEY_OWNED, false)) return true
if (!ownedFlag(context).exists()) return false
markOwned(context)
return true
}
fun cacheFile(context: Context): File? = prefs(context).getString(KEY_ID, null)?.let { cacheFor(context, it) }
/** Takes a new or updated Steam copy and rebuilds a missing or outdated cache. A [LsfgNative] status. */
@Synchronized
fun sync(context: Context): Int {
val steam = steamDll(context)
if (steam != null) {
markOwned(context)
val stamp = "${steam.length()}:${steam.lastModified()}"
if (stamp != prefs(context).getString(KEY_STEAM_STAMP, null)) {
val status = adopt(context, steam, Source.STEAM)
if (status != LsfgNative.STATUS_OK && status != UNCHANGED) {
Log.w(TAG, "Steam copy $steam not taken: ${statusName(status)}")
}
prefs(context).edit().putString(KEY_STEAM_STAMP, stamp).apply()
}
}
return ensureBuilt(context)
}
@Synchronized
fun import(context: Context, dll: File): ImportResult {
if (!owned(context)) return ImportResult.NOT_OWNED
return when (adopt(context, dll, Source.IMPORT)) {
UNCHANGED -> ImportResult.UNCHANGED
LsfgNative.STATUS_OK -> ImportResult.UPDATED
LsfgNative.STATUS_UNREADABLE_FILE, LsfgNative.STATUS_NOT_PORTABLE_EXECUTABLE,
LsfgNative.STATUS_MISSING_SHADERS -> ImportResult.INVALID
else -> ImportResult.FAILED
}
}
fun message(context: Context, result: ImportResult): String = context.getString(
when (result) {
ImportResult.UPDATED -> R.string.lsfg_imported
ImportResult.UNCHANGED -> R.string.lsfg_import_unchanged
ImportResult.NOT_OWNED -> R.string.lsfg_import_not_owned
ImportResult.INVALID -> R.string.lsfg_import_invalid
ImportResult.FAILED -> R.string.lsfg_import_failed
},
)
private fun ensureBuilt(context: Context): Int {
val id = prefs(context).getString(KEY_ID, null) ?: return LsfgNative.STATUS_NOT_INSTALLED
val cache = cacheFor(context, id)
if (usable(cache)) return LsfgNative.STATUS_OK
val dll = storedDll(context)
if (!dll.isFile) return LsfgNative.STATUS_NOT_INSTALLED
return build(dll, cache)
}
private fun adopt(context: Context, source: File, from: Source): Int {
val staged = File(dir(context).apply { mkdirs() }, "Lossless.dll.staged")
try {
val id = copyHashing(source, staged)
if (id == prefs(context).getString(KEY_ID, null) && usable(cacheFor(context, id))) return UNCHANGED
val cache = cacheFor(context, id)
var status = LsfgNative.nativeValidateDll(staged.path)
if (status == LsfgNative.STATUS_OK) status = build(staged, cache)
if (status != LsfgNative.STATUS_OK) {
cache.delete()
return status
}
if (!staged.renameTo(storedDll(context))) {
cache.delete()
return LsfgNative.STATUS_CACHE_UNUSABLE
}
prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, from.name).apply()
removeStale(context, id)
Log.i(TAG, "Lossless.dll from $source ($from) ready as $id")
return LsfgNative.STATUS_OK
} catch (e: java.io.IOException) {
Log.w(TAG, "could not copy $source", e)
return LsfgNative.STATUS_UNREADABLE_FILE
} catch (t: Throwable) {
Log.e(TAG, "could not take $source", t)
return LsfgNative.STATUS_CACHE_UNUSABLE
} finally {
staged.delete()
}
}
private fun build(dll: File, cache: File): Int = try {
val status = LsfgNative.nativeBuildCache(dll.path, cache.path, true)
Log.i(TAG, "shader cache ${cache.name}: ${statusName(status)}" +
if (status == LsfgNative.STATUS_OK) " (${LsfgNative.nativeVariantName(LsfgNative.nativeCacheVariant(cache.path))})" else "")
status
} catch (t: Throwable) {
Log.e(TAG, "shader cache ${cache.name}", t)
LsfgNative.STATUS_CACHE_UNUSABLE
}
private fun usable(cache: File): Boolean = cache.isFile &&
runCatching { LsfgNative.nativeCacheVariant(cache.path) != LsfgNative.VARIANT_NONE }.getOrDefault(false)
private fun copyHashing(source: File, target: File): String {
val digest = MessageDigest.getInstance("SHA-256")
source.inputStream().use { input ->
DigestOutputStream(target.outputStream(), digest).use { output -> input.copyTo(output) }
}
return digest.digest().take(8).joinToString("") { "%02x".format(it) }
}
private fun removeStale(context: Context, keep: String) {
File(context.filesDir, "lsfg-native").deleteRecursively()
dir(context).listFiles { f -> f.name.startsWith("shaders-") && f.name != cacheFor(context, keep).name }
?.forEach { it.delete() }
}
/** The newest copy in any library the client installs to: its own, the card's, the Games folders. */
private fun steamDll(context: Context): File? {
val libraries = listOfNotNull(
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"),
GameStorage.effective(context)?.path?.let(::File),
) + SessionPrefs.addedGamesDirs(context).map(::File)
return libraries.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() }
}
private fun markOwned(context: Context) {
if (!prefs(context).getBoolean(KEY_OWNED, false)) prefs(context).edit().putBoolean(KEY_OWNED, true).apply()
}
private fun statusName(status: Int): String =
runCatching { LsfgNative.nativeStatusName(status) }.getOrDefault("status $status")
private fun ownedFlag(context: Context) = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/lossless-owned")
private fun dir(context: Context) = File(context.filesDir, "lsfg")
private fun storedDll(context: Context) = File(dir(context), "Lossless.dll")
private fun cacheFor(context: Context, id: String) = File(dir(context), "shaders-$id.cache")
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}
@@ -1,30 +1,99 @@
package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.runtime.LinuxRuntime;
import java.io.File;
/**
* The native half of LSFG's shader cache (lsfg_jni.cpp, compiled into the compositor library):
* {@code Lossless.dll} is mapped read-only and parsed as data, never loaded or executed, and its
* DXBC chain translated to SPIR-V. {@link Lossless} decides when; these calls block.
* LSFG frame generation's shader chain: extracted from the user's own copy of Lossless Scaling
* and cached on device.
*
* <p>The 25 compute shaders are not redistributable. They live as resources inside the user's
* paid {@code Lossless.dll} (Steam app 993090), which in this app the user installs from the
* Steam client itself - so the DLL sits in the runtime's own Steam library. It is mapped
* read-only and parsed as data, never loaded or executed. Extraction is slow enough to be worth
* doing once (the DXBC chain is translated to SPIR-V), so the result is cached, keyed on the
* DLL's size and hash. Call {@link #ensureCache} off the main thread.
*
* <p>Ported from Bannerlator's LsfgNative; the native side is the same lsfg_jni.cpp compiled into
* the compositor library.
*/
final class LsfgNative {
public final class LsfgNative {
private static final String TAG = "LsfgNative";
static { System.loadLibrary("bannerwayland"); }
private LsfgNative() {}
// Mirrors lsfg::DllStatus.
static final int STATUS_OK = 0;
static final int STATUS_NOT_INSTALLED = 1;
static final int STATUS_UNREADABLE_FILE = 2;
static final int STATUS_NOT_PORTABLE_EXECUTABLE = 3;
static final int STATUS_MISSING_SHADERS = 4;
static final int STATUS_TRANSLATION_FAILED = 5;
static final int STATUS_CACHE_UNUSABLE = 6;
public static final int STATUS_OK = 0;
public static final int STATUS_NOT_INSTALLED = 1;
public static final int STATUS_UNREADABLE_FILE = 2;
public static final int STATUS_NOT_PORTABLE_EXECUTABLE = 3;
public static final int STATUS_MISSING_SHADERS = 4;
public static final int STATUS_TRANSLATION_FAILED = 5;
public static final int STATUS_CACHE_UNUSABLE = 6;
// Mirrors lsfg::Variant.
static final int VARIANT_NONE = 0;
private static native int nativeValidateDll(String dllPath);
private static native int nativeDllVariant(String dllPath, boolean preferFp16);
private static native int nativeBuildCache(String dllPath, String cachePath, boolean preferFp16);
private static native boolean nativeCacheMatchesSource(String cachePath, String dllPath);
private static native int nativeCacheVariant(String cachePath);
private static native String nativeStatusName(int status);
private static native String nativeVariantName(int variant);
static native int nativeValidateDll(String dllPath);
static native int nativeBuildCache(String dllPath, String cachePath, boolean preferFp16);
static native int nativeCacheVariant(String cachePath);
static native String nativeStatusName(int status);
static native String nativeVariantName(int variant);
/** Where Lossless Scaling lands when installed from the client inside the runtime. */
public static File losslessDll(Context context) {
return new File(LinuxRuntime.rootDir(context),
"root/.local/share/Steam/steamapps/common/Lossless Scaling/Lossless.dll");
}
/** Where the translated SPIR-V chain is cached. */
public static File cacheFile(Context context) {
return new File(context.getFilesDir(), "lsfg-native/shaders.cache");
}
public static boolean isInstalled(Context context) {
return losslessDll(context).isFile();
}
/**
* Makes sure a usable cache exists for the installed DLL, building it if the DLL is new or
* changed. Returns a {@code STATUS_*} code; {@link #STATUS_OK} means the engine can start.
*/
public static int ensureCache(Context context) {
File dll = losslessDll(context);
if (!dll.isFile()) return STATUS_NOT_INSTALLED;
File cache = cacheFile(context);
try {
if (cache.isFile() && nativeCacheMatchesSource(cache.getPath(), dll.getPath())) {
return STATUS_OK;
}
int status = nativeValidateDll(dll.getPath());
if (status != STATUS_OK) {
Log.w(TAG, "Lossless.dll rejected: " + statusName(status));
return status;
}
//noinspection ResultOfMethodCallIgnored
cache.getParentFile().mkdirs();
status = nativeBuildCache(dll.getPath(), cache.getPath(), true);
Log.i(TAG, "cache build: " + statusName(status)
+ (status == STATUS_OK ? " (" + nativeVariantName(nativeCacheVariant(cache.getPath())) + ")" : ""));
return status;
} catch (Throwable t) {
Log.e(TAG, "ensureCache", t);
return STATUS_CACHE_UNUSABLE;
}
}
public static String statusName(int status) {
try {
return nativeStatusName(status);
} catch (Throwable t) {
return "status " + status;
}
}
}
@@ -179,7 +179,10 @@ public final class TurnipDriver {
* {@link IOException} on read/extract failures.
*/
public String installFromZip(Uri zipUri, String displayName) throws IOException {
File tmpDir = newStagingDir();
if (!contentDir.exists()) contentDir.mkdirs();
File tmpDir = new File(contentDir, ".tmp-" + System.currentTimeMillis());
FileUtils.delete(tmpDir);
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
boolean keep = false;
try {
try (InputStream is = context.getContentResolver().openInputStream(zipUri);
@@ -195,44 +198,26 @@ public final class TurnipDriver {
Files.copy(zis, new File(tmpDir, base).toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
String id = adopt(tmpDir, displayName);
String rejected = rejectionReason(tmpDir);
if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected);
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
String name = meta != null ? meta.optString("name", "") : "";
if (name.isEmpty()) {
name = displayName != null ? displayName : "adrenotools-driver";
if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4);
}
String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name));
File dir = new File(contentDir, id);
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
keep = true;
Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir);
return id;
} finally {
if (!keep) FileUtils.delete(tmpDir);
}
}
/** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */
File newStagingDir() throws IOException {
if (!contentDir.exists()) contentDir.mkdirs();
File tmpDir = new File(contentDir, ".tmp-" + System.nanoTime());
FileUtils.delete(tmpDir);
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
return tmpDir;
}
/**
* Check a staged driver (meta.json and its library, flat) and move it in as a new driver.
* Returns the id; the caller deletes {@code tmpDir} when this throws.
*/
String adopt(File tmpDir, String displayName) throws IOException {
String rejected = rejectionReason(tmpDir);
if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected);
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
String name = meta != null ? meta.optString("name", "") : "";
if (name.isEmpty()) {
name = displayName != null ? displayName : "adrenotools-driver";
if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4);
}
String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name));
File dir = new File(contentDir, id);
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir);
return id;
}
private static JSONObject readMetaFile(File metaFile) {
try {
return new JSONObject(FileUtils.readString(metaFile));
@@ -29,20 +29,12 @@ object TurnipReleases {
/** [label] names the variant for the menu: the GPUs it is for, and a build flavour. */
/** [sha256] is the release asset's digest from GitHub; empty for a list cached before it was kept. */
/**
* [pair] names the matched set an asset belongs to (DriverPairs): a display build and a Linux
* build of the same pair are made to run together. "" for a list cached before pairs were kept.
*/
/** [bundle]: one zip holding both halves of the pair (DriverBundle); [linux] is false for it. */
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String,
val sha256: String = "", val pair: String = "", val bundle: Boolean = false)
val sha256: String = "")
/** [latest] = each source's newest release tag, for the refresh line. */
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
/** What an asset is: a Linux build or not, the menu label, and the pair it belongs to. */
private class Kind(val linux: Boolean, val label: String, val pair: String, val bundle: Boolean = false)
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Kind?)
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Pair<Boolean, String>?)
private val SOURCES = listOf(
// Turnip-<tag>[-variant][-Linux|-Wayland].zip; -Wayland is for a path this app does not have.
@@ -53,14 +45,12 @@ object TurnipReleases {
if (variant.endsWith("-Wayland")) return@Source null
val linux = variant.endsWith("-Linux")
variant = variant.removeSuffix("-Linux")
val label = when {
linux to when {
variant.isEmpty() -> "Adreno 6xx/7xx"
variant == "-A8xx" -> "Adreno 8xx"
variant.startsWith("-710-720") -> "Adreno 710/720" + if (variant.contains("Test")) " (test)" else ""
variant.contains("OneUI", ignoreCase = true) -> "8 Gen 2 on One UI"
else -> variant.trimStart('-')
}
Kind(linux, label, "banner" + variant.lowercase())
},
// WN-Turnip-<ver>-<b|p>_Axxx.zip (Android) and WN-Linux-Turnip-<ver>-<b|p>_Axxx.zip (Linux):
// b = Balanced, p = Performance, Axxx = every Adreno.
@@ -68,13 +58,7 @@ object TurnipReleases {
val m = Regex("""^WN-(Linux-)?Turnip-[^-]+-([a-z]+)_(\w+)\.zip$""").find(name) ?: return@Source null
val flavour = when (m.groupValues[2]) { "b" -> "Balanced"; "p" -> "Performance"; else -> m.groupValues[2] }
val gpus = if (m.groupValues[3] == "Axxx") "all Adreno" else m.groupValues[3]
Kind(m.groupValues[1].isNotEmpty(), "$gpus · $flavour", "wn-" + m.groupValues[2])
},
// DD-Turnip-v<ver>.zip: DroidDeck's own all-in-one build, both halves in one zip, published
// to Drivers-CI (releases only). Every release is offered, not just the newest, each its own pair.
Source("DroidDeck", "Droid-Deck/Drivers-CI") { name, tag ->
if (!Regex("""^DD-Turnip-v\d+\.\d+\.\d+\.zip$""").matches(name)) return@Source null
Kind(false, "Android + Linux · all Adreno", DriverPairs.ddTurnip(tag), bundle = true)
(m.groupValues[1].isNotEmpty()) to "$gpus · $flavour"
},
)
@@ -107,19 +91,14 @@ object TurnipReleases {
for (j in 0 until list.length()) {
val a = list.getJSONObject(j)
val name = a.getString("name")
val kind = src.classify(name, tag) ?: continue
// A bundle is only offered from an official release, never a pre-release.
if (kind.bundle && r.optBoolean("prerelease")) continue
val linux = kind.linux
val label = kind.label
val (linux, label) = src.classify(name, tag) ?: continue
// Only assets GitHub has a sha256 for are offered: the download is checked against it.
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
// Newest first: the first release carrying a variant is the one offered.
if (!seen.add(if (kind.bundle) kind.pair else "$linux|$label")) continue
if (!seen.add("$linux|$label")) continue
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
.put("linux", linux).put("label", label).put("sha256", sha).put("pair", kind.pair)
.put("bundle", kind.bundle))
.put("linux", linux).put("label", label).put("sha256", sha))
}
}
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
@@ -157,8 +136,7 @@ object TurnipReleases {
for (i in 0 until list.length()) {
val a = list.getJSONObject(i)
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", ""), a.optString("pair", ""),
a.optBoolean("bundle", false)))
a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", "")))
}
val latest = ArrayList<Pair<String, String>>()
val l = json.optJSONArray("latest") ?: JSONArray()
@@ -66,16 +66,6 @@ public final class PadBridge {
private volatile Runnable onPlayerInput;
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
// What reached the pad over the last stats window, so a report of "the pad does nothing" or
// "touch and the pad don't work together" shows in the app log whether input arrived, from
// which device, and whether it got to the ring. Logged only for a window that had input.
private static final long STATS_WINDOW_MS = 10_000;
private int statButtons, statAxes, statOnScreen, statDropped;
private String statDevice;
private boolean statsScheduled;
private final java.util.Set<Integer> seenDevices = new java.util.HashSet<>();
private int lastDeviceId = Integer.MIN_VALUE;
public PadBridge(File fakeInputDir) {
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
}
@@ -144,7 +134,6 @@ public final class PadBridge {
/** @return true when the event was a pad button and has been consumed. */
public synchronized boolean onKeyEvent(KeyEvent event) {
if (!isFromController(event.getDevice())) return false;
noteDevice(event.getDevice());
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BUTTON_A: state.press(0, pressed); break;
@@ -172,8 +161,6 @@ public final class PadBridge {
default: return false;
}
if (pressed) notePlayerInput();
statButtons++;
scheduleStats();
publish();
return true;
}
@@ -182,9 +169,6 @@ public final class PadBridge {
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isFromController(event.getDevice())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
noteDevice(event.getDevice());
statAxes++;
scheduleStats();
state.leftX = axis(event, MotionEvent.AXIS_X);
// Android's Y axis grows downwards and evdev's ABS_Y does too, so no flip here: what the
// pad reports as "down" is what the client is told.
@@ -219,8 +203,6 @@ public final class PadBridge {
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
mutation.accept(state);
notePlayerInput();
statOnScreen++;
scheduleStats();
publish();
}
@@ -297,39 +279,8 @@ public final class PadBridge {
publish();
}
/** Per event, so the common case - the same pad as last time - is a single compare. */
private void noteDevice(InputDevice device) {
if (device.getId() == lastDeviceId) return;
lastDeviceId = device.getId();
statDevice = device.getName();
if (seenDevices.add(device.getId())) {
Log.i(TAG, String.format(java.util.Locale.ROOT, "first input from \"%s\" (%04x:%04x, id %d, sources 0x%x); ring %s, deck pad %b",
device.getName(), device.getVendorId(), device.getProductId(), device.getId(), device.getSources(),
open ? "open" : "not open yet", SessionState.getDeckPad()));
}
}
private void scheduleStats() {
if (statsScheduled) return;
statsScheduled = true;
mainHandler.postDelayed(this::logStats, STATS_WINDOW_MS);
}
private synchronized void logStats() {
statsScheduled = false;
Log.i(TAG, "[input] last 10 s: pad " + statButtons + " buttons, " + statAxes + " axis events"
+ (statDevice != null ? " (\"" + statDevice + "\")" : "")
+ ", on-screen " + statOnScreen
+ (statDropped > 0 ? ", " + statDropped + " NOT delivered (ring closed)" : "")
+ "; ring " + (open ? "open" : "closed") + ", deck pad " + SessionState.getDeckPad());
statButtons = statAxes = statOnScreen = statDropped = 0;
}
private void publish() {
if (!open && !start()) {
statDropped++;
return;
}
if (!open && !start()) return;
boolean guide = systemGuidePressed || qamChordActive;
boolean qam = SessionState.getDeckPad() && (systemQamPressed || qamTapPressed);
if (!guide && !qam) {
@@ -1,9 +1,7 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.graphics.BitmapFactory
import android.os.StatFs
import android.system.Os
import android.util.Log
import com.droiddeck.launcher.core.FileUtils
import java.io.File
@@ -23,7 +21,6 @@ object AppImageManager {
const val LAUNCHER = "/usr/local/bin/bannerlator-appimage-run"
private const val ELF_AARCH64 = 183
private const val ELF_X86_64 = 62
private const val SHARP_ICON = 128
class Item(val id: String, val name: String, val icon: File?, val comment: String?) {
val guestDir: String get() = "$GUEST_DIR/$id"
@@ -77,15 +74,8 @@ object AppImageManager {
return id
}
fun dir(context: Context, id: String) = File(root(context), id)
/**
* Imports [file]; null on success, else what went wrong. [name] and [icon] replace the image's own;
* each of [meta] is written as a file beside them.
*/
fun import(
context: Context, file: File, name: String?, icon: File?, meta: Map<String, String> = emptyMap(), onProgress: (String) -> Unit,
): String? {
/** Imports [file]; null on success, else what went wrong. [onProgress] gets a stage line. */
fun import(context: Context, file: File, onProgress: (String) -> Unit): String? {
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
problem(file)?.let { return it }
val base = root(context).apply { mkdirs() }
@@ -93,45 +83,9 @@ object AppImageManager {
if (StatFs(base.path).availableBytes < file.length() * 3) {
return "Not enough free space: importing needs about ${FileUtils.sizeToString(file.length() * 3)}"
}
val dir = File(base, idFor(name ?: file.name, base.list()?.toSet() ?: emptySet()))
try {
extract(context, dir, file, onProgress)?.let { FileUtils.delete(dir); return it }
describe(dir, file)
if (name != null) FileUtils.writeString(File(dir, "name"), name)
if (icon != null && !UserApps.saveIcon(icon, File(dir, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
meta.forEach { (k, v) -> FileUtils.writeString(File(dir, k), v) }
writeMenuEntry(context, dir)
return null
} catch (e: Exception) {
Log.e(TAG, "import ${file.name}", e)
FileUtils.delete(dir)
return e.message ?: "Import failed"
}
}
/** Swaps the program of imported [id] for [file], keeping its name and icon; the old one stays if this fails. */
fun replace(context: Context, id: String, file: File, meta: Map<String, String>, onProgress: (String) -> Unit): String? {
problem(file)?.let { return it }
val dir = dir(context, id)
if (!File(dir, "app").isDirectory) return "That AppImage is gone"
if (StatFs(dir.path).availableBytes < file.length() * 3) {
return "Not enough free space: updating needs about ${FileUtils.sizeToString(file.length() * 3)}"
}
return try {
extract(context, dir, file, onProgress) ?: run {
meta.forEach { (k, v) -> FileUtils.writeString(File(dir, k), v) }
null
}
} catch (e: Exception) {
Log.e(TAG, "replace $id", e)
e.message ?: "Update failed"
}
}
/** Extracts [file] to [dir]/app, replacing what is there only once the extraction has worked. */
private fun extract(context: Context, dir: File, file: File, onProgress: (String) -> Unit): String? {
val id = idFor(file.name, base.list()?.toSet() ?: emptySet())
val dir = File(base, id)
val image = File(dir, "image.AppImage")
val links = File(dir, ".links").apply { mkdirs() }
try {
dir.mkdirs()
// Copied in, not run where it lies: shared storage is mounted noexec, and proot's loader
@@ -140,41 +94,27 @@ object AppImageManager {
file.inputStream().use { input -> image.outputStream().use { FileUtils.copy(input, it) } }
image.setExecutable(true, false)
onProgress("Extracting ${file.name}")
val guestDir = "$GUEST_DIR/$id"
val out = StringBuilder()
// uruntime's DwarFS images unpack into AppDir with squashfs-root a link to it, and keep
// one program under several names as hard links (sharun), which Android denies apps.
val status = GuestCommand.run(context, listOf(
"/bin/bash", "-c",
"cd \"$1\" && rm -rf squashfs-root AppDir && ./image.AppImage --appimage-extract >/dev/null && " +
"rm -rf app && mv \"$(readlink -f squashfs-root)\" app && rm -f squashfs-root",
"extract", "$GUEST_DIR/${dir.name}",
), logName = "appimage-import", linkDir = links) { line -> if (out.length < 2000) out.appendLine(line) }
"cd \"$1\" && ./image.AppImage --appimage-extract >/dev/null && mv squashfs-root app",
"extract", guestDir,
), logName = "appimage-import") { line -> if (out.length < 2000) out.appendLine(line) }
if (status != 0 || !File(dir, "app").isDirectory) {
listOf("squashfs-root", "AppDir").forEach { FileUtils.delete(File(dir, it)) }
FileUtils.delete(dir)
return "The AppImage could not be extracted" + (out.lines().lastOrNull { it.isNotBlank() }?.let { ": $it" } ?: "")
}
copyLinkedFiles(File(dir, "app"), links)
image.delete()
describe(dir, file)
writeMenuEntry(context, dir)
return null
} catch (e: Exception) {
Log.e(TAG, "import ${file.name}", e)
FileUtils.delete(dir)
return e.message ?: "Import failed"
} finally {
image.delete()
FileUtils.delete(links)
}
}
/**
* Each name proot's link2symlink left for a hard link becomes a file of its own: a program run
* through a link would see the shared file's name, and sharun picks what to start by its own.
*/
private fun copyLinkedFiles(app: File, links: File) {
val roots = setOf(links.path + "/", links.canonicalPath + "/")
app.walkTopDown().onEnter { !Files.isLink(it) }.forEach { f ->
if (!Files.isLink(f)) return@forEach
val target = runCatching { Os.readlink(f.path) }.getOrNull() ?: return@forEach
if (roots.none { target.startsWith(it) }) return@forEach
val data = f.toPath().toRealPath()
java.nio.file.Files.delete(f.toPath())
java.nio.file.Files.copy(data, f.toPath())
if (java.nio.file.Files.isExecutable(data)) f.setExecutable(true, false)
}
}
@@ -188,32 +128,14 @@ object AppImageManager {
FileUtils.writeString(File(dir, "name"), name)
key("Comment")?.let { FileUtils.writeString(File(dir, "comment"), it) }
key("Categories")?.let { FileUtils.writeString(File(dir, "categories"), it) }
restoreIcon(dir)
}
/**
* The image's own icon as [dir]'s: of the files its entry names, beside it or anywhere in its
* icon theme, a PNG of at least [SHARP_ICON] px, else the SVG, else the largest PNG; .DirIcon
* without any.
*/
internal fun restoreIcon(dir: File) {
val app = File(dir, "app")
val entry = app.listFiles { f -> f.isFile && f.name.endsWith(".desktop") }?.firstOrNull()
val iconName = entry?.let { FileUtils.readString(it) }?.let { desktopKey(it, "Icon") }
val named = iconName?.let { n ->
app.walkTopDown().maxDepth(8).filter { it.isFile && (it.name == "$n.png" || it.name == "$n.svg") }.toList()
}.orEmpty()
val png = named.filter(::isPng).maxByOrNull(::pngSide)
val svg = named.firstOrNull { it.name.endsWith(".svg") }
val pick = png?.takeIf { pngSide(it) >= SHARP_ICON } ?: svg ?: png ?: File(app, ".DirIcon").takeIf { it.isFile }
val icon = File(dir, "icon.png")
if (pick == null || !UserApps.saveIcon(pick, icon)) icon.delete()
}
private fun pngSide(f: File): Int {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(f.path, bounds)
return minOf(bounds.outWidth, bounds.outHeight)
// The icon the entry names, beside it or anywhere in the image's icon theme, else .DirIcon.
val iconName = key("Icon")
val candidates = listOfNotNull(
iconName?.let { File(app, "$it.png") },
iconName?.let { n -> app.walkTopDown().maxDepth(8).filter { it.isFile && it.name == "$n.png" }.maxByOrNull { it.length() } },
File(app, ".DirIcon"),
)
candidates.firstOrNull { it.isFile && isPng(it) }?.copyTo(File(dir, "icon.png"), overwrite = true)
}
private fun isPng(f: File): Boolean = try {
@@ -237,7 +159,7 @@ object AppImageManager {
File(LinuxRuntime.rootDir(context), "usr/local/share/applications/droiddeck-appimage-$id.desktop")
/** The Linux desktop's menu entry: the desktop's own Exec rules (and droiddeck-gpu) apply to it. */
internal fun writeMenuEntry(context: Context, dir: File) {
private fun writeMenuEntry(context: Context, dir: File) {
val id = dir.name
val name = FileUtils.readString(File(dir, "name"))?.trim() ?: id
val categories = FileUtils.readString(File(dir, "categories"))?.trim()?.takeIf { it.isNotEmpty() } ?: "Utility;"
@@ -89,7 +89,7 @@ object FlatpakManager {
/** Runs [argv] in the runtime, its output also in Download/DroidDeck/flatpak-<verb>.log. */
private fun runGuest(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
val name = "flatpak-" + (argv.getOrNull(2)?.takeIf { argv.getOrNull(1) == HELPER } ?: "setup")
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
return GuestCommand.run(context, argv, fakeRoot, name, onLine)
}
private inline fun <T> exclusive(what: String, block: () -> T): T? {
@@ -5,7 +5,6 @@ import android.os.Environment
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionFiles
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
@@ -17,26 +16,23 @@ object GuestCommand {
/**
* Runs [argv] and hands each output line to [onLine]; returns the exit status. [fakeRoot] is
* for the package tools, which refuse any uid but 0. With [logName], everything the command
* says also goes to Download/DroidDeck/tools/<logName>.log beside the session logs, so a problem can
* be handed over like a session's. With [linkDir], hard links (which Android denies apps)
* become symlinks to files proot keeps there (its link2symlink).
* says also goes to Download/DroidDeck/<logName>.log beside the session logs, so a problem can
* be handed over like a session's.
*/
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
linkDir: File? = null, onLine: (String) -> Unit): Int {
onLine: (String) -> Unit): Int {
val log = logName?.let {
try {
File(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
} catch (e: Exception) { null }
try { File(LinuxRuntime.debugLogDir().apply { mkdirs() }, "$it.log").printWriter() } catch (e: Exception) { null }
}
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
try {
return runLogged(context, argv, fakeRoot, linkDir) { line -> log?.println(line); log?.flush(); onLine(line) }
return runLogged(context, argv, fakeRoot) { line -> log?.println(line); log?.flush(); onLine(line) }
} finally {
log?.close()
}
}
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, onLine: (String) -> Unit): Int {
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, root)
@@ -44,12 +40,11 @@ object GuestCommand {
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")
LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), null)
.forEach { cmd.add("-b"); cmd.add(it) }
cmd += listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${runtimeDir.path}",
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
)
@@ -58,7 +53,6 @@ object GuestCommand {
builder.environment().apply {
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", context.cacheDir.path)
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
@@ -34,14 +34,6 @@ public final class LinuxRuntime {
/** Shortcut extra naming which of the modes above a Linux entry launches. */
public static final String EXTRA_LINUX_MODE = "linux_mode";
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
/**
* Where the guest sees a command's XDG_RUNTIME_DIR. A Unix socket's path must fit in 108 bytes,
* and libwayland checks the guest's path before proot ever sees it: with the app on an SD card
* adopted as internal storage the files directory is /mnt/expand/<uuid>/user/0/<package>/files,
* and gamescope-0 under it is one byte over, so gamescope could not open its socket and the
* session ended at once. A long host path behind it is proot's to shorten.
*/
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
public static final String DEBUG_LOG_DIR = "DroidDeck";
@@ -193,10 +185,7 @@ public final class LinuxRuntime {
bind(cmd, new File(root, "etc/bannerlator/empty").getPath() + ":/sys/fs/selinux");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
if (runtimeDir != null) {
bind(cmd, runtimeDir.getPath());
bind(cmd, runtimeDir.getPath() + ":" + GUEST_RUNTIME_DIR);
}
if (runtimeDir != null) bind(cmd, runtimeDir.getPath());
if (sessionRoot != null) bind(cmd, sessionRoot.getPath());
if (externalStorage != null && externalStorage.isDirectory()) {
bind(cmd, externalStorage.getPath());
@@ -242,15 +231,12 @@ public final class LinuxRuntime {
};
for (String[] entry : procFiles) {
File fake = new File(fakeProc, entry[0]);
// A live stand-in the session binds itself (CpuStatComponent's /proc/stat) wins.
boolean live = false;
if (extraBinds != null) for (String spec : extraBinds) live |= spec.endsWith(":" + entry[1]);
if (!live && fake.isFile() && !new File(entry[1]).canRead()) {
if (fake.isFile() && !new File(entry[1]).canRead()) {
bind(cmd, fake.getPath() + ":" + entry[1]);
}
}
bindGpuNode(context, cmd);
bindAdrenoStats(cmd, extraBinds);
bindAdrenoStats(cmd);
bindCpuTemps(cmd, root);
if (extraBinds != null) {
for (String spec : extraBinds) bind(cmd, spec);
@@ -296,84 +282,27 @@ public final class LinuxRuntime {
if (!Files.isSymbolicLink(subsystem.toPath())) {
Os.symlink("/sys/bus/platform", subsystem.getPath());
}
// What MangoHud names a GPU's driver by; msm_drm is how an Adreno's render node reads
// on a mainline kernel, and the driver it reads the load of (bindAdrenoStats).
File driver = new File(device, "driver");
if (!Files.isSymbolicLink(driver.toPath())) {
Os.symlink("/sys/bus/platform/drivers/msm_drm", driver.getPath());
}
} catch (IOException | ErrnoException e) {
return;
}
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
bind(cmd, dri.getPath() + ":/dev/dri");
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
bindDrmClass(base, cmd, node, major + ":" + minor);
}
/**
* MangoHud (Deck mode's performance overlay, mangoapp) finds the GPU by listing
* {@code /sys/class/drm}, and an exception from that listing ends the process: under an
* enforcing SELinux policy - every retail phone - an app may not list it, so mangoapp died on
* start, gamescope restarted it until the session gave up, and there was no overlay. Where the
* app cannot list it, the session's {@code /sys/class/drm} is ours: the render node above,
* named as an Adreno's is. MangoHud then reads the GPU's stats from KGSL's sysfs, which such a
* device refuses too - SessionService's GpuStatsComponent stands in for that. Where the
* listing is allowed it is left alone.
*/
private static void bindDrmClass(File base, List<String> cmd, String node, String devNumbers) {
if (new File("/sys/class/drm").list() != null) return;
File drmClass = new File(base, "class");
try {
if (!drmClass.isDirectory() && !drmClass.mkdirs()) return;
// Only symlinks are ever made here; deleting them must not follow one into its target.
File[] old = drmClass.listFiles();
if (old != null) for (File f : old) Files.deleteIfExists(f.toPath());
Os.symlink("/sys/dev/char/" + devNumbers, new File(drmClass, node).getPath());
} catch (IOException | ErrnoException e) {
return;
}
bind(cmd, drmClass.getPath() + ":/sys/class/drm");
android.util.Log.i("LinuxRuntime", "hud: /sys/class/drm is not listable here; the session's lists " + node);
// Also refused to list, also asked for by MangoHud twice a second - an error line each
// time in the session log - and holding nothing it reads on an Adreno phone.
if (new File("/sys/class/powercap").list() == null) {
File empty = new File(base, "empty-powercap");
if (empty.isDirectory() || empty.mkdirs()) bind(cmd, empty.getPath() + ":/sys/class/powercap");
}
}
/** The temperature of a CPU zone the app may read (the first by name), or null. */
public static String cpuTempSource() {
for (java.util.Map.Entry<String, File> e : new java.util.TreeMap<>(thermalZones()).entrySet()) {
File temp = new File(e.getValue(), "temp");
if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) return temp.getPath();
}
return null;
}
/** The file the GPU's temperature reads from, or null where the app may read none. */
public static String gpuTempSource() {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
return firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
}
private static String gpuLoadSource() {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
return firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load");
}
/**
* Valve's mangoapp (Deck mode's performance overlay) reads an Adreno GPU's load, clock and
* temperatures from where they are on Valve's own hardware; every Adreno under Android keeps
* them in KGSL's sysfs, readable by the app, though which files a kernel has differs between
* Snapdragon generations.
* Snapdragon generations - so each value takes the first source that exists, the order other
* Android PC emulators (GameNative, Winlator forks) read them in. A value found nowhere is left
* alone.
*/
private static void bindAdrenoStats(List<String> cmd, List<String> extraBinds) {
private static void bindAdrenoStats(List<String> cmd) {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
String gpuTemp = gpuTempSource();
String gpuTemp = firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
String[][] stats = {
{gpuLoadSource(), "/sys/kernel/debug/dri/0/perf_now"},
{firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load"), "/sys/kernel/debug/dri/0/perf_now"},
{firstReadable(kgsl + "devfreq/cur_freq", kgsl + "gpuclk"),
"/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"},
{gpuTemp, "/sys/class/thermal/thermal_zone28/temp"},
@@ -381,21 +310,8 @@ public final class LinuxRuntime {
{thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"},
};
for (String[] stat : stats) {
// A value the session feeds itself (GpuStatsComponent, where KGSL is refused) wins.
boolean fed = false;
if (extraBinds != null) for (String spec : extraBinds) fed |= spec.endsWith(":" + stat[1]);
if (stat[0] != null && !fed) bind(cmd, stat[0] + ":" + stat[1]);
if (stat[0] != null) bind(cmd, stat[0] + ":" + stat[1]);
}
// Which of the overlay's GPU values this device lets the app read: a phone under an
// enforcing policy refuses some of them, and the overlay then has no line for that value.
android.util.Log.i("LinuxRuntime", "hud sources: gpu load " + orNone(stats[0][0]) + ", gpu clock "
+ orNone(stats[1][0]) + ", gpu temp " + orNone(gpuTemp) + ", ddr temp " + orNone(stats[4][0])
+ ", thermal zones " + thermalZones().size()
+ ", kgsl gpubusy " + (new File(kgsl + "gpubusy").canRead() ? "readable" : "refused"));
}
private static String orNone(String path) {
return path != null ? path : "none";
}
/**
@@ -1,45 +0,0 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.MessageDigest
/**
* proot's fast path: the session's path lookups answered inside each process by libblfastpath
* (tools/proot/fastpath), which issues the translated call from a trampoline page proot's seccomp
* filter lets through (tools/proot/patches/0014). A stat or an open costs about a microsecond
* instead of a 15-60 us round trip through the tracer.
*
* The library maps guest paths to host paths itself, so it has to be told the rootfs and the
* binds exactly as proot was given them. Both sides carry a key derived from that view - proot
* PROOT_FASTPATH=<key>, the guest PROOT_FP_KEY=<key> - and the library answers nothing unless the
* process that traces it has the same key: a program that inherited the variables but runs under
* another proot (a Flatpak sandbox, a one-off command) leaves every call to its own proot.
*
* Needs proot's seccomp filter, so "Run proot without seccomp" turns it off as well.
*/
object ProotFastPath {
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
fun enabled(context: Context): Boolean =
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context)
/** The key for this rootfs and these binds, or null when the library cannot be told them. */
fun key(root: File, binds: List<String>): String? {
if (binds.any { it.contains('|') } || root.path.contains('|')) return null
val digest = MessageDigest.getInstance("SHA-256")
.digest((root.path + "\n" + binds.joinToString("\n")).toByteArray())
return digest.take(12).joinToString("") { "%02x".format(it) }
}
/** What proot's own environment carries. */
fun hostEnv(key: String): Pair<String, String> = "PROOT_FASTPATH" to key
/** The guest's assignments (for `env -i`), describing the view proot was given. */
fun guestEnv(root: File, binds: List<String>, key: String): List<String> = listOf(
"PROOT_FP_ROOT=" + root.path,
"PROOT_FP_BINDS=" + binds.joinToString("|"),
"PROOT_FP_KEY=$key",
)
}
@@ -1,422 +0,0 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.net.Uri
import android.os.Environment
import android.os.StatFs
import android.system.Os
import android.util.Log
import com.caverock.androidsvg.SVG
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.store.FlathubApi
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.RandomAccessFile
/**
* The apps a user adds to the Desktop page: shell scripts, AppImages (from storage or a GitHub
* release) and Flatpak apps. Each opens full screen under gamescope, like an emulator.
*
* A script lives at /opt/droiddeck-apps/<id>: its folder at `files`, the script's name in `entry`.
* The folder is linked where it lies; shared storage is mounted noexec, so a folder holding Linux
* programs is copied in instead. A linked folder outside internal storage is bound into the
* session at its own path ([binds]), so the link resolves inside the guest.
*/
object UserApps {
private const val TAG = "UserApps"
const val GUEST_DIR = "/opt/droiddeck-apps"
const val SCRIPT_LAUNCHER = "/usr/local/bin/bannerlator-script-run"
private const val FLATPAK_OVERRIDES = ".flatpak"
private const val ICON_SIZE = 256
private const val ELF_SCAN_LIMIT = 4000
private const val ICON_SUGGESTIONS = 7
private const val ICON_FILE_LIMIT = 2L shl 20
private val ICON_TYPES = setOf("png", "jpg", "jpeg", "webp")
private val IGNORED_DIRS = Regex("(^|/)(node_modules|vendor|third[_-]?party|external|tests?|docs?/screenshots)/", RegexOption.IGNORE_CASE)
private const val GITHUB_REPO = "github-repo"
private const val GITHUB_TAG = "github-tag"
private const val GITHUB_PUBLISHED = "github-published"
enum class Kind { SCRIPT, APPIMAGE, FLATPAK }
/**
* [copied]: a script whose folder was copied in rather than linked. [repo]: the GitHub repository
* an AppImage came from, [version] the release it is.
*/
class App(
val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?,
val program: String, val args: List<String>, val copied: Boolean = false,
val repo: String? = null, val version: String? = null,
)
class Release(val tag: String, val published: String, val asset: String, val url: String)
sealed class UpdateCheck {
class Current(val tag: String) : UpdateCheck()
class Available(val release: Release) : UpdateCheck()
class Failed(val message: String) : UpdateCheck()
}
sealed class Source {
class Script(val file: File) : Source()
class AppImage(val file: File) : Source()
class GitHub(val repo: String) : Source()
class Flatpak(val id: String) : Source()
}
/** [icon]: a picked file's path or a suggested icon's URL. */
class Request(val source: Source, val name: String?, val icon: String?)
/** How a script's folder reaches the session: linked in place, or copied in ([bytes] to copy). */
class ScriptPlan(val folder: File, val copy: Boolean, val bytes: Long)
private fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1))
private fun overrides(context: Context, flatpakId: String) = File(root(context), "$FLATPAK_OVERRIDES/$flatpakId")
private fun menuEntry(context: Context, id: String) =
File(LinuxRuntime.rootDir(context), "usr/local/share/applications/droiddeck-app-$id.desktop")
fun list(context: Context): List<App> {
val scripts = root(context).listFiles()?.filter { File(it, "entry").isFile }?.map { dir ->
App(
"script:${dir.name}", Kind.SCRIPT, readName(dir) ?: dir.name, File(dir, "icon.png").takeIf { it.isFile },
FileUtils.readString(File(dir, "source"))?.trim(), SCRIPT_LAUNCHER, listOf("$GUEST_DIR/${dir.name}"),
copied = !java.nio.file.Files.isSymbolicLink(File(dir, "files").toPath()),
)
}.orEmpty()
val images = AppImageManager.list(context).map { item ->
val dir = AppImageManager.dir(context, item.id)
App(
"appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir),
repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(),
)
}
val flatpaks = FlatpakManager.installedApps(context).map { app ->
val custom = overrides(context, app.id)
App(
"flatpak:${app.id}", Kind.FLATPAK, readName(custom) ?: app.name,
File(custom, "icon.png").takeIf { it.isFile } ?: app.icon ?: FlathubApi.iconUrl(app.id),
app.summary, FlatpakManager.LAUNCHER, listOf(app.id),
)
}
return (scripts + images + flatpaks).sortedBy { it.name.lowercase() }
}
private fun readName(dir: File) = FileUtils.readString(File(dir, "name"))?.trim()?.takeIf { it.isNotEmpty() }
/** Adds [request]; null on success, else what went wrong. */
fun add(context: Context, request: Request, onProgress: (String, Int) -> Unit): String? {
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val name = request.name?.trim()?.takeIf { it.isNotEmpty() }
return withIcon(context, request.icon) { icon ->
when (val s = request.source) {
is Source.Script -> addScript(context, s.file, name, icon, onProgress)
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon) { onProgress(it, -1) }
is Source.GitHub -> addFromGitHub(context, s.repo, name, icon, onProgress)
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
}
}
}
/** [icon] as a file for [use]: a path as it is, a URL downloaded for the while. */
private inline fun <T> withIcon(context: Context, icon: String?, use: (File?) -> T): T {
if (icon == null || !icon.startsWith("https://")) return use(icon?.let(::File))
val download = File(context.cacheDir, "icon-${System.nanoTime()}")
try {
return use(download.takeIf { Downloader.downloadFile(icon, it, false) { } })
} finally {
download.delete()
}
}
/**
* Renames [app] and sets its icon: [icon] a path or URL, "" for its default, null to keep it.
* The Linux desktop's menu entry follows.
*/
fun edit(context: Context, app: App, name: String, icon: String?): String? {
val id = app.key.substringAfter(':')
if (id.isEmpty() || '/' in id || id.startsWith(".")) return null
val dir = when (app.kind) {
Kind.SCRIPT -> File(root(context), id)
Kind.APPIMAGE -> AppImageManager.dir(context, id)
Kind.FLATPAK -> overrides(context, id)
}.apply { mkdirs() }
FileUtils.writeString(File(dir, "name"), name.trim())
val target = File(dir, "icon.png")
when {
icon == null -> {}
icon.isEmpty() -> if (app.kind == Kind.APPIMAGE) AppImageManager.restoreIcon(dir) else target.delete()
else -> withIcon(context, icon) { file -> if (file == null || !saveIcon(file, target)) return context.getString(R.string.user_apps_icon_failed) }
}
when (app.kind) {
Kind.SCRIPT -> writeScriptEntry(context, dir)
Kind.APPIMAGE -> AppImageManager.writeMenuEntry(context, dir)
Kind.FLATPAK -> {}
}
return null
}
fun remove(context: Context, app: App, onProgress: (String, Int) -> Unit): String? {
val id = app.key.substringAfter(':')
if (id.isEmpty() || '/' in id || id.startsWith(".")) return null
return when (app.kind) {
Kind.SCRIPT -> {
val dir = File(root(context), id)
// The link goes, never the folder it points to.
File(dir, "files").delete()
FileUtils.delete(dir)
menuEntry(context, id).delete()
null
}
Kind.APPIMAGE -> { AppImageManager.remove(context, id); null }
Kind.FLATPAK -> FlatpakManager.uninstall(context, id, onProgress).also {
if (it == null) FileUtils.delete(overrides(context, id))
}
}
}
/** Folders linked from outside internal storage, bound into a session at their own paths. */
fun binds(context: Context): List<String> {
val internal = Environment.getExternalStorageDirectory().canonicalPath
return root(context).listFiles().orEmpty().mapNotNull { dir ->
val target = runCatching { Os.readlink(File(dir, "files").path) }.getOrNull() ?: return@mapNotNull null
target.takeIf { !it.startsWith("$internal/") && File(it).isDirectory }
}.distinct()
}
fun planScript(script: File): ScriptPlan {
val folder = script.canonicalFile.parentFile ?: script.parentFile!!
var scanned = 0
val copy = folder.walkTopDown().maxDepth(4).filter { it.isFile }.takeWhile { scanned++ < ELF_SCAN_LIMIT }.any(::isElf)
val bytes = if (copy) folder.walkTopDown().filter { it.isFile }.sumOf { it.length() } else 0L
return ScriptPlan(folder, copy, bytes)
}
private fun isElf(f: File): Boolean = try {
RandomAccessFile(f, "r").use { val b = ByteArray(4); it.read(b) == 4 && b[0] == 0x7f.toByte() && b[1] == 'E'.code.toByte() && b[2] == 'L'.code.toByte() && b[3] == 'F'.code.toByte() }
} catch (e: Exception) { false }
private fun addScript(context: Context, script: File, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
if (!script.isFile) return context.getString(R.string.user_apps_file_gone)
val plan = planScript(script)
val base = root(context).apply { mkdirs() }
if (plan.copy && StatFs(base.path).availableBytes < plan.bytes + (64L shl 20)) {
return context.getString(R.string.user_apps_no_space, FileUtils.sizeToString(plan.bytes))
}
val title = name ?: script.nameWithoutExtension
val id = AppImageManager.idFor(title, base.list()?.toSet() ?: emptySet())
val dir = File(base, id)
try {
dir.mkdirs()
val files = File(dir, "files")
if (plan.copy) {
onProgress(context.getString(R.string.user_apps_copying, plan.folder.name), -1)
copyTree(plan.folder, files)
} else {
Os.symlink(plan.folder.path, files.path)
}
FileUtils.writeString(File(dir, "entry"), script.name)
FileUtils.writeString(File(dir, "name"), title)
FileUtils.writeString(File(dir, "source"), script.canonicalPath)
if (icon != null && !saveIcon(icon, File(dir, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
writeScriptEntry(context, dir)
return null
} catch (e: Exception) {
Log.e(TAG, "script ${script.path}", e)
File(dir, "files").takeIf { !plan.copy }?.delete()
FileUtils.delete(dir)
return e.message ?: context.getString(R.string.user_apps_failed)
}
}
private fun writeScriptEntry(context: Context, dir: File) {
val id = dir.name
val icon = if (File(dir, "icon.png").isFile) "$GUEST_DIR/$id/icon.png" else "utilities-terminal"
FileUtils.writeString(menuEntry(context, id),
"[Desktop Entry]\nType=Application\nName=${readName(dir) ?: id}\nExec=$SCRIPT_LAUNCHER $GUEST_DIR/$id\nIcon=$icon\n" +
"Terminal=false\nCategories=Game;\nX-DroidDeck-App=$id\n")
}
/** Copies [from] into [to], keeping Linux programs and scripts executable. */
private fun copyTree(from: File, to: File) {
from.walkTopDown().forEach { src ->
val dst = File(to, src.relativeTo(from).path)
if (src.isDirectory) dst.mkdirs()
else {
src.inputStream().use { input -> dst.outputStream().use { FileUtils.copy(input, it) } }
if (isElf(dst) || dst.extension == "sh") dst.setExecutable(true, false)
}
}
}
/** [source] (PNG, JPEG, WebP or SVG) as the app's icon: a PNG no larger than [ICON_SIZE] on a side. */
internal fun saveIcon(source: File, target: File): Boolean {
val bitmap = (if (isSvg(source)) renderSvg(source) else decodeScaled(source)) ?: return false
return try {
target.parentFile?.mkdirs()
target.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
} catch (e: Exception) {
Log.w(TAG, "icon ${source.path}", e); false
} finally {
bitmap.recycle()
}
}
private fun decodeScaled(source: File): Bitmap? {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(source.path, bounds)
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
var sample = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= ICON_SIZE) sample *= 2
val decoded = BitmapFactory.decodeFile(source.path, BitmapFactory.Options().apply { inSampleSize = sample }) ?: return null
val scale = ICON_SIZE.toFloat() / maxOf(decoded.width, decoded.height)
if (scale >= 1f) return decoded
val scaled = Bitmap.createScaledBitmap(decoded, (decoded.width * scale).toInt().coerceAtLeast(1), (decoded.height * scale).toInt().coerceAtLeast(1), true)
if (scaled !== decoded) decoded.recycle()
return scaled
}
private fun isSvg(f: File): Boolean = try {
f.inputStream().use { val head = ByteArray(1024); val n = it.read(head); n > 0 && String(head, 0, n).contains("<svg") }
} catch (e: Exception) { false }
/** An SVG drawn at [ICON_SIZE], centred in its own proportions. */
private fun renderSvg(source: File): Bitmap? = try {
val svg = source.inputStream().use { SVG.getFromInputStream(it) }
if (svg.documentViewBox == null && svg.documentWidth > 0 && svg.documentHeight > 0) {
svg.setDocumentViewBox(0f, 0f, svg.documentWidth, svg.documentHeight)
}
svg.setDocumentWidth("100%")
svg.setDocumentHeight("100%")
Bitmap.createBitmap(ICON_SIZE, ICON_SIZE, Bitmap.Config.ARGB_8888).also { svg.renderToCanvas(Canvas(it)) }
} catch (e: Exception) {
Log.w(TAG, "svg ${source.path}", e); null
}
/** "owner/repo" from what was typed: any link into the repository, its clone address, or the short form. */
fun githubRepo(input: String): String? {
val t = input.trim()
val m = Regex("^(?:https?://)?(?:www\\.)?github\\.com[/:]([\\w.-]+)/([\\w.-]+)", RegexOption.IGNORE_CASE).find(t)
?: Regex("^git@github\\.com:([\\w.-]+)/([\\w.-]+)", RegexOption.IGNORE_CASE).find(t)
?: Regex("^([\\w.-]+)/([\\w.-]+)/?$").find(t) ?: return null
val repo = m.groupValues[2].removeSuffix(".git")
return if (repo.isEmpty() || repo == "." || repo == "..") null else "${m.groupValues[1]}/$repo"
}
/** The ARM64 AppImage among a release's files: named for aarch64/arm64, else for no other CPU. */
internal fun pickAsset(names: List<String>): String? {
val images = names.filter { it.endsWith(".appimage", ignoreCase = true) }
return images.firstOrNull { Regex("aarch64|arm64", RegexOption.IGNORE_CASE).containsMatchIn(it) }
?: images.firstOrNull { !Regex("x86_64|x86-64|amd64|x64|i[36]86|armhf|armv7", RegexOption.IGNORE_CASE).containsMatchIn(it) }
}
/** The newest release of [repo] with an ARM64 AppImage, preferring full releases; else what went wrong. */
private fun latestRelease(context: Context, repo: String): Pair<Release?, String?> {
val body = Downloader.downloadString("https://api.github.com/repos/$repo/releases?per_page=15")
val releases = body?.let { runCatching { JSONArray(it) }.getOrNull() }
?: return null to context.getString(R.string.user_apps_github_unreachable, repo)
val candidates = (0 until releases.length()).mapNotNull { i ->
val r = releases.getJSONObject(i)
if (r.optBoolean("draft")) return@mapNotNull null
val assets = r.optJSONArray("assets") ?: return@mapNotNull null
val byName = (0 until assets.length()).associate { j -> assets.getJSONObject(j).let { it.getString("name") to it.getString("browser_download_url") } }
pickAsset(byName.keys.toList())?.let { asset ->
r.optBoolean("prerelease") to Release(r.optString("tag_name", asset), r.optString("published_at"), asset, byName.getValue(asset))
}
}
val pick = (candidates.firstOrNull { !it.first } ?: candidates.firstOrNull())?.second
return pick to if (pick == null) context.getString(R.string.user_apps_github_no_appimage, repo) else null
}
/** Downloads [release] and hands it to [use]; null on success, else what went wrong. */
private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? {
val download = File(context.cacheDir, "github-${release.asset}")
try {
val label = context.getString(R.string.user_apps_downloading, release.asset)
val ok = Downloader.downloadFile(release.url, download, false) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
return if (ok) use(download) else context.getString(R.string.user_apps_download_failed)
} finally {
download.delete()
}
}
private fun githubMeta(repo: String, release: Release) =
mapOf(GITHUB_REPO to repo, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published)
private fun addFromGitHub(context: Context, repo: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
onProgress(context.getString(R.string.user_apps_github_checking, repo), -1)
val (release, problem) = latestRelease(context, repo)
if (release == null) return problem
return withDownload(context, release, onProgress) { file ->
AppImageManager.import(context, file, name ?: repo.substringAfter('/'), icon, githubMeta(repo, release)) { onProgress(it, -1) }
}
}
/**
* Images in [repo] that look like its icon, best first, then its owner's picture: links to show
* as suggestions and to download once one is picked.
*/
fun githubIcons(repo: String): List<String> {
val info = Downloader.downloadString("https://api.github.com/repos/$repo")?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return emptyList()
val branch = info.optString("default_branch").ifEmpty { return emptyList() }
val avatar = info.optJSONObject("owner")?.optString("avatar_url")?.takeIf { it.startsWith("https://") }
val tree = Downloader.downloadString("https://api.github.com/repos/$repo/git/trees/${Uri.encode(branch)}?recursive=1")
?.let { runCatching { JSONObject(it).optJSONArray("tree") }.getOrNull() }
val project = repo.substringAfter('/').lowercase().replace(Regex("[^a-z0-9]"), "")
val images = (0 until (tree?.length() ?: 0)).mapNotNull { i ->
val entry = tree!!.getJSONObject(i)
val path = entry.optString("path")
val size = entry.optLong("size")
val file = path.substringAfterLast('/').lowercase()
val stem = file.substringBeforeLast('.').replace(Regex("[^a-z0-9]"), "")
if (entry.optString("type") != "blob" || size !in 512..ICON_FILE_LIMIT || file.substringAfterLast('.') !in ICON_TYPES) return@mapNotNull null
if (IGNORED_DIRS.containsMatchIn(path)) return@mapNotNull null
val score = listOf("icon" in stem, "logo" in stem, project.isNotEmpty() && project in stem, "icon" in path.lowercase()).count { it }
if (score == 0) null else Triple(path, score, size)
}.sortedWith(compareByDescending<Triple<String, Int, Long>> { it.second }.thenByDescending { it.third })
val urls = images.take(ICON_SUGGESTIONS).map { (path, _, _) ->
"https://raw.githubusercontent.com/$repo/${Uri.encode(branch)}/" + path.split('/').joinToString("/") { Uri.encode(it) }
}
return urls + listOfNotNull(avatar)
}
/** Whether [app], added from GitHub, has a newer release than the one it is. */
fun checkUpdate(context: Context, app: App): UpdateCheck {
val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
val (release, problem) = latestRelease(context, repo)
if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed))
val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty()
// Releases are compared by date, so a newest one without an ARM64 build never reads as a downgrade.
val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version
return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
}
fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? {
val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed)
return withDownload(context, release, onProgress) { file ->
AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) }
}
}
/** A Flathub app ID from what was typed: the ID itself or its Flathub page. */
fun flatpakId(input: String): String? {
val t = input.trim().removeSuffix("/").substringAfterLast('/')
return t.takeIf { Regex("^[A-Za-z][\\w-]*(\\.[A-Za-z0-9_][\\w-]*){2,}$").matches(it) }
}
private fun addFlatpak(context: Context, id: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
if (!FlatpakManager.ready(context)) FlatpakManager.setup(context, onProgress)?.let { return it }
FlatpakManager.install(context, id, onProgress)?.let { return it }
val custom = overrides(context, id)
if (name != null) FileUtils.writeString(File(custom.apply { mkdirs() }, "name"), name)
if (icon != null && !saveIcon(icon, File(custom, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
return null
}
}
@@ -18,15 +18,11 @@ import kotlin.math.abs
* from Android's own battery API - the same on every device - into a directory the session binds
* over `/sys/class/power_supply`, refreshed every few seconds while the session runs.
*
* Steam's Quick Access Menu takes its time estimates from neither: it reads the files in `/run/vpower` (as on
* SteamOS), and with those absent showed "?h ?m" for projected battery life and for time to full.
* The same estimates are written there too, into [vpowerDir] in the guest's own `/run`.
*
* Values: charge in µAh from the charge counter; energy in µWh from charge × voltage; power in µW
* from |current| × voltage; time to empty from charge ÷ |average current| while discharging. Where
* a device reports no current, the client still gets status and percentage.
*/
class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart() {
class BatteryComponent(val dir: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
@@ -46,8 +42,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
running = false
thread?.interrupt()
thread = null
// Stale estimates would outlive the session in the rootfs; Steam falls back to "?h ?m".
for (name in VPOWER_FILES) File(vpowerDir, name).delete()
}
private fun write() {
@@ -121,17 +115,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
for ((k, v) in attrs) uevent.append("POWER_SUPPLY_").append(k.uppercase()).append('=').append(v).append('\n')
put(File(bat, "uevent"), uevent.toString())
}
val plugged = (sticky?.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) ?: 0) != 0
vpowerDir.mkdirs()
val vpower = linkedMapOf(
"ac_status" to if (plugged) "Connected" else "Disconnected",
"battery_percent" to "%.2f".format(java.util.Locale.ROOT, pct.toDouble()),
"battery_status" to statusText,
// Steam reads a separate file for each direction; -1 = no estimate.
"secs_until_battery_full" to (if (timeToFullS > 0) timeToFullS else -1L).toString(),
"secs_until_shutdown_request" to (if (timeToEmptyS > 0) timeToEmptyS else -1L).toString(),
)
for ((k, v) in vpower) put(File(vpowerDir, k), v + "\n")
} catch (t: Throwable) {
Log.w(TAG, "battery: could not write", t)
}
@@ -147,9 +130,5 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
companion object {
private const val TAG = "SessionService"
private const val PERIOD_MS = 5_000L
private val VPOWER_FILES = listOf(
"ac_status", "battery_percent", "battery_status",
"secs_until_battery_full", "secs_until_shutdown_request",
)
}
}
@@ -1,110 +0,0 @@
package com.droiddeck.launcher.session
import android.os.SystemClock
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import java.io.File
/**
* A `/proc/stat` that moves.
*
* Android has refused apps `/proc/stat` since 8.0, and the session's stand-in for it was one
* `cpu0` line of zeros - enough for glibc and Steam to start, but every CPU load in the session
* read 0 % (the performance overlay showed one core, idle). The kernel still lets apps read each
* core's idle residency (`cpuidle/stateN/time`, µs, the same label as the cpufreq files), which is
* how overlays on Android work out CPU load: a core's busy time is the time that passed less the
* time it spent idle. This writes `/proc/stat` from that, one line per core, refreshed twice a
* second. Counters only grow - a sample's idle is never more than the time that passed - so a
* reader taking the difference of two reads never sees a negative. Where `/proc/stat` is readable,
* or the idle times are not, nothing is done.
*/
class CpuStatComponent(val file: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private val cores = (0 until coreCount()).toList()
private val busy = LongArray(cores.size)
private val idle = LongArray(cores.size)
private val lastIdleUs = LongArray(cores.size)
private var lastMs = 0L
private val bootSeconds = (System.currentTimeMillis() - SystemClock.elapsedRealtime()) / 1000
/** Writes the first sample; true when it should be bound over `/proc/stat`. */
fun prepare(): Boolean {
if (File("/proc/stat").canRead() || cores.isEmpty() || idleUs(0) == null) return false
lastMs = SystemClock.elapsedRealtime()
for (i in cores) lastIdleUs[i] = idleUs(i) ?: 0L
write()
Log.i(TAG, "hud: /proc/stat from the cores' idle times (${cores.size} cores)")
return true
}
override fun start() {
running = true
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (!running) break
sample()
write()
}
}, "cpu-stat").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
}
private fun sample() {
val now = SystemClock.elapsedRealtime()
val elapsed = (now - lastMs) / MS_PER_TICK
if (elapsed <= 0) return
lastMs += elapsed * MS_PER_TICK
for (i in cores) {
// An offline core has no idle residency to count and runs nothing: all idle.
val us = idleUs(i)
val idleTicks = if (us == null) elapsed else ((us - lastIdleUs[i]) / US_PER_TICK).coerceIn(0, elapsed)
if (us != null) lastIdleUs[i] = us
idle[i] += idleTicks
busy[i] += elapsed - idleTicks
}
}
/** The whole file at once, renamed into place: a reader opens either the last sample or this one. */
private fun write() {
val text = StringBuilder()
text.append("cpu ${busy.sum()} 0 0 ${idle.sum()} 0 0 0 0 0 0\n")
for (i in cores) text.append("cpu$i ${busy[i]} 0 0 ${idle[i]} 0 0 0 0 0 0\n")
text.append("intr 0\nctxt 0\nbtime $bootSeconds\nprocesses 1\nprocs_running 1\nprocs_blocked 0\n")
try {
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeText(text.toString())
if (!tmp.renameTo(file)) tmp.delete()
} catch (e: Exception) {
}
}
companion object {
private const val TAG = "SessionService"
private const val PERIOD_MS = 500L
/** /proc/stat counts in USER_HZ, 100 a second on every Linux the guest runs. */
private const val MS_PER_TICK = 10L
private const val US_PER_TICK = 10_000L
private fun coreCount(): Int =
File("/sys/devices/system/cpu").list()?.count { it.matches(Regex("cpu\\d+")) } ?: 0
/** The core's total idle residency in µs, or null when it has none to read (offline). */
private fun idleUs(core: Int): Long? {
val states = File("/sys/devices/system/cpu/cpu$core/cpuidle").listFiles { f -> f.name.startsWith("state") }
?: return null
if (states.isEmpty()) return null
var total = 0L
for (state in states) {
total += runCatching { File(state, "time").readText().trim().toLong() }.getOrNull() ?: return null
}
return total
}
}
}
@@ -1,70 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
/**
* The GPU held at its top clock for a session, without root: KGSL's power-control property turned
* off on /dev/kgsl-3d0, the node the driver already opens (adrenotools' "turbo"). Left to itself the
* governor lets the GPU sit low between bursts, and a frame that lands on a low clock is a hitch;
* Bannerlator measured the clock going from 231 to 1000 MHz with this set. It costs power and heat,
* so it is opt-in, and the kernel's thermal limits still apply on top of it.
*
* The property belongs to the device, not to this process, and a killed app cannot unwind it: it
* is cleared when a session stops, and at the next app start when a marker file says this app set
* it and never cleared it - only then, so another app's own setting is not undone.
* (Bannerlator, PerfGpuTurbo.)
*/
object GpuClockPin {
private const val TAG = "GpuClockPin"
private const val KGSL_NODE = "/dev/kgsl-3d0"
private const val MARKER = "gpu-clock-pinned"
@Volatile
private var pinned = false
private val supported: Boolean by lazy { File(KGSL_NODE).exists() }
/** At a session's start: pins the clock when the user asked for it. The line is for the log. */
@Synchronized
fun start(context: Context): String {
if (!SessionPrefs.gpuClockPin(context)) return "gpu clock: governed"
if (!supported) return "gpu clock: no $KGSL_NODE, left governed"
return try {
File(context.filesDir, MARKER).createNewFile()
WaylandCompositor.nativeSetGpuTurbo(true)
pinned = true
"gpu clock: held at its top"
} catch (t: Throwable) {
Log.w(TAG, "pin", t)
"gpu clock: pin failed"
}
}
/** At a session's end. */
@Synchronized
fun stop(context: Context) {
if (pinned) clear(context)
}
/** At the app's start: a process killed with the clock pinned left only the marker behind. */
@Synchronized
fun clearLeftover(context: Context) {
if (File(context.filesDir, MARKER).exists()) clear(context)
}
private fun clear(context: Context) {
if (supported) {
try {
WaylandCompositor.nativeSetGpuTurbo(false)
} catch (t: Throwable) {
Log.w(TAG, "clear", t)
}
}
pinned = false
File(context.filesDir, MARKER).delete()
}
}
@@ -1,118 +0,0 @@
package com.droiddeck.launcher.session
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import java.io.File
/**
* The GPU memory in use, for the performance overlay's VRAM and PVRAM lines.
*
* Valve's mangoapp reads it from the kernel's gpu_mem_total tracepoint, which no Android app may
* reach, so both lines read 0. Our libtracefs for mangoapp (tools/mangoapp/libtracefs-shim.c) hands
* it what this writes to [file] - `/run/droiddeck-hud/gpu-mem` in the guest - every few seconds, in
* bytes, from the best of what KGSL lets the app read:
*
* - `/sys/class/kgsl/kgsl/page_alloc`, every GPU page on the device - what the tracepoint's total
* counts, where the policy allows it;
* - else KGSL's own accounting of each of the session's processes
* (`/sys/class/kgsl/kgsl/proc/<pid>/gpumem_mapped` and `gpumem_unmapped`);
* - else the size of the KGSL mappings in each of the session's processes' `maps` - only the
* buffers the CPU has mapped, so less than the GPU holds (about 40 % of KGSL's own count in a
* game on an AYN Thor), but always readable: every process the app can see in `/proc` is one of
* its own. `maps` rather than `smaps`, which gives the same sizes but walks page tables to do it:
* in a game, 180,000 lines and most of a second of CPU a pass.
*
* Sampled only while the overlay shows (OverlayShown).
*/
class GpuMemComponent(private val file: File, private val root: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private var source = ""
/** True when there is a source to write from. */
fun prepare(): Boolean {
val bytes = sample() ?: return false
write(bytes)
Log.i(TAG, "hud: gpu memory from $source (${bytes / (1024 * 1024)} MiB now)")
return true
}
override fun start() {
running = true
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (running && OverlayShown.check(root)) sample()?.let { write(it) }
}
}, "gpu-mem").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
file.delete()
}
private fun sample(): Long? {
readLong("$KGSL_ROOT/page_alloc")?.let { source = "$KGSL_ROOT/page_alloc"; return it }
val pids = sessionPids()
var perProcess = 0L
var anyProcess = false
for (pid in pids) {
val mapped = readLong("$KGSL_ROOT/proc/$pid/gpumem_mapped") ?: continue
perProcess += mapped + (readLong("$KGSL_ROOT/proc/$pid/gpumem_unmapped") ?: 0L)
anyProcess = true
}
if (anyProcess) { source = "$KGSL_ROOT/proc/<pid>/gpumem_*"; return perProcess }
var mappedKb = 0L
var anyMap = false
for (pid in pids) {
val kb = kgslMappedKb(pid) ?: continue
mappedKb += kb
anyMap = true
}
if (anyMap) { source = "/proc/<pid>/maps (KGSL mappings)"; return mappedKb * 1024 }
return null
}
/** The processes this app may see in /proc: Android hides every other uid's. */
private fun sessionPids(): List<String> =
File("/proc").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) }.orEmpty()
/** Size of a process's mappings of the KGSL device, in kB; null where its maps cannot be read. */
private fun kgslMappedKb(pid: String): Long? = runCatching {
var bytes = 0L
File("/proc/$pid/maps").forEachLine { line ->
if (line.endsWith("kgsl-3d0") || line.contains("/dev/dri/renderD")) {
val dash = line.indexOf('-')
val space = line.indexOf(' ')
if (dash > 0 && space > dash) {
bytes += line.substring(dash + 1, space).toLong(16) - line.substring(0, dash).toLong(16)
}
}
}
bytes / 1024
}.getOrNull()
/** Whole, renamed into place: the reader opens either the last value or this one. */
private fun write(bytes: Long) {
try {
file.parentFile?.mkdirs()
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeText("$bytes\n")
if (!tmp.renameTo(file)) tmp.delete()
} catch (e: Exception) {
}
}
companion object {
private const val TAG = "SessionService"
private const val KGSL_ROOT = "/sys/class/kgsl/kgsl"
/** GPU memory moves slowly; a pass over every process's maps is ~40 ms of CPU in a game. */
private const val PERIOD_MS = 5_000L
private fun readLong(path: String): Long? =
runCatching { File(path).readText().trim().toLong() }.getOrNull()
}
}
@@ -1,174 +0,0 @@
package com.droiddeck.launcher.session
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.RandomAccessFile
/**
* The Adreno's stats as mangoapp (Deck mode's performance overlay) reads them.
*
* MangoHud takes an Adreno's load, clock and temperature from `gpu_busy_percentage`, `clock_mhz`
* and `temp` in `/sys/class/kgsl/kgsl-3d0`, and ends the process on one of them it may not read -
* not on one that is missing, which it skips. An enforcing SELinux policy (every retail phone)
* refuses apps some or all of KGSL's sysfs, each vendor differently, so mangoapp died on start and
* the session ran with no overlay. Where any of the three is refused, a directory of our own is
* bound there instead. A value with no
* readable source is left out, and the overlay shows no line for it. Where all three are
* readable, nothing is done.
*
* Valve's build also reads load and clock where a mainline msm kernel has them (debugfs
* `perf_now`, the GPU's devfreq `cur_freq` in Hz) - the paths LinuxRuntime.bindAdrenoStats points
* at KGSL's own files when it may - so the same values are fed there too, in the same formats
* ([binds]).
*/
class GpuStatsComponent(val dir: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private val feeds = ArrayList<Feed>()
/** One of MangoHud's files and where its value comes from. */
private class Feed(
val file: File, val source: String, val read: () -> Long?, val format: String, val percent: Boolean = false,
)
/** Where Valve's msm reader looks, and the feed for it, as host:guest binds. */
fun binds(): List<String> {
val list = mutableListOf(dir.path + ":" + KGSL)
if (File(dir, "perf_now").exists()) list.add(File(dir, "perf_now").path + ":" + MSM_LOAD)
if (File(dir, "cur_freq").exists()) list.add(File(dir, "cur_freq").path + ":" + MSM_CLOCK)
return list
}
/** Writes the directory; true when it should be bound over [KGSL]. */
fun prepare(): Boolean {
if (!File(KGSL).exists() || MANGOHUD_FILES.none { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }) return false
return try {
dir.mkdirs()
dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) }
feeds.clear()
loadFeed()?.let { load ->
feeds.add(load)
// KGSL's gpu_busy_percentage reads "37 %"; padded after, so a shorter value
// written over a longer one leaves no digits behind.
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
}
pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) }?.let { clock ->
feeds.add(clock)
feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n"))
}
pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
feeds.forEach { feed -> feed.read()?.let { write(feed, it) } }
Log.i(TAG, "hud: kgsl stats from the session's own: " + MANGOHUD_FILES.joinToString { name ->
"$name " + (feeds.firstOrNull { it.file.name == name }?.source ?: "none")
})
true
} catch (e: Exception) {
Log.w(TAG, "hud: could not stand in for kgsl stats: $e")
false
}
}
override fun start() {
if (feeds.isEmpty()) return
running = true
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (!running) break
for (feed in feeds) feed.read()?.let { write(feed, it) }
}
}, "gpu-stats").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
}
/** Load: a file that states it in percent, else KGSL's busy and total of the last sample. */
private fun loadFeed(): Feed? {
pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }?.let { return it }
val gpubusy = "$KGSL/gpubusy"
val read = {
runCatching {
val parts = File(gpubusy).readText().trim().split(Regex("\\s+"))
val total = parts[1].toLong()
if (total > 0) (parts[0].toLong() * 100 / total).coerceIn(0, 100) else 0L
}.getOrNull()
}
return if (read() != null) Feed(File(dir, "gpu_busy_percentage"), gpubusy, read, "%3d %%\n") else null
}
/** The first of [sources] that reads as a number, its value put in MangoHud's unit by [unit]. */
private fun pick(name: String, sources: List<String>, format: String, unit: (Long) -> Long?): Feed? {
for (source in sources) {
val read = { firstNumber(source)?.let(unit) }
if (read() != null) return Feed(File(dir, name), source, read, format)
}
return null
}
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
private fun write(feed: Feed, value: Long) {
try {
val text = if (feed.percent) String.format(feed.format, "$value %") else String.format(feed.format, value)
RandomAccessFile(feed.file, "rw").use { it.seek(0); it.write(text.toByteArray()) }
} catch (e: Exception) {
}
}
companion object {
private const val TAG = "SessionService"
const val KGSL = "/sys/class/kgsl/kgsl-3d0"
/** Must match LinuxRuntime.bindAdrenoStats. */
const val MSM_LOAD = "/sys/kernel/debug/dri/0/perf_now"
const val MSM_CLOCK = "/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"
private const val PERIOD_MS = 500L
private val MANGOHUD_FILES = listOf("gpu_busy_percentage", "clock_mhz", "temp")
/** Qualcomm's own GPU summary, beside KGSL in vendor kernels, under the plain sysfs label. */
private const val QCOM_GPU = "/sys/kernel/gpu"
private val LOAD_SOURCES = listOf(
"$KGSL/gpu_busy_percentage", "$KGSL/devfreq/gpu_load", "$KGSL/gpuload", "$QCOM_GPU/gpu_busy",
)
/** The GPU's devfreq node is named by its register address, which differs between Snapdragons. */
private val DEVFREQ_NODES = listOf(
"kgsl-3d0", "3d00000.qcom,kgsl-3d0", "2c00000.qcom,kgsl-3d0", "5000000.qcom,kgsl-3d0", "5900000.qcom,kgsl-3d0",
)
private fun clockSources(): List<String> {
val sources = mutableListOf(
"$KGSL/clock_mhz", "$KGSL/gpu_clock", "$KGSL/gpuclk", "$KGSL/devfreq/cur_freq", "$QCOM_GPU/gpu_clock",
)
DEVFREQ_NODES.forEach { sources.add("/sys/class/devfreq/$it/cur_freq") }
File("/sys/class/devfreq").list()?.sorted()?.forEach { node ->
if (node.contains("kgsl") || node.contains("gpu")) sources.add("/sys/class/devfreq/$node/cur_freq")
}
return sources.distinct()
}
private fun tempSources(): List<String> =
listOfNotNull("$KGSL/temp", "$KGSL/devfreq/temp", "$QCOM_GPU/temp", LinuxRuntime.gpuTempSource()).distinct()
/** The first integer in the file ("550", "37 %", "550000000"), or null. */
private fun firstNumber(path: String): Long? =
runCatching { Regex("-?\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
/** Hz, kHz or MHz to MHz, as the files differ; a stopped clock reads 0. */
private fun mhz(raw: Long): Long? = when {
raw < 0 -> null
raw > 10_000_000 -> raw / 1_000_000
raw > 10_000 -> raw / 1_000
else -> raw
}
/** °C or m°C to MangoHud's m°C; nothing a GPU reads at is below 1 °C or above 1000. */
private fun milliCelsius(raw: Long): Long? = when {
raw <= 0 -> null
raw < 1000 -> raw * 1000
else -> raw
}
}
}
@@ -1,141 +0,0 @@
package com.droiddeck.launcher.session
import android.os.SystemClock
import android.system.Os
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.RandomAccessFile
/**
* The session's `/sys/class/hwmon`, as mangoapp (Deck mode's performance overlay) looks there.
*
* MangoHud finds a CPU's temperature by an hwmon sensor named `cpuN_thermal`, and an Adreno's
* temperature, fan and power by one whose name has `gpuss` in it - a mainline Arm kernel's names.
* An Android kernel has neither (its hwmon holds the PMIC's sensors, or nothing), and where the
* app may not list hwmon at all the overlay logged an error twice a second. So the overlay showed
* no CPU temperature and no fan. This is two sensors named so:
*
* - `hwmon0` (`cpu0_thermal`): `temp1_input` linked to a CPU thermal zone the app can read;
* - `hwmon1` (`gpuss0_thermal`): `temp1_input` linked to the GPU's zone, and `fan1_input` with
* the device's fan speed where it has a fan the app can read - an AYN handheld's tachometer
* (`/sys/class/gpio5_pwm2/speed`), or a `fan*_input` in the device's own hwmon;
* - `hwmon2` (`slg4ax46073v`): the same fan, for Valve's own Qualcomm reader (msm.cpp), which
* looks for its fan controller by that name and halves what it reads - that part reports twice
* the real speed - so this one holds twice it.
*
* Nothing in a phone's own hwmon is read by the overlay, so standing in for it loses nothing.
*/
class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private var fanSource: String? = null
private val fanFile = File(dir, "hwmon1/fan1_input")
private val valveFanFile = File(dir, "hwmon2/fan1_input")
private var lastRpm = 0L
private var lastRpmAt = 0L
/** Writes the sensors; true when the directory should be bound over `/sys/class/hwmon`. */
fun prepare(): Boolean = try {
dir.mkdirs()
clear(dir)
val cpu = LinuxRuntime.cpuTempSource()
if (cpu != null) sensor("hwmon0", "cpu0_thermal").also { link(cpu, File(it, "temp1_input")) }
val gpu = LinuxRuntime.gpuTempSource()
fanSource = FAN_SOURCES().firstOrNull { readNumber(it) != null }
if (gpu != null || fanSource != null) {
val sensor = sensor("hwmon1", "gpuss0_thermal")
if (gpu != null) link(gpu, File(sensor, "temp1_input"))
if (fanSource != null) {
sensor("hwmon2", "slg4ax46073v")
writeFan(sampleFan())
}
}
Log.i(TAG, "hud: hwmon cpu temp ${cpu ?: "none"}, gpu temp ${gpu ?: "none"}, fan ${fanSource ?: "none"}")
cpu != null || gpu != null || fanSource != null
} catch (e: Exception) {
Log.w(TAG, "hud: could not write the session's hwmon: $e")
false
}
override fun start() {
if (fanSource == null) return
running = true
thread = Thread({
while (running) {
try { Thread.sleep(FAN_PERIOD_MS) } catch (e: InterruptedException) { break }
// A tachometer read busy-waits 100 ms in the kernel: only while the overlay shows.
if (running && OverlayShown.check(root)) writeFan(sampleFan())
}
}, "hwmon-fan").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
}
/**
* The fan's speed in RPM. An AYN tachometer counts pulses over a short window per read and
* often catches none, reading 0 while the fan turns; a reading is held until a newer one
* comes or [FAN_HOLD_MS] passes with only zeros, when the fan is taken to have stopped.
*/
private fun sampleFan(): Long {
val now = SystemClock.elapsedRealtime()
val rpm = fanSource?.let { readNumber(it) } ?: 0L
if (rpm > 0) {
lastRpm = rpm
lastRpmAt = now
} else if (now - lastRpmAt > FAN_HOLD_MS) {
lastRpm = 0
}
return lastRpm
}
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
private fun writeFan(rpm: Long) {
for ((file, value) in listOf(fanFile to rpm, valveFanFile to rpm * 2)) {
try {
RandomAccessFile(file, "rw").use { it.seek(0); it.write(String.format("%6d\n", value).toByteArray()) }
} catch (e: Exception) {
}
}
}
private fun sensor(name: String, label: String): File =
File(dir, name).apply { mkdirs(); File(this, "name").writeText("$label\n") }
private fun link(target: String, link: File) {
java.nio.file.Files.deleteIfExists(link.toPath())
Os.symlink(target, link.path)
}
/** Only files and links are made here; deleting a link must not follow it into sysfs. */
private fun clear(root: File) {
root.listFiles()?.forEach { f ->
if (!java.nio.file.Files.isSymbolicLink(f.toPath()) && f.isDirectory) clear(f)
java.nio.file.Files.deleteIfExists(f.toPath())
}
}
companion object {
private const val TAG = "SessionService"
/** The AYN tachometer reads 0 if read again within a couple of seconds. */
private const val FAN_PERIOD_MS = 3_000L
private const val FAN_HOLD_MS = 10_000L
private val FAN_SOURCES = {
val sources = mutableListOf("/sys/class/gpio5_pwm2/speed", "/sys/class/gpio5_pwm/speed")
File("/sys/class/hwmon").listFiles()?.sortedBy { it.name }?.forEach { hwmon ->
hwmon.listFiles { f -> f.name.matches(Regex("fan\\d+_input")) }?.sortedBy { it.name }
?.forEach { sources.add(it.path) }
}
sources
}
private fun readNumber(path: String): Long? =
runCatching { File(path).readText().trim().toLong() }.getOrNull()?.takeIf { it >= 0 }
}
}
@@ -1,17 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
/**
* Whether Deck mode's performance overlay is on screen. The client sets its level by rewriting
* mangoapp's config (bannerlator-session makes it, `/tmp/mangohud.*`), and `no_display` is the
* level that hides it. The feeds whose reads cost something - the fan's tachometer busy-waits in
* the kernel, GPU memory walks every process's mappings - only run while it shows.
*/
object OverlayShown {
fun check(root: File): Boolean {
val config = File(root, "tmp").listFiles { f -> f.name.startsWith("mangohud.") }
?.maxByOrNull { it.lastModified() } ?: return false
return runCatching { !config.readText().contains("no_display") }.getOrDefault(false)
}
}
@@ -8,9 +8,7 @@ import android.os.SystemClock
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.util.Locale
@@ -21,9 +19,8 @@ import java.util.concurrent.atomic.AtomicInteger
* is on, what the screen is actually being shown - "60 → 118 fps" is the proof that the engine
* is doing something, and "FG starting" or a reason is the proof that it is not.
*
* The base rate is the game window's own frames, counted here from the compositor's per-frame
* callback with or without an engine - what Steam's overlay counts too. The presented rate comes
* from the engine's telemetry while it generates.
* The base rate is counted here from the compositor's per-frame callback, so it is right with or
* without an engine. The presented rate comes from the engine's own telemetry while it generates.
*/
class PerfHud(context: Context) {
/** Empty when the HUD is off or not yet started. */
@@ -89,19 +86,20 @@ class PerfHud(context: Context) {
}
private fun line(base: Float): String {
val mode = FrameGen.mode(context)
if (mode.engine == FrameGen.ENGINE_OFF) return fps(base)
val lsfg = mode.engine == FrameGen.ENGINE_LSFG
val name = if (lsfg) "LSFG" else "Win-FG"
val label = FrameGen.label(context, mode)
if (lsfg && Lossless.cacheFile(context)?.isFile != true) return context.getString(R.string.hud_fg_needs_lossless, name)
val engine = FrameGen.engine(context)
if (engine == FrameGen.ENGINE_OFF) return fps(base)
val name = if (engine == FrameGen.ENGINE_LSFG) "LSFG" else "Win-FG"
val multiplier = FrameGen.multiplier(context)
val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null }
val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 }
return when {
problem == 1 -> context.getString(R.string.hud_fg_unsupported, name)
problem == 2 -> context.getString(R.string.hud_fg_failed, name)
stats != null && stats[3] > 1f -> String.format(Locale.US, "%s %.0f → %.0f fps", label, base, stats[3])
else -> context.getString(R.string.hud_fg_starting, label, fps(base))
problem == 1 -> "$name: unsupported"
problem == 2 -> "$name: engine failed"
stats != null && stats[3] > 1f -> {
val source = if (stats[2] > 1f) stats[2] else base
String.format(Locale.US, "%s %d× %.0f → %.0f fps", name, multiplier, source, stats[3])
}
else -> String.format(Locale.US, "%s %d× %s · FG starting", name, multiplier, fps(base))
}
}
@@ -17,8 +17,7 @@ import android.util.Log
* Big Picture their peak clocks. WinNative never asks for it; the thermal budget is left to
* the game;
* - the panel's fastest mode at its current size (Android 6+): a 120 Hz phone is switched to
* 120 Hz for the menu, not only when a game votes for it. With a frame cap, the fastest mode
* the cap divides evenly, so every capped frame is shown for the same number of refreshes;
* 120 Hz for the menu, not only when a game votes for it;
* - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases
* its boost on loading screens or menus keeps it up.
*
@@ -28,7 +27,7 @@ import android.util.Log
object PerfMode {
private const val TAG = "PerfMode"
fun apply(a: Activity, fpsLimit: Int = 0): String {
fun apply(a: Activity): String {
val parts = ArrayList<String>(2)
// The fastest display mode at the panel's current size.
@@ -36,12 +35,10 @@ object PerfMode {
val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay
if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else {
val cur = display.mode
val sameSize = display.supportedModes
val best = display.supportedModes
.filter { it.physicalWidth == cur.physicalWidth && it.physicalHeight == cur.physicalHeight }
val best = sameSize.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate }
?: sameSize.maxByOrNull { it.refreshRate }
if (best != null && best.modeId != cur.modeId &&
(best.refreshRate > cur.refreshRate + 0.5f || !cadenceFits(cur.refreshRate, fpsLimit))) {
.maxByOrNull { it.refreshRate }
if (best != null && best.modeId != cur.modeId && best.refreshRate > cur.refreshRate + 0.5f) {
a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = best.modeId }
"display ${cur.refreshRate.toInt()} → ${best.refreshRate.toInt()} Hz (mode ${best.modeId})"
} else "display ${cur.refreshRate.toInt()} Hz"
@@ -67,11 +64,4 @@ object PerfMode {
return parts.joinToString(" · ")
}
/** A panel rate that shows every capped frame for a whole number of refreshes (no cap: any). */
fun cadenceFits(hz: Float, fpsLimit: Int): Boolean {
if (fpsLimit <= 0) return true
val ratio = hz / fpsLimit
return ratio >= 0.98f && Math.abs(ratio - Math.round(ratio)) < 0.02f
}
}
@@ -1,94 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
import java.security.MessageDigest
import java.util.Locale
/** Android shared storage cannot create the links in Wine prefixes or native Steam depots. */
object SecondaryLibrary {
private val bootstrapTools = linkedMapOf(
"4185400" to "SteamLinuxRuntime_4-arm64",
"4427310" to "Proton Experimental (ARM64)",
"4628740" to "Proton 11.0 (ARM64)",
)
fun privateRoot(files: File, library: File): File {
val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray())
.joinToString("") { "%02x".format(it.toInt() and 255) }
return File(files, "steam-libraries/$digest")
}
/** Parent binds come first; the more specific private directories override them in PRoot. */
fun binds(files: File, library: File): List<String> {
val private = privateRoot(files, library)
val apps = File(library, "steamapps")
val tools = LinkedHashMap(bootstrapTools)
// Include other installed Proton/runtime versions, without routing ordinary game depots.
apps.listFiles()?.filter { it.name.matches(Regex("appmanifest_\\d+\\.acf")) }?.forEach { manifest ->
val text = manifest.readText()
val id = Regex("\"appid\"\\s+\"(\\d+)\"").find(text)?.groupValues?.get(1)
val dir = Regex("\"installdir\"\\s+\"([^\"]+)\"").find(text)?.groupValues?.get(1)
if (id != null && dir != null && File(dir).name == dir &&
(dir.startsWith("Proton ") || dir.startsWith("SteamLinuxRuntime"))) tools[id] = dir
}
val overrides = ArrayList<Pair<File, String>>()
for (name in listOf("compatdata", "shadercache")) {
val target = File(private, "steamapps/$name")
migrate(File(apps, name), target)
overrides.add(target to "steamapps/$name")
}
for ((id, dir) in tools) {
for (relative in listOf("steamapps/common/$dir", "steamapps/downloading/$id")) {
val target = File(private, relative)
migrate(File(library, relative), target)
// FUSE discarded the executable bits. Steam will restore the depot's exact modes
// on verification; its launchers must already be executable when importing it.
target.walkTopDown().filter { it.isFile }.forEach { it.setExecutable(true, true) }
overrides.add(target to relative)
// Steam normalizes depot install directories to lowercase on Android's
// case-insensitive shared storage. PRoot binds are case-sensitive, so both
// spellings must reach the same private directory during the commit.
val lower = relative.lowercase(Locale.ROOT)
if (lower != relative) overrides.add(target to lower)
}
}
return listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd").flatMap { guest ->
listOf("${library.path}:$guest") + overrides.map { (host, relative) -> "${host.path}:$guest/$relative" }
}
}
/** Copy once into a staging directory; retain the source and never merge over a live prefix. */
private fun migrate(source: File, target: File) {
val migrated = File(target.parentFile, ".${target.name}.migrated")
if (target.isDirectory) {
if (!migrated.isFile) migrated.writeText(source.canonicalPath)
return
}
check(target.parentFile!!.isDirectory || target.parentFile!!.mkdirs()) { "cannot create ${target.parent}" }
if (!source.isDirectory || migrated.isFile) {
check(target.mkdirs()) { "cannot create $target" }
if (!migrated.isFile) migrated.writeText(source.canonicalPath)
return
}
val stage = File(target.parentFile, "${target.name}.migrating")
check(!stage.exists() || stage.deleteRecursively()) { "cannot clear $stage" }
check(stage.mkdirs()) { "cannot create $stage" }
try {
Files.walk(source.toPath()).use { paths ->
paths.forEach { path ->
val destination = stage.toPath().resolve(source.toPath().relativize(path))
if (Files.isDirectory(path, NOFOLLOW_LINKS)) Files.createDirectories(destination)
else Files.copy(path, destination, NOFOLLOW_LINKS, COPY_ATTRIBUTES)
}
}
check(stage.renameTo(target)) { "cannot finish migration to $target" }
migrated.writeText(source.canonicalPath)
} catch (e: Exception) {
stage.deleteRecursively()
throw e
}
}
}
@@ -66,7 +66,7 @@ object SessionArtifacts {
fun scrubOlder(context: Context) {
val current = SessionPaths.current()
val dirs = LinuxRuntime.debugLogDir().listFiles { f ->
SessionPaths.isSessionFolder(f) && f != current && !File(f, SCRUBBED_MARKER).exists()
f.isDirectory && f.name.startsWith("session-") && f != current && !File(f, SCRUBBED_MARKER).exists()
} ?: return
if (dirs.isEmpty()) return
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
@@ -124,8 +124,8 @@ object SessionArtifacts {
fun finishAbandoned(context: Context) {
val parent = LinuxRuntime.debugLogDir()
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists()
}?.sortedWith(SessionPaths.chronological) ?: return
f.isDirectory && f.name.startsWith("session-") && !File(f, COMPLETE_MARKER).exists()
}?.sortedBy { it.name } ?: return
if (abandoned.isEmpty()) return
val current = SessionPaths.current()
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
@@ -157,37 +157,5 @@ object SessionArtifacts {
}
}
/**
* Keeps the newest [SessionPaths.KEEP_SESSIONS] session folders and deletes the rest: a few
* days of testing left hundreds, and the one a report needed was lost among them. Only folders
* that are finished; the session in progress is never touched. Runs at app start after
* [finishAbandoned], on its worker thread.
*/
@Synchronized
fun prune(context: Context) {
val current = SessionPaths.current()
val finished = SessionPaths.sessionFolders(context).filter { it != current && File(it, COMPLETE_MARKER).exists() }
val old = finished.dropLast(SessionPaths.KEEP_SESSIONS)
old.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
if (old.isNotEmpty()) Log.i(TAG, "deleted ${old.size} session folder(s) past the newest ${SessionPaths.KEEP_SESSIONS}")
}
/**
* Every session folder but the one in progress, and the one-off command logs (tools/, or loose
* beside the folders from before it): the Setup page's Clear logs. Returns how many session
* folders went.
*/
@Synchronized
fun clearAll(context: Context): Int {
val current = SessionPaths.current()
val gone = SessionPaths.sessionFolders(context).filter { it != current }
gone.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
com.droiddeck.launcher.core.FileUtils.delete(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR))
// Before tools/, those logs sat loose beside the session folders.
LinuxRuntime.debugLogDir().listFiles { f -> f.isFile && f.name.endsWith(".log") }?.forEach { it.delete() }
Log.i(TAG, "cleared ${gone.size} session folder(s)")
return gone.size
}
private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
}
@@ -11,12 +11,11 @@ object SessionEvents {
private const val TAG = "SessionEvents"
private val lock = Any()
/** [label] names the session's folder for what is being run (SessionPaths.label). */
fun begin(context: Context, mode: String, label: String? = null) {
fun begin(context: Context, mode: String) {
// A runtime-install failure can leave the folder claimed before the service ever starts.
// Keep that folder, but give the next attempt its own session directory.
SessionPaths.take()
val dir = SessionPaths.beginOrCurrent(context, label ?: SessionPaths.label(mode, null))
val dir = SessionPaths.beginOrCurrent(context)
synchronized(SessionState) {
SessionState.phase = SessionPhase.PREPARING
SessionState.mode = mode
@@ -5,7 +5,6 @@ import android.os.Environment
import android.util.Log
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import java.io.File
/** Everything the session needs written into the runtime before it starts. */
@@ -30,7 +29,6 @@ object SessionFiles {
"usr/local/bin/bannerlator-game-env" to "usr/local/bin/bannerlator-game-env",
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
@@ -51,7 +49,6 @@ object SessionFiles {
"usr/local/bin/bannerlator-flatpak-run" to "usr/local/bin/bannerlator-flatpak-run",
// The user's own AppImages, extracted at import (AppImageManager).
"usr/local/bin/bannerlator-appimage-run" to "usr/local/bin/bannerlator-appimage-run",
"usr/local/bin/bannerlator-script-run" to "usr/local/bin/bannerlator-script-run",
// The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
"usr/bin/steamos-update" to "usr/bin/steamos-update",
@@ -154,9 +151,6 @@ object SessionFiles {
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
// Last, so the others' opens and stats reach it through RTLD_NEXT. It stays idle in any
// process its proot did not describe to it (ProotFastPath).
if (ProotFastPath.enabled(context)) preload.append(ProotFastPath.LIBRARY + "\n")
val etc = File(root, "etc").apply { mkdirs() }
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
@@ -17,7 +17,10 @@ import java.util.zip.ZipOutputStream
*/
object SessionLogShare {
/** The newest session folder in either place logs are written, or null if there is none. */
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
fun latest(context: Context): File? =
listOf(LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
.flatMap { dir -> dir.listFiles { f -> f.isDirectory && f.name.startsWith("session-") }?.toList() ?: emptyList() }
.maxByOrNull { it.name }
/** Builds the zip (blocking). Returns null when there is no session to share. */
fun zipLatest(context: Context): File? = latest(context)?.let { zipFolder(context, it) }
@@ -33,40 +36,21 @@ object SessionLogShare {
// session pass yet, and the redactor changes nothing in a line that is already clean.
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
ZipOutputStream(zip.outputStream().buffered()).use { z ->
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f) }
liveSteamLogs(context, folder).forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f) }
files.forEach { f ->
z.putNextEntry(ZipEntry(folder.name + "/" + f.relativeTo(folder).path))
if (LogRedactor.isText(f)) {
val w = z.bufferedWriter()
LogRedactor.scrubTo(f, w)
w.flush()
} else {
f.inputStream().use { it.copyTo(z) }
}
z.closeEntry()
}
}
return zip
}
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
z.putNextEntry(ZipEntry(name))
if (LogRedactor.isText(f)) {
val w = z.bufferedWriter()
LogRedactor.scrubTo(f, w)
w.flush()
} else {
f.inputStream().use { it.copyTo(z) }
}
z.closeEntry()
}
/**
* The client's own logs as they stand, for a session shared while it runs. The session script
* copies them into steam/ only as it exits, so a zip made from the drawer had none - and
* controller.txt (which pad the client opened, the touch mode it set) is what a controller or
* touch report needs most. Only for the running session: an older folder would get this
* session's logs. The same files the script copies; nothing holding credentials is in logs/.
*/
private fun liveSteamLogs(context: Context, folder: File): List<File> {
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
}
/** The client's content and bootstrap logs grow large over months and say nothing about a session. */
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
fun shareIntent(context: Context, zip: File): Intent {
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", zip)
val send = Intent(Intent.ACTION_SEND)
@@ -8,24 +8,18 @@ import java.util.Date
import java.util.Locale
/**
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded,
* named for the day, that day's session number and what was run, so the one a report is about can
* be picked out without opening any:
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded:
*
* ```
* Download/DroidDeck/2026-09-30-03-steam/
* Download/DroidDeck/session-20260921-161256/
* device.txt what this device is, and every setting the session ran with
* session.log the guest session: proot, gamescope, the client's stdout
* wayland.log the app's compositor
* steam.log the Steam client's own log, scrubbed (Steam mode)
* steam/ the rest of the client's logs, scrubbed (Steam mode)
* desktop.log labwc, the panel and the programs on it (desktop mode)
* Download/DroidDeck/tools/ one-off commands: Flatpak installs, AppImage imports
* ```
*
* Folders from before this naming (`session-20260930-180642`) are still recognised, shared and
* pruned with the rest.
*
* The folder is claimed by whoever starts first - the activity starts the compositor before the
* service starts the session - so both write into the same one, and a recreated activity (a
* foldable opening mid-session) joins the folder in progress instead of opening another.
@@ -33,44 +27,24 @@ import java.util.Locale
object SessionPaths {
private const val TAG = "SessionPaths"
/** How many session folders are kept; older ones go at the next app start. */
const val KEEP_SESSIONS = 30
/** Beside the session folders: the logs of one-off commands (GuestCommand's logName). */
const val TOOLS_DIR = "tools"
/** `2026-09-30-03-steam`: day, that day's session number, what was run. */
private val NAMED = Regex("""^(\d{4})-(\d{2})-(\d{2})-(\d{2,})-.+$""")
/** `session-20260930-180642`, from before. */
private val LEGACY = Regex("""^session-(\d{8})-(\d{6})(-\d+)?$""")
@Volatile
private var dir: File? = null
@Volatile
private var ended: File? = null
/**
* The folder for the session now starting, or the one already in progress. With logs turned
* off on the main screen the folder lives in the app's cache instead of Downloads - the
* scripts and the compositor still need somewhere to write - and [release] deletes it.
* [label] says what is being run (see [label]); without one it comes from the session's state.
*/
@Synchronized
fun beginOrCurrent(context: Context, label: String? = null): File {
fun beginOrCurrent(context: Context): File {
dir?.let { if (it.isDirectory) return it }
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
else File(context.cacheDir, "session-logs")
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
// The day's highest number plus one, not a count: pruning removes the oldest folders, and
// a count would hand out a number already in use.
val last = parent.listFiles()?.mapNotNull { f ->
NAMED.matchEntire(f.name)?.takeIf { f.name.startsWith("$day-") }?.groupValues?.get(4)?.toIntOrNull()
}?.maxOrNull() ?: 0
val what = slug(label ?: label(SessionState.mode, SessionState.program))
var number = last + 1
var made = File(parent, "$day-${"%02d".format(Locale.US, number)}-$what")
while (made.exists()) made = File(parent, "$day-${"%02d".format(Locale.US, ++number)}-$what")
val baseName = "session-$stamp"
var made = File(parent, baseName)
var suffix = 2
while (made.exists()) made = File(parent, "$baseName-${suffix++}")
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
dir = made
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
@@ -79,9 +53,6 @@ object SessionPaths {
fun current(): File? = dir
/** The folder of the session that ended last, while it is still there: what its Share logs sends. */
fun lastEnded(): File? = ended?.takeIf { it.isDirectory }
/**
* The ending session takes its folder with it: the next session (one that replaces this one
* in place) then claims a folder of its own instead of sharing, and this one's collector
@@ -89,10 +60,9 @@ object SessionPaths {
*/
@Synchronized
fun take(): File? {
val taken = dir
val ended = dir
dir = null
if (taken != null) ended = taken
return taken
return ended
}
fun file(name: String): File? = dir?.let { File(it, name) }
@@ -108,39 +78,4 @@ object SessionPaths {
com.droiddeck.launcher.core.FileUtils.delete(ended)
}
}
/**
* What a session's folder is named for: Steam, the desktop, or the program started from the
* rail by its own name (`2026-10-01-02-retroarch`).
*/
fun label(mode: String, program: String?): String = when (mode) {
SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(program)
?: program?.substringAfterLast('/')
?: mode
SessionService.MODE_DESKTOP -> "desktop"
else -> mode
}
/** Whether [f] is a session's folder, in either naming. */
fun isSessionFolder(f: File): Boolean =
f.isDirectory && (NAMED.matches(f.name) || LEGACY.matches(f.name))
/**
* Oldest first: by day, then by when in the day. A folder from before the new naming sorts
* ahead of a new one from the same day, which it always predates.
*/
val chronological: Comparator<File> = compareBy { f ->
NAMED.matchEntire(f.name)?.groupValues?.let { g -> "${g[1]}${g[2]}${g[3]}1${g[4].padStart(6, '0')}" }
?: LEGACY.matchEntire(f.name)?.groupValues?.let { g -> "${g[1]}0${g[2]}${g[3].removePrefix("-").padStart(2, '0')}" }
?: f.name
}
/** Every session folder in the places logs are written, oldest first. */
fun sessionFolders(context: Context): List<File> =
listOf(com.droiddeck.launcher.runtime.LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
.flatMap { parent -> parent.listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList() }
.sortedWith(chronological)
internal fun slug(text: String): String =
text.lowercase(Locale.US).replace(Regex("[^a-z0-9]+"), "-").trim('-').take(24).trim('-').ifEmpty { "session" }
}
@@ -30,29 +30,25 @@ object SessionPrefs {
prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
}
/** The Flathub Store (beta): its rail item. Off by default. */
/** The Flathub Store (beta): its rail item and the Store's apps on the Desktop page. Off by default. */
fun storeEnabled(context: Context): Boolean = prefs(context).getBoolean("storeEnabled", false)
fun setStoreEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("storeEnabled", on).apply()
}
/**
* The session's performance HUD (the fps box). A Deck-mode Steam session with the performance
* overlay has Steam's own (mangoapp, from the QAM), so there the HUD is off unless turned on
* in one - a choice kept apart from every other session's, where it stays on by default.
*/
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), !mangoappSession(context))
/** AppImage import (beta): the AppImages section on the Desktop page. Off by default. */
fun appImagesEnabled(context: Context): Boolean = prefs(context).getBoolean("appImagesEnabled", false)
fun setHudEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean(hudKey(context), on).apply()
fun setAppImagesEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("appImagesEnabled", on).apply()
}
private fun hudKey(context: Context) = if (mangoappSession(context)) "hudDeck" else "hud"
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true)
/** A Steam session that runs Deck mode with its performance overlay (mangoapp). */
private fun mangoappSession(context: Context) =
SessionState.mode == SessionService.MODE_STEAM && steamDeckMode(context) && mangoapp(context)
fun setHudEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("hud", on).apply()
}
/** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
@@ -105,52 +101,15 @@ object SessionPrefs {
}
/**
* The imported glibc Turnip every session draws with inside the runtime - Steam, its games and
* the desktop alike, as they run on the same GPU; "" = the driver built into the runtime.
* Resolved by LinuxVulkanDriver at session start. It was once chosen per mode: the Steam
* session's choice, the one nearly everyone set, carries over.
* The imported glibc Turnip a mode draws with inside the runtime, keyed by
* SessionService.MODE_STEAM / MODE_DESKTOP so Steam and the desktop can differ; "" = the
* driver built into the runtime. Resolved by LinuxVulkanDriver at session start.
*/
fun linuxDriver(context: Context): String =
prefs(context).getString("linuxDriver", null)
?: prefs(context).getString("linuxDriver.steam", null)
?: prefs(context).getString("linuxDriver.desktop", "") ?: ""
fun linuxDriver(context: Context, mode: String): String =
prefs(context).getString("linuxDriver.$mode", "") ?: ""
fun setLinuxDriver(context: Context, id: String) {
prefs(context).edit().putString("linuxDriver", id).apply()
}
const val GPU_DRIVERS_AUTO = "auto"
const val GPU_DRIVERS_MANUAL = "manual"
/**
* Who picks the GPU drivers: [GPU_DRIVERS_AUTO] (the app, the matched pair recommended for
* this GPU, kept current - DriverPairs) or [GPU_DRIVERS_MANUAL] (the user). Auto for new
* installs; see settleGpuDriverMode.
*/
fun gpuDriverMode(context: Context): String =
prefs(context).getString("gpuDriverMode", GPU_DRIVERS_AUTO) ?: GPU_DRIVERS_AUTO
fun setGpuDriverMode(context: Context, mode: String) {
prefs(context).edit().putString("gpuDriverMode", mode).apply()
}
/**
* Auto arrived after people had picked drivers by hand: an install that chose either driver
* keeps its choice (Manual), everyone else is Auto. Decided once, at process start.
*/
fun settleGpuDriverMode(context: Context) {
val p = prefs(context)
if (p.contains("gpuDriverMode")) return
val chosen = androidDriver(context).isNotEmpty() || linuxDriver(context).isNotEmpty()
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
}
/** Drivers Auto downloaded: the only ones it removes when a newer pair replaces them. */
fun gpuAutoInstalled(context: Context): Set<String> =
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
fun setGpuAutoInstalled(context: Context, ids: Set<String>) {
prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply()
fun setLinuxDriver(context: Context, mode: String, id: String) {
prefs(context).edit().putString("linuxDriver.$mode", id).apply()
}
/**
@@ -177,12 +136,6 @@ object SessionPrefs {
writeForceFullscreenFlag(context)
}
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
fun setStretch16x9(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("stretch16x9", on).apply()
}
/**
* The same choice as a file the running session watches, so the drawer can change it live:
* the session hands every change to gamescope, which reads GAMESCOPE_FORCE_WINDOWS_FULLSCREEN
@@ -282,30 +235,12 @@ object SessionPrefs {
* plainly exist is the signature - and the fallback is to trace everything instead: slower,
* but correct. Max's advice for devices whose kernels "don't work well with it".
*/
/** Hold the GPU at its top clock during a session (GpuClockPin). Off by default: power and heat. */
fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false)
fun setGpuClockPin(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("gpuClockPin", on).apply()
}
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
fun setProotNoSeccomp(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
}
/**
* Whether the session's path lookups take proot's fast path (ProotFastPath): answered inside
* each process instead of a round trip through the tracer. On by default; it needs proot's
* seccomp filter, so it is off whenever proot runs without one.
*/
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
@JvmStatic
@@ -357,29 +292,10 @@ object SessionPrefs {
prefs(context).getString("steamController", CONTROLLER_DECK) ?: CONTROLLER_DECK
fun setSteamController(context: Context, id: String) { prefs(context).edit().putString("steamController", id).apply() }
/** Runs the SteamOS gamepad client with its Quick Access performance controls. On by default (settleDeckModeDefault). */
fun steamDeckMode(context: Context): Boolean = prefs(context).getBoolean("steamDeckMode", true)
/** Runs the SteamOS gamepad client with its Quick Access performance controls. */
fun steamDeckMode(context: Context): Boolean = prefs(context).getBoolean("steamDeckMode", false)
fun setSteamDeckMode(context: Context, on: Boolean) { prefs(context).edit().putBoolean("steamDeckMode", on).apply() }
/**
* Deck mode is the default: every install, new or from before, is moved to it once. An install
* from before 0.3.0 had off written down for it whether or not anyone chose it, so the move
* can't tell a choice from that default and moves everyone; turning it off afterwards sticks.
* Run once at process start, before anything reads or writes these prefs.
*/
fun settleDeckModeDefault(context: Context) {
val p = prefs(context)
if (p.getBoolean("deckModeMoved", false)) return
p.edit().putBoolean("steamDeckMode", true).putBoolean("deckModeMoved", true).apply()
}
/**
* Deck mode's performance overlay (mangoapp, beside gamescope): the QAM's Overlay Level draws
* through it. Off is the way out where Valve's mangoapp crashes (one Turnip build did).
*/
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
/**
* Zink's lazy descriptor mode (ZINK_DESCRIPTORS=lazy) with its compact set layout
* (ZINK_DEBUG=compact) for the client's GL-on-Vulkan UI, as WinNative runs it. On by default.
@@ -456,18 +372,14 @@ object SessionPrefs {
.onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) }
}
/**
* The Steam client branch forced on the command line: "publicbeta" (every session so far) or
* "steamdeck_publicbeta" (Armada's). Deck mode always takes the Deck branch, whatever was chosen:
* with -steamos3 the client picks its own branch as SteamOS does, and on publicbeta it settled
* on steamdeck_stable - an older client it then offered as a "Software Update" in every session,
* which applying turns into the exit-42 restart loop (seen on device 2026-09-30). Earlier, Deck
* mode on publicbeta also reinstalled the same client at every start (2026-09-23). On
* steamdeck_publicbeta the client finds no update. The choice applies with Deck mode off.
*/
/** The Steam client branch forced on the command line: "publicbeta" (every session so far) or "steamdeck_publicbeta" (Armada's). */
fun steamChannel(context: Context): String =
if (steamDeckMode(context)) "steamdeck_publicbeta"
else prefs(context).getString("steamChannel", null) ?: "publicbeta"
prefs(context).getString("steamChannel", null)
// Deck mode on the publicbeta channel reinstalls the same client at every start (the
// client reports "installed version 0" against that manifest and exits 42 to apply it,
// losing the launch URL each time); on steamdeck_publicbeta the second launch comes up
// clean. Seen on device 2026-09-23. So Deck mode takes the Deck channel unless chosen.
?: if (steamDeckMode(context)) "steamdeck_publicbeta" else "publicbeta"
fun setSteamChannel(context: Context, id: String) {
prefs(context).edit().putString("steamChannel", id).apply()
@@ -572,22 +484,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
}
/**
* The session's frame cap, 0 for none. One number used everywhere a frame is paced: gamescope's
* -r (what the client and its games see as the display's rate), the compositor's buffer release
* pacer, the rate the display layer votes for, and the panel mode picked, which is the fastest
* one the cap divides evenly (40 on a 120 Hz panel, not on a 144 Hz one). A 60 fps cap on a
* 144 Hz panel with nothing else changed judders; this is what WinNative's per-shortcut limit
* does. Applies next session.
*/
fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0)
fun setFpsLimit(context: Context, mode: String, fps: Int) {
prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply()
}
val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120")
/**
* The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a
* fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices.
@@ -608,7 +504,7 @@ object SessionPrefs {
// ── Game storage ────────────────────────────────────────────────────────────────────────
/**
* A second Steam library on this device: the folder bound at /mnt/droiddeck-sd and
* A second Steam library on this device: the folder bound at /mnt/bannerlator-sd and
* registered with the client, which then asks where to install every game and shows both
* on its Storage page. "" = automatic: the SD card when one is in the phone (the default,
* so the choice is made inside the client like anywhere else); GAME_STORAGE_OFF = internal
@@ -36,8 +36,6 @@ import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.input.FakeInputWriter
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
@@ -271,16 +269,12 @@ class SessionService : Service() {
val sessionDir = openSessionFolder()
val sessionLog = File(sessionDir, "session.log")
Log.i(TAG, GpuClockPin.start(this))
val size = SessionState.outputSize
val guest = ArrayList<String>()
// The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the
// same set-up as a Steam session: it gets what the client and its games are started with.
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
addClientEnvironment(guest, steamHere)
// Where the fast path's description of proot's view goes, once the binds are known.
val fastPathAt = guest.size
addClientEnvironment(guest, runtimeDir, steamHere)
val pulse = startAudio(guest, sessionDir)
@@ -293,7 +287,7 @@ class SessionService : Service() {
guest.add("DXVK_HDR=1")
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
}
guest.add("BL_FPS=" + SessionState.fpsLimit)
guest.add("BL_FPS=0")
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
@@ -302,7 +296,7 @@ class SessionService : Service() {
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
SessionState.deckPad = false
deckBinds = emptyList()
if (controllersOn) addControllerEnvironment(guest, fakeInputDir, sessionDir)
if (controllersOn) addControllerEnvironment(guest, fakeInputDir)
// The desktop is wlroots (labwc). Stock wlroots allocates through gbm on a real DRM render
// node, and ours is a KGSL stand-in - labwc died at "unable to create allocator" - so the
// default is pixman (software, shm), where a Vulkan program cannot draw at all; those run
@@ -320,7 +314,6 @@ class SessionService : Service() {
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
guest.add("BL_ADDED_GAMES=" + listing.path)
if (OfflineMode.enabled(this)) guest.add("BL_STEAM_OFFLINE=1")
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("BL_LOSSLESS_OWNED=1")
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
// Where the guest leaves a request for another session (the desktop's Steam launchers).
@@ -366,19 +359,6 @@ class SessionService : Service() {
FileUtils.clear(File(cacheDir, "shm"))
val binds = sessionBinds(controllersOn, fakeInputDir)
// The fast path is told exactly the rootfs and binds proot is given (ProotFastPath).
val fastPathKey = if (ProotFastPath.enabled(this)) {
val prootBinds = LinuxRuntime.binds(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds,
)
val root = LinuxRuntime.rootDir(this)
ProotFastPath.key(root, prootBinds)?.also { key ->
val env = ProotFastPath.guestEnv(root, prootBinds, key)
guest.addAll(fastPathAt, env)
shellGuest.addAll(fastPathAt, env)
Log.i(TAG, "proot: fast path on (${prootBinds.size} binds)")
}
} else null
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
@@ -395,7 +375,6 @@ class SessionService : Service() {
hostEnv["PROOT_NO_SECCOMP"] = "1"
Log.i(TAG, "proot: seccomp acceleration off by request")
}
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } }
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
@@ -456,7 +435,6 @@ class SessionService : Service() {
}
sessionPid = pid
if (pid > 1) {
raiseTracer(pid, gen)
SessionEvents.guestStarted(pid)
} else {
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
@@ -500,7 +478,7 @@ class SessionService : Service() {
}
/** The guest's base environment: paths, the display, the GL/Vulkan stack and the client's switches. */
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean) {
private fun addClientEnvironment(guest: MutableList<String>, runtimeDir: File, steamHere: Boolean) {
guest.add("/usr/bin/env")
guest.add("-i")
guest.add("HOME=/root")
@@ -511,7 +489,7 @@ class SessionService : Service() {
// Without this the session is UTC: the client's clock, its logs and every timestamp in a
// session bundle sit hours off the device's. Bannerlator carries the same line.
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
guest.add("XDG_SESSION_TYPE=wayland")
guest.add("WAYLAND_DISPLAY=wayland-0")
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
@@ -520,12 +498,15 @@ class SessionService : Service() {
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
// An imported glibc Turnip, when one is set (by the user, or by Auto): the session script
// checks the manifest and its library from inside and points the loader at it with
// VK_DRIVER_FILES, so the runtime's own driver above stays untouched and is what a bad
// import falls back to. One driver for every session: the driver's shader cache is keyed on
// its build, and with one per mode every emulator compiled its shaders twice.
val linuxDriverId = SessionPrefs.linuxDriver(this)
// An imported glibc Turnip for this mode, when the user chose one: the session script checks
// the manifest and its library from inside and points the loader at it with VK_DRIVER_FILES,
// so the runtime's own driver above stays untouched and is what a bad import falls back to.
// A program from the rail is one of the desktop's emulators, so it draws with the desktop's
// Linux driver, not the Steam session's: the driver's shader cache is keyed on the driver
// build, and with two drivers every emulator compiled its shaders twice - once per way of
// starting it (RPCS3's 6650 interpreter variants on each first boot).
val driverMode = if (SessionState.mode == MODE_RUN) MODE_DESKTOP else SessionPrefs.prefMode(SessionState.mode)
val linuxDriverId = SessionPrefs.linuxDriver(this, driverMode)
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
@@ -546,22 +527,10 @@ class SessionService : Service() {
// BL_STEAMDECK; it is the one that builds the command line).
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
// Mesa's shader cache as one database instead of a file per entry. Every lookup in the
// file cache is an open and every store an open and a rename, each a proot stop (a rename
// two), for every pipeline DXVK, vkd3d-proton and Zink compile or find; the database is
// opened once and read and written with pread/pwrite, which proot never sees. Mesa removes
// the old folder itself once it has gone a week untouched.
guest.add("MESA_DISK_CACHE_DATABASE=1")
// glibc's per-thread rseq registration is refused by Android's app seccomp policy, so
// every thread start paid a SIGSYS that proot answers; the malloc top pad grows the heap
// 16 MB at a time instead of 128 KB, and every brk(2) is a proot stop too.
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
if (SessionState.mode == MODE_STEAM) {
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
SessionPrefs.writeForceFullscreenFlag(this)
}
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
@@ -638,7 +607,7 @@ class SessionService : Service() {
}
/** The fake evdev pads: the ring files the app writes and the identity SDL and Steam see. */
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File) {
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
// Virtual pads a client made last session (event16 and up, and their hidden rings) are
// not there any more; a client that crashed never took its own down.
@@ -664,15 +633,11 @@ class SessionService : Service() {
deckBinds = if (wantsDeck) SteamDeckPad.prepare(this, fakeInputDir.parentFile!!.parentFile!!) else emptyList()
SessionState.deckPad = deckBinds.isNotEmpty()
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
logControllersAtStart()
if (uinput) {
// /dev/uinput, stood in for by libfakeinput: the virtual pad Steam Input makes for a
// game becomes a node the game reads, carrying the player's layout, as on a Deck.
guest.add("FAKE_EVDEV_UINPUT=1")
if (SessionState.deckPad) {
guest.add("FAKE_EVDEV_DECK=1")
guest.add("FAKE_DECK_SYSFS_LISTING=" + SteamDeckPad.listingDir(fakeInputDir.parentFile!!.parentFile!!).path)
}
if (SessionState.deckPad) guest.add("FAKE_EVDEV_DECK=1")
} else if (SessionState.mode == MODE_STEAM) {
// Without it, games see the pad itself wearing Steam Input's virtual-gamepad identity -
// for games the client starts only. Everywhere else (the desktop, a program from the
@@ -685,11 +650,9 @@ class SessionService : Service() {
// The client reads a Deck controller through SDL's HIDAPI; a hint in the environment
// outranks the client's own. Nothing else is shown the Deck (libfakeinput).
if (!SessionState.deckPad) guest.add("SDL_JOYSTICK_HIDAPI=0")
// The guest side of the pads (libfakeinput: which pads were opened, the Deck's hidraw and why
// it was refused) in pad.log beside the session's other logs, so it is in every shared zip.
// Setup-time lines only, nothing per input event.
guest.add("FAKE_EVDEV_LOG=1")
guest.add("FAKE_EVDEV_LOG_FILE=" + File(sessionDir, "pad.log").path)
if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) {
guest.add("FAKE_EVDEV_LOG=1")
}
SessionState.fakeInputDir = fakeInputDir
}
@@ -702,41 +665,10 @@ class SessionService : Service() {
// /sys/class/power_supply/BAT<n>/..., a laptop's or a Deck's naming; Android's supply is
// called "battery" and its files differ, so the client sees no battery at all. A directory
// of our own, written from Android's battery API every few seconds, is bound over it.
// Steam's time estimates come from /run/vpower instead, written straight into the rootfs.
val battery = BatteryComponent(
File(filesDir, "session/sys/power_supply"),
File(LinuxRuntime.rootDir(this), "run/vpower"),
)
val battery = BatteryComponent(File(filesDir, "session/sys/power_supply"))
battery.attach(this)
components.add(battery)
binds.add(battery.dir.path + ":/sys/class/power_supply")
// The overlay's CPU and GPU temperatures and the fan, as hwmon sensors it knows by name.
val hwmon = HwmonComponent(File(filesDir, "session/sys/hwmon"), LinuxRuntime.rootDir(this))
if (hwmon.prepare()) {
hwmon.attach(this)
components.add(hwmon)
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
}
// CPU load for everything in the session that reads /proc/stat, the overlay among them.
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
if (cpuStat.prepare()) {
cpuStat.attach(this)
components.add(cpuStat)
binds.add(cpuStat.file.path + ":/proc/stat")
}
// The GPU memory in use for the overlay's VRAM lines, which it would read from tracefs.
val gpuMem = GpuMemComponent(File(LinuxRuntime.rootDir(this), "run/droiddeck-hud/gpu-mem"), LinuxRuntime.rootDir(this))
if (gpuMem.prepare()) {
gpuMem.attach(this)
components.add(gpuMem)
}
// The GPU's load and temperature for the performance overlay, where KGSL's sysfs is refused.
val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"))
if (gpuStats.prepare()) {
gpuStats.attach(this)
components.add(gpuStats)
binds.addAll(gpuStats.binds())
}
// Rumble for the on-screen pad: the fake evdev layer sends force-feedback effects to this
// listener, which drives the phone's vibrator (see RumbleComponent).
if (controllersOn) components.add(RumbleComponent().also { it.attach(this) })
@@ -756,15 +688,9 @@ class SessionService : Service() {
if (library != null) {
val problem = GameStorage.prepare(library.path)
if (problem == null) {
File(LinuxRuntime.rootDir(this), "mnt/droiddeck-sd").mkdirs()
// Links, prefixes and Steam entries made before the rename still name the old path.
File(LinuxRuntime.rootDir(this), "mnt/bannerlator-sd").mkdirs()
try {
binds.addAll(SecondaryLibrary.binds(filesDir, File(library.path)))
Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\"); prefixes and native tools private")
} catch (e: Exception) {
Log.w(TAG, "game storage: private directories could not be prepared; internal only this session", e)
}
binds.add("${library.path}:/mnt/bannerlator-sd")
Log.i(TAG, "game storage: ${library.path} -> /mnt/bannerlator-sd (\"${library.label}\")")
} else {
Log.w(TAG, "game storage: $problem; internal only this session")
}
@@ -782,8 +708,6 @@ class SessionService : Service() {
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
}
}
// Folders of added scripts outside internal storage, where their links point.
binds.addAll(com.droiddeck.launcher.runtime.UserApps.binds(this))
val roms = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }?.let { File(it) }
if (roms != null && roms.isDirectory && roms.canRead()) {
File(home, "ROMs").mkdirs()
@@ -1042,31 +966,6 @@ class SessionService : Service() {
}
}
/**
* proot is one thread, and every syscall it traps anywhere in the session - a path lookup in
* Proton's python, Wine's file opens, the Steam client's /proc scans - waits for that thread to
* be scheduled, at nice 0 beside a game that keeps the big cores busy. It is raised to nice -6,
* under the compositor's -8. After a moment, not at once: the first guest process is forked by
* proot itself and would inherit the value, and with it everything the session starts.
*/
private fun raiseTracer(pid: Int, gen: Int) {
Thread({
try {
Thread.sleep(2000)
} catch (e: InterruptedException) {
return@Thread
}
if (gen != sessionGen || sessionPid != pid) return@Thread
val nice = try {
WaylandCompositor.nativeRaisePriority(pid, TRACER_NICE)
} catch (t: Throwable) {
Log.w(TAG, "tracer priority", t)
return@Thread
}
Log.i(TAG, "proot tracer $pid: nice $nice (asked for $TRACER_NICE)")
}, "tracer-priority").start()
}
private fun stopSession(status: Int) {
synchronized(stopLock) {
if (!SessionState.running) return
@@ -1075,7 +974,6 @@ class SessionService : Service() {
val stoppedGen = sessionGen
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
GpuClockPin.stop(this)
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
suspendOperationPending = false
launchWatcher?.stopWatching()
@@ -1250,22 +1148,8 @@ class SessionService : Service() {
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification())
}
/** The pads attached as the session starts; the activity logs the ones that come and go after. */
private fun logControllersAtStart() {
val pads = ArrayList<String>()
for (id in android.view.InputDevice.getDeviceIds()) {
val d = android.view.InputDevice.getDevice(id) ?: continue
if (!com.droiddeck.launcher.input.PadBridge.isFromController(d)) continue
pads.add(String.format(java.util.Locale.ROOT, "\"%s\" (%04x:%04x)", d.name, d.vendorId, d.productId))
}
Log.i(TAG, "controllers at start: " + (if (pads.isEmpty()) "none" else pads.joinToString(", ")) +
"; presented to the guest as " + if (SessionState.deckPad) "a Steam Deck controller" else "an Xbox 360 controller")
}
companion object {
private const val TAG = "SessionService"
/** proot's tracer: above everything in the guest, under the compositor thread's -8. */
private const val TRACER_NICE = -6
/** Downloads file whose contents become TU_DEBUG inside the session, e.g. "sysmem". */
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
/** Downloads file of KEY=VALUE lines added to the session environment verbatim. */
@@ -1291,6 +1175,7 @@ class SessionService : Service() {
private const val STEAM_PICKUP_MS = 1500L
private const val STEAM_EXIT_MS = 10_000L
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
private const val PAD_LOG_SWITCH = "Download/droiddeck-pad-log"
private const val NO_UINPUT_SWITCH = "Download/droiddeck-no-uinput"
private const val NO_DECK_PAD_SWITCH = "Download/droiddeck-no-deck-pad"
/** libfakeinput numbers the pads made through its /dev/uinput stand-in from here. */
@@ -95,10 +95,6 @@ object SessionState {
@Volatile
var refreshHz: Float = 60f
/** The session's frame cap (SessionPrefs.fpsLimit), fixed when it starts; 0 = none. */
@Volatile
var fpsLimit: Int = 0
/** The compositor has presented a frame, so the loading panel is behind us for this session. */
@Volatile
var firstFrameSeen = false
@@ -23,11 +23,7 @@ import java.io.File
* - `/sys/dev/char/240:16` - how the node's device number is looked up (in the directory the
* runtime already binds there for the GPU);
* - `/run/udev/data/c240:16` - the udev database entry that marks the device initialised, without
* which libudev's enumeration leaves a device node out;
* - [listingDir] - stand-ins for the listings of `/sys`, `/sys/class` and `/sys/bus`. An app under
* an enforcing SELinux policy (every retail phone) may not list those directories, and libudev
* abandons its whole scan when it cannot, so the client never reached `hidraw`; libfakeinput
* lists these to the client instead when the real listing is refused (FAKE_DECK_SYSFS_LISTING).
* which libudev's enumeration leaves a device node out.
*
* Symlinks are absolute guest paths; proot resolves them inside the session.
*/
@@ -51,9 +47,6 @@ object SteamDeckPad {
0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0,
).map { it.toByte() }.toByteArray()
/** Where [prepare] puts the stand-in listings; bound into the guest at the same path. */
fun listingDir(sessionRoot: File) = File(sessionRoot, "sys/deck/listing")
/** Writes the tree and returns the `host:guest` binds for it, or none if it could not be made. */
fun prepare(context: Context, sessionRoot: File): List<String> {
val base = File(sessionRoot, "sys/deck")
@@ -96,11 +89,6 @@ object SteamDeckPad {
hidrawClass.mkdirs()
link(File(hidrawClass, NODE), HIDRAW)
// Only the names matter: libudev reads a listing for the subsystems to descend into and
// then opens /sys/class/hidraw itself, which is the bind above.
val listing = listingDir(sessionRoot)
for (name in listOf("sys/bus", "sys/class", "sys/devices", "class/hidraw", "bus")) File(listing, name).mkdirs()
// The runtime binds this directory over /sys/dev/char for the GPU (LinuxRuntime.bindGpuNode).
link(File(context.cacheDir, "drm/sys/$MAJOR:$MINOR"), HIDRAW)
@@ -0,0 +1,63 @@
package com.droiddeck.launcher.store
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.AppImageManager
import java.io.File
/** The imported AppImages and the import in progress, for the Desktop page. */
object AppImageState {
private val main = Handler(Looper.getMainLooper())
var items by mutableStateOf<List<AppImageManager.Item>>(emptyList())
private set
/** The file being imported and what the import is doing; null when idle. */
var importing by mutableStateOf<String?>(null)
private set
var stage by mutableStateOf<String?>(null)
private set
/** Why the last import was refused, shown on the page until the next one. */
var lastError by mutableStateOf<String?>(null)
private set
fun refresh(context: Context) {
val app = context.applicationContext
Thread({
val list = AppImageManager.list(app)
main.post { items = list }
}, "appimage-refresh").start()
}
fun import(context: Context, file: File) {
if (importing != null) return
val app = context.applicationContext
importing = file.name; stage = "Starting…"; lastError = null
Thread({
val problem = try {
AppImageManager.import(app, file) { s -> main.post { stage = s } }
} catch (e: Exception) {
e.message ?: e.toString()
}
val list = AppImageManager.list(app)
main.post {
importing = null; stage = null; items = list
lastError = problem?.let { "${file.name}: $it" }
if (problem == null) Toast.makeText(app, "${file.name} imported", Toast.LENGTH_SHORT).show()
}
}, "appimage-import").start()
}
fun remove(context: Context, id: String) {
val app = context.applicationContext
Thread({
AppImageManager.remove(app, id)
val list = AppImageManager.list(app)
main.post { items = list }
}, "appimage-remove").start()
}
}
@@ -1,99 +0,0 @@
package com.droiddeck.launcher.store
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.UserApps
/**
* The Desktop page's added apps and the one add or remove in progress. State changes only on the
* main thread; the work runs on a thread of its own and posts back.
*/
object UserAppsState {
private val main = Handler(Looper.getMainLooper())
var items by mutableStateOf<List<UserApps.App>>(emptyList())
private set
/** What is being added or removed; null when idle. */
var working by mutableStateOf<String?>(null)
private set
var stage by mutableStateOf<String?>(null)
private set
var percent by mutableStateOf(-1)
private set
/** Why the last add or remove failed, shown on the page until the next one. */
var lastError by mutableStateOf<String?>(null)
private set
/** The app whose updates are being looked up, and what each lookup found, by app key. */
var checking by mutableStateOf<String?>(null)
private set
var updates by mutableStateOf<Map<String, UserApps.UpdateCheck>>(emptyMap())
private set
/** Bumped per listing; only the newest one is shown. */
private var listing = 0
fun refresh(context: Context) {
val app = context.applicationContext
val seq = ++listing
Thread({
val list = runCatching { UserApps.list(app) }.getOrDefault(emptyList())
main.post { if (seq == listing) items = list }
}, "user-apps-list").start()
}
fun add(context: Context, request: UserApps.Request, label: String) =
run(context, label, R.string.user_apps_added) { app, progress -> UserApps.add(app, request, progress) }
fun remove(context: Context, target: UserApps.App) {
updates = updates - target.key
run(context, target.name, R.string.user_apps_removed) { app, progress -> UserApps.remove(app, target, progress) }
}
fun edit(context: Context, target: UserApps.App, name: String, icon: String?) =
run(context, name, R.string.user_apps_saved) { app, _ -> UserApps.edit(app, target, name, icon) }
fun checkUpdate(context: Context, target: UserApps.App) {
if (checking != null) return
val app = context.applicationContext
checking = target.key
updates = updates - target.key
Thread({
val result = try {
UserApps.checkUpdate(app, target)
} catch (e: Exception) {
UserApps.UpdateCheck.Failed(e.message ?: e.toString())
}
main.post { checking = null; updates = updates + (target.key to result) }
}, "user-apps-check").start()
}
fun update(context: Context, target: UserApps.App, release: UserApps.Release) =
run(context, target.name, R.string.user_apps_updated) { app, progress ->
UserApps.update(app, target, release, progress).also { if (it == null) main.post { updates = updates - target.key } }
}
private fun run(context: Context, label: String, done: Int, work: (Context, (String, Int) -> Unit) -> String?) {
if (working != null) return
val app = context.applicationContext
working = label; stage = null; percent = -1; lastError = null
Thread({
val problem = try {
work(app) { s, p -> main.post { stage = s; percent = p } }
} catch (e: Exception) {
e.message ?: e.toString()
}
main.post {
working = null; stage = null; percent = -1
lastError = problem?.let { "$label: $it" }
if (problem == null) Toast.makeText(app, app.getString(done, label), Toast.LENGTH_SHORT).show()
refresh(app)
StoreState.refresh(app)
}
}, "user-apps-work").start()
}
}
@@ -1,545 +0,0 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material.icons.outlined.Terminal
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.files.InAppFilePicker
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.store.UserAppsState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.File
private enum class AddSource(val label: Int, val hint: Int) {
SCRIPT(R.string.add_app_tab_script, R.string.add_app_script_hint),
APPIMAGE(R.string.add_app_tab_appimage, R.string.add_app_appimage_hint),
GITHUB(R.string.add_app_tab_github, R.string.add_app_github_hint),
FLATPAK(R.string.add_app_tab_flatpak, R.string.add_app_flatpak_hint),
}
private val ICON_TYPES = listOf("png", "jpg", "jpeg", "webp")
private val FieldShape = RoundedCornerShape(8.dp)
/** What an icon choice shows: a picked file, or a suggestion's link. */
private fun iconModel(ref: String): Any = if (ref.startsWith("https://")) ref else File(ref)
/** The Desktop page's Add: a script, an AppImage, a GitHub release or a Flatpak, with a name and icon. */
@Composable
internal fun AddAppDialog(runtimeReady: Boolean, onDismiss: () -> Unit, onAdd: (UserApps.Request, String) -> Unit) {
val ctx = LocalContext.current
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var source by rememberSaveable { mutableStateOf(AddSource.SCRIPT) }
var scriptPath by rememberSaveable { mutableStateOf<String?>(null) }
var imagePath by rememberSaveable { mutableStateOf<String?>(null) }
var repo by rememberSaveable { mutableStateOf("") }
var flatpak by rememberSaveable { mutableStateOf("") }
var name by rememberSaveable { mutableStateOf("") }
var iconPath by rememberSaveable { mutableStateOf<String?>(null) }
val pickScript = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { scriptPath = it.path }
}
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { imagePath = it.path }
}
val pickIcon = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { iconPath = it.path }
}
val repoId = UserApps.githubRepo(repo)
val flatpakId = UserApps.flatpakId(flatpak)
val custom = name.trim().takeIf { it.isNotEmpty() }
val request: Pair<UserApps.Request, String>? = when (source) {
AddSource.SCRIPT -> scriptPath?.takeIf { it.endsWith(".sh", ignoreCase = true) }?.let { File(it) }
?.let { UserApps.Request(UserApps.Source.Script(it), custom, iconPath) to (custom ?: it.nameWithoutExtension) }
AddSource.APPIMAGE -> imagePath?.takeIf { it.endsWith(".appimage", ignoreCase = true) }?.let { File(it) }
?.let { UserApps.Request(UserApps.Source.AppImage(it), custom, iconPath) to (custom ?: it.nameWithoutExtension) }
AddSource.GITHUB -> repoId?.let { UserApps.Request(UserApps.Source.GitHub(it), custom, iconPath) to (custom ?: it) }
AddSource.FLATPAK -> flatpakId?.let { UserApps.Request(UserApps.Source.Flatpak(it), custom, iconPath) to (custom ?: it) }
}
val busy = UserAppsState.working
val tabFocus = remember { AddSource.entries.map { FocusRequester() } }
val inputMode = LocalInputModeManager.current.inputMode
// Once, as it opens: typing a name switches the input mode too, and must keep its field.
LaunchedEffect(Unit) {
if (inputMode == InputMode.Keyboard) {
repeat(2) { androidx.compose.runtime.withFrameNanos { } }
runCatching { tabFocus[source.ordinal].requestFocus() }
}
}
val step = { by: Int -> source = AddSource.entries[(source.ordinal + by + AddSource.entries.size) % AddSource.entries.size] }
AppDialog(shown, close, "addApp", wide = true, modifier = Modifier.bumpers(onPrevious = { step(-1) }, onNext = { step(1) })) {
DialogHeader(stringResource(R.string.user_apps_back), stringResource(R.string.add_app_title)) {
TabStrip(AddSource.entries.map { stringResource(it.label) }, source.ordinal, { source = AddSource.entries[it] }, focusRequesters = tabFocus)
}
val glyph = if (source == AddSource.SCRIPT) Icons.Outlined.Terminal else Icons.Outlined.Apps
Columns(
first = {
Panel(stringResource(R.string.add_app_source)) {
AnimatedContent(
targetState = source,
transitionSpec = {
val dir = if (targetState.ordinal > initialState.ordinal) 1 else -1
(fadeIn(Motion.tw(260, 60)) + slideInHorizontally(Motion.tw(320, 60)) { dir * it / 12 })
.togetherWith(fadeOut(Motion.tw(140)) + slideOutHorizontally(Motion.tw(140)) { -dir * it / 16 })
},
label = "addSource",
) { src ->
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Small(stringResource(src.hint))
when (src) {
AddSource.SCRIPT -> {
FileRow(scriptPath) { pickScript.launch(InAppFilePicker.buildIntent(ctx, listOf("sh"), ctx.getString(R.string.add_app_pick_script))) }
scriptPath?.let { FolderNote(it) }
}
AddSource.APPIMAGE -> FileRow(imagePath) {
pickImage.launch(InAppFilePicker.buildIntent(ctx, listOf("appimage"), ctx.getString(R.string.add_app_pick_appimage)))
}
AddSource.GITHUB -> CheckedField(
repo, { repo = it.take(200) }, stringResource(R.string.add_app_repository),
stringResource(R.string.add_app_repository_placeholder),
stringResource(R.string.add_app_repository_invalid).takeIf { repo.isNotBlank() && repoId == null },
)
AddSource.FLATPAK -> CheckedField(
flatpak, { flatpak = it.take(200) }, stringResource(R.string.add_app_flatpak_id),
stringResource(R.string.add_app_flatpak_placeholder),
stringResource(R.string.add_app_flatpak_invalid).takeIf { flatpak.isNotBlank() && flatpakId == null },
)
}
}
}
}
},
second = {
Panel(stringResource(R.string.add_app_appearance)) {
AppPreview(iconPath?.let(::iconModel), glyph, request?.second, stringResource(source.label))
NameField(name, { name = it }, stringResource(R.string.add_app_name_placeholder))
IconActions(
onChoose = { pickIcon.launch(InAppFilePicker.buildIntent(ctx, ICON_TYPES, ctx.getString(R.string.add_app_pick_icon))) },
clear = iconPath?.let { R.string.add_app_clear_icon to { iconPath = null } },
)
if (source == AddSource.GITHUB && repoId != null) IconSuggestions(repoId, iconPath) { iconPath = it }
}
},
)
DialogFooter(
when {
!runtimeReady -> stringResource(R.string.add_app_runtime_required)
busy != null -> stringResource(R.string.add_app_busy, busy)
else -> null
},
stringResource(R.string.add_app_confirm), request != null && runtimeReady && busy == null,
onCancel = close,
) { request?.let { (r, label) -> onAdd(r, label); close() } }
}
}
/**
* An added app's name and icon, changed on its page. [icon]: null keeps the current one, "" goes
* back to the default, else a picked file or a suggestion.
*/
@Composable
internal fun EditAppDialog(app: UserApps.App, onDismiss: () -> Unit, onSave: (String, String?) -> Unit) {
val ctx = LocalContext.current
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var name by rememberSaveable(app.key) { mutableStateOf(app.name) }
var icon by rememberSaveable(app.key) { mutableStateOf<String?>(null) }
val pickIcon = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { icon = it.path }
}
val preview: Any? = when (val i = icon) {
null -> app.icon
"" -> null
else -> iconModel(i)
}
val busy = UserAppsState.working
val changed = name.trim() != app.name || icon != null
AppDialog(shown, close, "editApp", wide = false) {
DialogHeader(stringResource(app.kind.label()), stringResource(R.string.edit_app_title, app.name))
Rise(1) {
Panel(stringResource(R.string.add_app_appearance)) {
AppPreview(
preview, if (app.kind == UserApps.Kind.SCRIPT) Icons.Outlined.Terminal else Icons.Outlined.Apps,
name.trim().ifEmpty { null }, stringResource(app.kind.label()),
)
NameField(name, { name = it }, app.name)
IconActions(
onChoose = { pickIcon.launch(InAppFilePicker.buildIntent(ctx, ICON_TYPES, ctx.getString(R.string.add_app_pick_icon))) },
clear = if (preview == null) null else R.string.add_app_icon_reset to { icon = "" },
)
app.repo?.let { repo -> IconSuggestions(repo, icon) { icon = it } }
}
}
DialogFooter(
busy?.let { stringResource(R.string.add_app_busy, it) },
stringResource(R.string.edit_app_save), name.isNotBlank() && changed && busy == null,
onCancel = close,
) { onSave(name.trim(), icon); close() }
}
}
/** Open from the first frame; [onDismiss] once the closing animation has run. */
@Composable
internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolean> {
val shown = remember { MutableTransitionState(false).apply { targetState = true } }
LaunchedEffect(shown.currentState, shown.isIdle) { if (shown.isIdle && !shown.currentState && !shown.targetState) onDismiss() }
return shown
}
/**
* The card both dialogs sit in, sized to fit a landscape handheld without scrolling: it scales in
* like the app's menus, rises above the keyboard, and closes on a tap outside or B.
*/
@Composable
internal fun AppDialog(
shown: MutableTransitionState<Boolean>, close: () -> Unit, label: String, wide: Boolean,
modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit,
) {
val pal = LocalPalette.current
// The page's ring stays out of sight behind it.
VeilRing()
Dialog(onDismissRequest = close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
// The page's focus memory stays the page's: nothing in here is a place to come back to.
CompositionLocalProvider(LocalFrontFocus provides null) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().imePadding()
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = close),
) {
AnimatedVisibility(
visibleState = shown,
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f),
exit = fadeOut(Motion.tw(140)) + scaleOut(Motion.tw(140), targetScale = 0.96f),
label = label,
) {
Column(
verticalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier
.padding(12.dp)
.widthIn(max = if (wide) 860.dp else 560.dp)
.fillMaxWidth()
.heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp)
.shadow(24.dp, Shape16, ambientColor = Color.Black, spotColor = Color.Black)
.clip(Shape16)
.background(pal.surfaceVariant.copy(alpha = 0.97f))
.border(1.dp, pal.signal.copy(alpha = 0.22f), Shape16)
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
.controllerBack(close)
.then(modifier)
.verticalScroll(rememberScrollState())
.padding(horizontal = 18.dp, vertical = 16.dp),
content = content,
)
}
}
}
}
}
/** The eyebrow and title, with [trailing] (the tabs) beside them when there is room, else under them. */
@Composable
internal fun DialogHeader(eyebrow: String, title: String, trailing: (@Composable () -> Unit)? = null) {
val heading = @Composable {
Column {
Eyebrow(eyebrow)
Text(title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
Rise(0) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
when {
trailing == null -> heading()
maxWidth >= 600.dp -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
Box(Modifier.weight(1f)) { heading() }
trailing()
}
else -> Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { heading(); trailing() }
}
}
}
}
/** Side by side and of one height on a wide card, stacked on a narrow one. */
@Composable
private fun Columns(first: @Composable ColumnScope.() -> Unit, second: @Composable ColumnScope.() -> Unit) {
Rise(1) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
if (maxWidth >= 600.dp) Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.height(IntrinsicSize.Max)) {
Column(Modifier.weight(1.15f).fillMaxHeight(), content = first)
Column(Modifier.weight(1f).fillMaxHeight(), content = second)
} else Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
first()
second()
}
}
}
}
/** A titled inset of the card; it fills the height its column is given. */
@Composable
private fun Panel(title: String, content: @Composable ColumnScope.() -> Unit) {
val colors = MaterialTheme.colorScheme
Column(
verticalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().fillMaxHeight().clip(Shape14)
.background(colors.surface.copy(alpha = 0.6f)).border(1.dp, LocalPalette.current.line, Shape14).padding(14.dp),
) {
Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = colors.onSurfaceVariant)
content()
}
}
/** Why the main button is off (or nothing), then Cancel and the main button, at the card's foot. */
@Composable
internal fun DialogFooter(note: String?, confirm: String, enabled: Boolean, onCancel: () -> Unit, onConfirm: () -> Unit) {
val lineColor = LocalPalette.current.line
Rise(2) {
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.drawBehind { drawLine(lineColor, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) }.padding(top = 14.dp),
) {
Box(Modifier.weight(1f)) { if (note != null) Small(note) }
SecondaryButton(stringResource(R.string.add_app_cancel), onClick = onCancel)
PrimaryButton(confirm, enabled = enabled, onClick = onConfirm)
}
}
}
@Composable
internal fun Small(text: String, error: Boolean = false) =
Text(text, fontSize = 12.sp, lineHeight = 16.sp, color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant)
private fun hideKeyboard(view: View) {
(view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? InputMethodManager)
?.hideSoftInputFromWindow(view.windowToken, 0)
}
/** The app's text field, with what is wrong with its value under it. */
@Composable
private fun CheckedField(value: String, onChange: (String) -> Unit, label: String, placeholder: String, problem: String?) {
val view = LocalView.current
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
AdbTextField(
value, onChange, label, KeyboardType.Uri, ImeAction.Done, placeholder = placeholder, compact = true,
onDone = { hideKeyboard(view) },
)
if (problem != null) Small(problem, error = true)
}
}
@Composable
private fun NameField(name: String, onName: (String) -> Unit, placeholder: String) {
val view = LocalView.current
AdbTextField(
name, { onName(it.take(80)) }, stringResource(R.string.add_app_name), KeyboardType.Text, ImeAction.Done,
placeholder = placeholder, compact = true, onDone = { hideKeyboard(view) },
)
}
/** The app as the Desktop page will show it: its icon, its name ([name] null: not known yet) and kind. */
@Composable
private fun AppPreview(icon: Any?, glyph: ImageVector, name: String?, kind: String) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surfaceVariant).border(1.dp, pal.line2, Shape12).padding(10.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(48.dp).clip(Shape12).background(colors.surface)) {
AnimatedContent(icon, transitionSpec = { (fadeIn(Motion.tw(260)) + scaleIn(Motion.sp(0.6f), 0.85f)) togetherWith fadeOut(Motion.tw(160)) }, label = "appIcon") { model ->
if (model != null) AsyncImage(model = model, contentDescription = stringResource(R.string.add_app_icon), contentScale = ContentScale.Fit, modifier = Modifier.size(40.dp))
else Icon(glyph, stringResource(R.string.add_app_icon_default), tint = colors.onSurfaceVariant, modifier = Modifier.size(24.dp))
}
}
Column(Modifier.weight(1f)) {
Text(
name ?: stringResource(R.string.add_app_preview_name), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (name != null) colors.onBackground else colors.onSurfaceVariant,
)
Text(kind, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
}
/** The icon's picker and [clear] (a label and what it does). */
@Composable
private fun IconActions(onChoose: () -> Unit, clear: Pair<Int, () -> Unit>?) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(stringResource(R.string.add_app_choose_icon), compact = true, onClick = onChoose)
AnimatedVisibility(clear != null, enter = fadeIn(Motion.tw(180)) + expandHorizontally(Motion.tw(220)), exit = fadeOut(Motion.tw(120)) + shrinkHorizontally(Motion.tw(180))) {
clear?.let { (label, action) -> SecondaryButton(stringResource(label), compact = true, onClick = action) }
}
}
}
/** Icons found in [repo], looked up off the main thread once the name has settled; [selected] is ringed. */
@Composable
private fun IconSuggestions(repo: String, selected: String?, onPick: (String) -> Unit) {
val found by produceState<List<String>?>(null, repo) {
value = null
delay(500)
value = withContext(Dispatchers.IO) { runCatching { UserApps.githubIcons(repo) }.getOrDefault(emptyList()) }
}
val list = found
if (list != null && list.isEmpty()) return
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.height(44.dp)) {
Small(stringResource(if (list == null) R.string.add_app_icon_searching else R.string.add_app_icon_suggestions))
if (list != null) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) {
list.forEachIndexed { i, url -> Rise(i) { SuggestedIcon(url, url == selected) { onPick(url) } } }
}
}
}
@Composable
private fun SuggestedIcon(url: String, selected: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val scale by animateFloatAsState(if (hot || selected) 1.06f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "suggestScale")
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(44.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick),
) {
AsyncImage(model = ImageRequest.Builder(LocalContext.current).data(url).crossfade(true).build(), contentDescription = stringResource(R.string.add_app_icon), contentScale = ContentScale.Fit, modifier = Modifier.size(34.dp))
// The chosen one is ticked; the ring stays with focus.
if (selected) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.align(Alignment.TopEnd).padding(2.dp).size(14.dp).clip(androidx.compose.foundation.shape.CircleShape).background(pal.signal),
) { Icon(Icons.Filled.Check, contentDescription = null, tint = pal.onSignal, modifier = Modifier.size(10.dp)) }
}
}
/** The chosen file, or none yet, laid out like the app's text fields, with the button that picks it. */
@Composable
private fun FileRow(path: String?, onChoose: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column {
Text(stringResource(R.string.add_app_file), style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Box(
contentAlignment = Alignment.CenterStart,
modifier = Modifier.weight(1f).height(44.dp).background(colors.surfaceVariant, FieldShape).border(1.dp, pal.line2, FieldShape).padding(horizontal = 12.dp),
) {
Text(
path?.substringAfterLast('/') ?: stringResource(R.string.add_app_no_file), fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (path != null) colors.onBackground else colors.onSurfaceVariant,
)
}
SecondaryButton(stringResource(if (path == null) R.string.add_app_choose_file else R.string.add_app_change_file), compact = true, onClick = onChoose)
}
}
}
/** Whether the script's folder will be linked or copied in, worked out off the main thread. */
@Composable
private fun FolderNote(scriptPath: String) {
var plan by remember(scriptPath) { mutableStateOf<UserApps.ScriptPlan?>(null) }
LaunchedEffect(scriptPath) {
plan = withContext(Dispatchers.IO) { runCatching { UserApps.planScript(File(scriptPath)) }.getOrNull() }
}
val p = plan
Small(
when {
p == null -> stringResource(R.string.add_app_checking_folder)
p.copy -> stringResource(R.string.add_app_folder_copied, FileUtils.sizeToString(p.bytes))
else -> stringResource(R.string.add_app_folder_linked, p.folder.path)
},
)
}
@@ -1,8 +1,5 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.LocalContext
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -105,9 +102,6 @@ fun ComponentsPage(
onImport: () -> Unit,
onBack: () -> Unit,
requestInitialFocus: Boolean = true,
/** The GPU drivers tab ([GPU_TAB]): what it shows and does. */
gpu: GpuDriversState = GpuDriversState(),
gpuActions: GpuDriversActions = GpuDriversActions(),
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -117,58 +111,24 @@ fun ComponentsPage(
var confirmTitle by remember { mutableStateOf("") }
var about by remember { mutableStateOf(false) }
var protonMenu by remember { mutableStateOf(false) }
var confirmVerb by remember { mutableStateOf(R.string.comp_swap) }
val ctx = LocalContext.current
fun ask(title: String, body: String, verb: Int, action: () -> Unit) { confirmTitle = title; confirmVerb = verb; confirm = body to action }
// The GPU drivers tab's Advanced pages: one driver list on its own, full page.
var driverPage by remember { mutableStateOf<String?>(null) }
val gpuTab = comp == GPU_TAB
when (driverPage) {
"rt" -> {
DriverPage(
title = stringResource(R.string.comp_runtime_driver), hint = stringResource(R.string.comp_runtime_driver_hint),
rows = gpu.linuxRows, selected = gpu.linuxSelected, downloads = gpu.linuxDownloads,
status = gpu.releaseStatus, checking = gpu.checking, importLabel = stringResource(R.string.comp_import_turnip), canRestore = false,
onSelect = gpuActions.onSelectLinux, onDelete = gpuActions.onRemoveLinux, onRefresh = gpuActions.onRefresh,
onDownload = gpuActions.onDownloadDriver, onImport = gpuActions.onImportLinux, onRestore = {}, onBack = { driverPage = null },
)
return
}
"panel" -> {
DriverPage(
title = stringResource(R.string.comp_display_driver), hint = stringResource(R.string.comp_display_driver_hint),
rows = gpu.androidRows, selected = gpu.androidSelected, downloads = gpu.androidDownloads,
status = gpu.releaseStatus, checking = gpu.checking, importLabel = stringResource(R.string.comp_import_adrenotools),
canRestore = gpu.canRestoreBundled,
onSelect = gpuActions.onSelectAndroid, onDelete = gpuActions.onRemoveAndroid, onRefresh = gpuActions.onRefresh,
onDownload = gpuActions.onDownloadDriver, onImport = gpuActions.onImportAndroid, onRestore = gpuActions.onRestoreBundled,
onBack = { driverPage = null },
)
return
}
}
fun ask(title: String, body: String, action: () -> Unit) { confirmTitle = title; confirm = body to action }
val views = snapshot?.protons ?: emptyList()
val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull()
val label = ComponentsManager.LABEL[comp] ?: comp
val checked = if (catalogAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(catalogAt * 1000)) else stringResource(R.string.comp_never)
val nightlies = if (gpuTab) gpu.releaseStatus else if (busy != null) "$busy…" else stringResource(R.string.comp_nightlies_checked, checked)
val checked = if (catalogAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(catalogAt * 1000)) else "never"
val nightlies = if (busy != null) "$busy…" else "Nightlies checked $checked"
Column(Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
// ---- title, and the one thing that goes online -----------------------------------------
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
Text(
stringResource(R.string.comp_title), fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
maxLines = 1,
"Components", fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
maxLines = 1, modifier = Modifier.weight(1f),
)
// The status gives way to the title, not the other way round.
if (!narrow) Text(
nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
textAlign = androidx.compose.ui.text.style.TextAlign.End, modifier = Modifier.weight(1f),
) else Spacer(Modifier.weight(1f))
if (!gpuTab) ToolIcon(Icons.Outlined.Info, stringResource(R.string.comp_about)) { about = true }
if (gpuTab) ToolIcon(Icons.Outlined.Refresh, stringResource(R.string.comp_check_drivers), busy = gpu.checking, enabled = !gpu.checking && gpu.busy == null, onClick = gpuActions.onRefresh)
else ToolIcon(Icons.Outlined.Refresh, stringResource(R.string.comp_check_nightlies), busy = checking, enabled = !checking, onClick = onRefresh)
if (!narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
ToolIcon(Icons.Outlined.Info, "About Components") { about = true }
ToolIcon(Icons.Outlined.Refresh, "Check the Nightlies for new packages", busy = checking, enabled = !checking, onClick = onRefresh)
}
if (narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
@@ -178,29 +138,27 @@ fun ComponentsPage(
horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
) {
if (view != null && !gpuTab) Box {
if (view != null) Box {
ValueChip(view.proton.name, protonMenu, modifier = Modifier.widthIn(max = 300.dp).heightIn(min = 44.dp)) { protonMenu = !protonMenu }
AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = stringResource(R.string.comp_proton),
note = stringResource(R.string.comp_proton_note)) { first ->
AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = "Proton",
note = "Valve's own Proton is replaced when Steam updates it; its originals are kept per build.") { first ->
views.forEachIndexed { i, v ->
val swaps = v.components.values.count { it.activeFile != null }
MenuItem(
v.proton.name, checked = v.proton.id == view.proton.id,
detail = (if (swaps > 0) stringResource(R.string.comp_swapped, v.proton.version, swaps) else stringResource(R.string.comp_all_original, v.proton.version))
.let { if (v.inUseByGame) stringResource(R.string.comp_game_running_suffix, it) else it },
detail = v.proton.version + (if (swaps > 0) " · $swaps swapped" else " · all original") + (if (v.inUseByGame) " · game running" else ""),
focusRequester = if (i == 0) first else null,
) { onProton(v.proton.id); protonMenu = false }
}
}
}
val tabs = listOf(GPU_TAB) + comps
TabStrip(tabs.map { ComponentsManager.LABEL[it] ?: stringResource(R.string.comp_gpu_drivers) }, tabs.indexOf(comp).coerceAtLeast(0), { onComp(tabs[it]) })
TabStrip(comps.map { ComponentsManager.LABEL.getValue(it) }, comps.indexOf(comp).coerceAtLeast(0), { onComp(comps[it]) })
}
// ---- what is in use -----------------------------------------------------------------------
if (view != null && !gpuTab) {
if (view != null) {
val st = view.components.getValue(comp)
val reappliedAt = if (view.reappliedAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(view.reappliedAt * 1000)) else null
val fixedAt = if (view.reappliedAt > 0) " · re-applied at launch " + DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(view.reappliedAt * 1000)) else ""
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(top = 12.dp).clip(RoundedCornerShape(12.dp)).background(colors.surface)
@@ -208,13 +166,12 @@ fun ComponentsPage(
) {
Box(Modifier.size(8.dp).background(if (st.queued != null) Color(0xFFFFB86B) else pal.good, CircleShape))
Text(
(if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
.let { if (reappliedAt != null) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
(if (st.queued != null) "Next: ${st.queued} · after the game closes" else "$label in use: ${st.inUse}") + fixedAt,
fontSize = 14.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
if (st.queued != null) FocusText(stringResource(R.string.common_cancel), pal.signal, onClick = onCancelQueued)
if (st.queued != null) FocusText("Cancel", pal.signal, onClick = onCancelQueued)
else if (!narrow) Text(
if (view.inUseByGame) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
if (view.inUseByGame) "Waits until the game closes" else "Changes apply the next time a game starts",
fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1,
)
}
@@ -222,19 +179,13 @@ fun ComponentsPage(
// ---- the lists ------------------------------------------------------------------------------
when {
gpuTab -> Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
GpuDriversPanel(gpu, gpuActions) { driverPage = it }
Row(modifier = Modifier.padding(top = 14.dp)) {
SmallButton(stringResource(R.string.comp_import_zip), onClick = gpuActions.onImportZip)
}
}
snapshot == null -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp)) {
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(12.dp))
Text(stringResource(R.string.comp_reading), fontSize = 14.sp, color = colors.onSurfaceVariant)
Text("Reading the Protons…", fontSize = 14.sp, color = colors.onSurfaceVariant)
}
view == null -> Text(
stringResource(R.string.comp_no_proton),
"No Proton is installed in the Linux runtime yet. Start the Steam client once so it downloads its ARM64 Proton, or add GE-Proton / CachyOS from Setup.",
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 16.dp),
)
else -> {
@@ -247,12 +198,12 @@ fun ComponentsPage(
val rows = originals.map { o ->
val isCurrent = o.protonVersion == build
InstalledItem(
stringResource(R.string.comp_original, o.protonVersion),
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
"Original · ${o.protonVersion}",
o.label.substringAfterLast(" · ", "").ifEmpty { o.label } + if (isCurrent) " · this build" else " · earlier build",
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + stored.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
InstalledItem(s.version, String.format("%.1f MB", s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
}
val storedNames = snapshot.packages.map { it.file }.toSet()
val available = catalog.filter { it.comp == comp && ComponentsManager.safeName(it.file) !in storedNames }
@@ -262,9 +213,9 @@ fun ComponentsPage(
}
val installed: @Composable () -> Unit = {
SettingsGroup(stringResource(R.string.comp_installed_count, rows.size)) {
SettingsGroup("Installed · ${rows.size}") {
if (rows.isEmpty()) Text(
stringResource(R.string.comp_nothing_stored, label),
"Nothing stored for $label yet. This Proton's own files are saved as its original when the page opens.",
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
)
rows.forEachIndexed { i, item ->
@@ -272,22 +223,22 @@ fun ComponentsPage(
item, modifier = if (i == 0) Modifier.focusRequester(first) else Modifier,
onSelect = {
if (item.selected) return@InstalledLine
val waits = if (view.inUseByGame) ctx.getString(R.string.comp_waits_long) else ctx.getString(R.string.comp_applies_long)
if (item.file != null) ask(ctx.getString(R.string.comp_swap_title, label), ctx.getString(R.string.comp_swap_body, item.name, p.name, waits), R.string.comp_swap) { onSwap(item.file) }
else ask(ctx.getString(R.string.comp_restore_title, label), ctx.getString(R.string.comp_restore_body, item.protonVersion, p.name, waits), R.string.common_restore) { onRestore(item.protonVersion!!) }
val waits = if (view.inUseByGame) " A game is running on this Proton, so it waits until the game closes." else " It applies the next time a game starts."
if (item.file != null) ask("Swap $label?", "Put ${item.name} into ${p.name}? Its shipped files stay saved as an original bundle.$waits") { onSwap(item.file) }
else ask("Restore $label?", "Put the ${item.protonVersion} original back into ${p.name}?$waits") { onRestore(item.protonVersion!!) }
},
onDelete = {
if (item.file != null) ask(ctx.getString(R.string.common_delete_named, item.name) + "?", ctx.getString(R.string.comp_delete_package_body), R.string.common_delete) { onDeletePackage(item.file) }
else ask(ctx.getString(R.string.comp_delete_original_title), ctx.getString(R.string.comp_delete_original_body, item.protonVersion, p.name), R.string.common_delete) { onDeleteOriginal(item.protonVersion!!) }
if (item.file != null) ask("Delete ${item.name}?", "Its package file is removed from the app. You can download it again any time.") { onDeletePackage(item.file) }
else ask("Delete this original?", "The ${item.protonVersion} original of $label belongs to an earlier build of ${p.name}. The installed build's original is always kept.") { onDeleteOriginal(item.protonVersion!!) }
},
)
}
}
}
val nightly: @Composable () -> Unit = {
SettingsGroup(stringResource(R.string.comp_nightlies_count, available.size)) {
SettingsGroup("On the Nightlies · ${available.size}") {
if (available.isEmpty()) Text(
if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new),
if (catalogAt == 0L) "Refresh to list the packages on the Nightlies." else "Nothing new since the last check.",
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
)
available.forEach { d -> AvailableLine(d, downloads[d.file], enabled = busy == null) { onDownload(d) } }
@@ -300,9 +251,9 @@ fun ComponentsPage(
Column(Modifier.weight(1f)) { nightly() }
}
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 14.dp)) {
SmallButton(stringResource(R.string.comp_import_wcp), onClick = onImport)
if (!activeIsOriginal && originals.any { it.protonVersion == build }) FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
ask(ctx.getString(R.string.comp_restore_title, label), ctx.getString(R.string.comp_restore_original_body, p.name, label), R.string.common_restore) { onRestore(build) }
SmallButton("Import .wcp", onClick = onImport)
if (!activeIsOriginal && originals.any { it.protonVersion == build }) FocusText("Restore this Proton's original", pal.signal) {
ask("Restore $label?", "Put ${p.name}'s original $label back?") { onRestore(build) }
}
}
}
@@ -312,14 +263,17 @@ fun ComponentsPage(
if (about) AlertDialog(
onDismissRequest = { about = false },
title = { Text(stringResource(R.string.comp_title)) },
title = { Text("Components") },
text = {
Text(
stringResource(R.string.comp_about_text),
"FEX, DXVK and VKD3D-Proton for each Proton the Steam client runs games with.\n\n" +
"Tap an installed row to swap it in; it applies the next time a game starts. If a game is running on that Proton, the swap waits until it closes.\n\n" +
"Your choices are also checked right before every game launch: if anything changed a Proton's files (Steam's start-up tests, for one), they are put back first, and the page says \"re-applied at launch\".\n\n" +
"Each Proton build's own files are kept as its original, so a Steam update never loses them. Packages come from the Nightlies \"-Linux\" releases (refresh) or Import .wcp.",
fontSize = 14.sp,
)
},
confirmButton = { FocusText(stringResource(R.string.common_ok), pal.signal) { about = false } },
confirmButton = { FocusText("OK", pal.signal) { about = false } },
)
confirm?.let { (body, action) ->
AlertDialog(
@@ -328,20 +282,20 @@ fun ComponentsPage(
text = { Text(body, fontSize = 14.sp) },
// Opens on Cancel, so a stray A press on a controller never swaps or deletes anything.
confirmButton = {
val del = confirmVerb == R.string.common_delete
FocusText(stringResource(confirmVerb), if (del) colors.error else pal.signal) { confirm = null; action() }
val del = confirmTitle.startsWith("Delete")
FocusText(if (del) "Delete" else if (confirmTitle.startsWith("Restore")) "Restore" else "Swap", if (del) colors.error else pal.signal) { confirm = null; action() }
},
dismissButton = {
val cancelFocus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { cancelFocus.requestFocus() } }
FocusText(stringResource(R.string.common_cancel), colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
FocusText("Cancel", colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
},
)
}
}
@Composable
internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
private fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
@@ -350,7 +304,7 @@ internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = fa
contentAlignment = Alignment.Center,
modifier = Modifier.size(40.dp).clip(RoundedCornerShape(12.dp))
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(hot, RoundedCornerShape(12.dp), pal.signal, pal.line2)
.border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line2, RoundedCornerShape(12.dp))
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick),
) {
@@ -373,7 +327,7 @@ private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean =
contentAlignment = Alignment.Center,
modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp))
.background(if (hot) pal.signal else colors.surfaceVariant)
.glideBorder(hot, RoundedCornerShape(10.dp), colors.onBackground, pal.line2, restWidth = 2.dp)
.border(2.dp, if (hot) colors.onBackground else pal.line2, RoundedCornerShape(10.dp))
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = 14.dp, vertical = 8.dp),
@@ -396,13 +350,7 @@ private fun Tag(text: String) {
else -> colors.onSurfaceVariant to Color.White.copy(alpha = 0.07f)
}
Text(
when (text) {
"ORIGINAL" -> stringResource(R.string.comp_tag_original)
"IN USE" -> stringResource(R.string.comp_tag_in_use)
"NEW" -> stringResource(R.string.comp_tag_new)
"STORED" -> stringResource(R.string.comp_tag_stored)
else -> text.lowercase().replaceFirstChar { it.uppercase() }
}, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = fg, maxLines = 1,
text.lowercase().replaceFirstChar { it.uppercase() }, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = fg, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(bg).padding(horizontal = 7.dp, vertical = 1.dp),
)
}
@@ -421,7 +369,7 @@ private fun InstalledLine(item: InstalledItem, modifier: Modifier = Modifier, on
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f).heightIn(min = 56.dp).then(modifier)
.glideBorder(hot, ROW_SHAPE, pal.signal)
.border(2.dp, if (hot) pal.signal else Color.Transparent, ROW_SHAPE)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect)
.controllerConfirm(onClick = onSelect)
.padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
@@ -450,10 +398,10 @@ private fun InstalledLine(item: InstalledItem, modifier: Modifier = Modifier, on
contentAlignment = Alignment.Center,
modifier = Modifier.padding(end = 6.dp).size(40.dp).clip(ROW_SHAPE)
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(delHot, ROW_SHAPE, colors.error)
.border(2.dp, if (delHot) colors.error else Color.Transparent, ROW_SHAPE)
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete)
.controllerConfirm(onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, item.name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
) { Icon(Icons.Outlined.Delete, contentDescription = "Delete ${item.name}", tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
@@ -470,11 +418,11 @@ private fun AvailableLine(d: CatalogItem, progress: Int?, enabled: Boolean, onDo
Column(Modifier.weight(1f)) {
Text(d.file.removeSuffix(".wcp"), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
"${d.release} · " + stringResource(R.string.common_size_mb, d.size / 1048576.0), fontSize = 13.sp, color = colors.onSurfaceVariant,
"${d.release} · " + String.format("%.1f MB", d.size / 1048576.0), fontSize = 13.sp, color = colors.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 2.dp),
)
}
if (progress == null) SmallButton(stringResource(R.string.common_download), enabled = enabled, accent = true, onClick = onDownload)
if (progress == null) SmallButton("Download", enabled = enabled, accent = true, onClick = onDownload)
else Column(horizontalAlignment = Alignment.End, modifier = Modifier.width(96.dp)) {
Text(if (progress < 0) "…" else "$progress%", fontSize = 13.sp, color = colors.onSurfaceVariant)
Spacer(Modifier.height(4.dp))
@@ -484,6 +432,3 @@ private fun AvailableLine(d: CatalogItem, progress: Int?, enabled: Boolean, onDo
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
/** The Components page's tab for the GPU drivers, before the Proton components' own. */
const val GPU_TAB = "gpu"
@@ -1,7 +1,5 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
@@ -38,17 +36,17 @@ private fun Swatch(color: Int) {
@Composable
fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPrefs.Settings, a: ControllerActions) {
ChoiceRow(
host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.ctrl_osc_hint),
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
oscMode, note = stringResource(R.string.mode_osc_note), onPick = a.onOsc,
host, "controller-osc", "On-screen controls", "When the touch pad appears in a session",
listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never"),
oscMode, note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
)
val tintOpen = host.open == "controller-tint"
SettingsRow(stringResource(R.string.ctrl_color), stringResource(R.string.ctrl_color_hint), highlighted = tintOpen) {
SettingsRow("Color", "Tint of the on-screen buttons", highlighted = tintOpen) {
Box {
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second ?: stringResource(R.string.ctrl_custom), tintOpen) {
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second ?: "Custom", tintOpen) {
host.open = if (tintOpen) null else "controller-tint"
}
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = stringResource(R.string.ctrl_color)) { firstItemFocus ->
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = "Color") { firstItemFocus ->
ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
MenuItem(name, checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) {
a.onTint(color)
@@ -58,36 +56,36 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
}
}
}
ChoiceRow(host, "controller-opacity", stringResource(R.string.ctrl_opacity), null, ControllerPrefs.opacities.map { it to stringResource(R.string.ctrl_percent, it) }, c.opacity, onPick = a.onOpacity)
ChoiceRow(host, "controller-size", stringResource(R.string.ctrl_size), stringResource(R.string.ctrl_size_hint), ControllerPrefs.sizes.map { it to stringResource(R.string.ctrl_percent, it) }, c.size, onPick = a.onSize)
ToggleRow(host, "controller-stick-click", stringResource(R.string.ctrl_stick_click), stringResource(R.string.ctrl_stick_click_hint), c.stickClick, onChange = a.onStickClick)
ToggleRow(host, "controller-adaptive", stringResource(R.string.ctrl_adaptive), stringResource(R.string.ctrl_adaptive_hint), c.adaptiveSticks, onChange = a.onAdaptiveSticks)
SettingsRow(stringResource(R.string.ctrl_layout), if (c.customLayout) stringResource(R.string.ctrl_layout_custom) else stringResource(R.string.ctrl_layout_default)) {
ChoiceRow(host, "controller-opacity", "Opacity", null, ControllerPrefs.opacities.map { it to "$it%" }, c.opacity, onPick = a.onOpacity)
ChoiceRow(host, "controller-size", "Button size", "100% keeps the standard size", ControllerPrefs.sizes.map { it to "$it%" }, c.size, onPick = a.onSize)
ToggleRow(host, "controller-stick-click", "Stick click", "Double-tap a stick and hold for L3 or R3", c.stickClick, onChange = a.onStickClick)
ToggleRow(host, "controller-adaptive", "Adaptive sticks", "Sticks appear when touched near their saved positions and hide when released", c.adaptiveSticks, onChange = a.onAdaptiveSticks)
SettingsRow("Layout", if (c.customLayout) "Custom positions saved" else "Placed for this screen's size and your grip") {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SecondaryButton(stringResource(R.string.ctrl_edit)) { a.onEditLayout() }
SecondaryButton(stringResource(R.string.ctrl_reset), enabled = c.customLayout) { a.onResetLayout() }
SecondaryButton("Edit") { a.onEditLayout() }
SecondaryButton("Reset", enabled = c.customLayout) { a.onResetLayout() }
}
}
val remapped = c.mapping.count { (id, target) -> id != target }
ActionRow(stringResource(R.string.ctrl_mapping), if (remapped == 0) stringResource(R.string.ctrl_mapping_default) else stringResource(R.string.ctrl_mapping_count, remapped, c.mapping.size), stringResource(R.string.ctrl_configure), a.onMapping)
ActionRow(stringResource(R.string.ctrl_reset_all), stringResource(R.string.ctrl_reset_all_hint), stringResource(R.string.ctrl_reset), a.onResetAll)
ActionRow("Button mapping", if (remapped == 0) "Every button sends its own input" else "$remapped of ${c.mapping.size} buttons remapped", "Configure", a.onMapping)
ActionRow("Reset controller", "Restore the default color, opacity, size, stick behavior, mapping and layout", "Reset", a.onResetAll)
}
@Composable
fun ControllerMappingPage(mapping: Map<String, String>, onPick: (String, String) -> Unit, onReset: () -> Unit, onBack: () -> Unit) {
val host = rememberMenuHost()
SettingsPage(
host, title = stringResource(R.string.ctrl_mapping), eyebrow = stringResource(R.string.setup_controller),
lede = stringResource(R.string.ctrl_mapping_lede),
host, title = "Button mapping", eyebrow = "Controller",
lede = "Choose what each on-screen button sends to the game. Hidden removes the button.",
onBack = onBack,
) {
SettingsGroup(stringResource(R.string.ctrl_onscreen_buttons)) {
SettingsGroup("On-screen buttons") {
for ((id, name) in ControllerPrefs.mappable) {
ChoiceRow(host, "map-$id", name, null, ControllerPrefs.targets, mapping[id] ?: id) { onPick(id, it) }
}
}
SettingsGroup(stringResource(R.string.ctrl_defaults)) {
ActionRow(stringResource(R.string.ctrl_reset_mapping), stringResource(R.string.ctrl_mapping_default), stringResource(R.string.ctrl_reset), onReset)
SettingsGroup("Defaults") {
ActionRow("Reset mapping", "Every button sends its own input again", "Reset", onReset)
}
}
}
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
@@ -37,7 +36,7 @@ class DeckControlsPanel(
private val onSteamMenu: () -> Unit,
private val onQam: () -> Unit,
) : LinearLayout(context) {
private enum class Tab(val label: Int) { GRIPS(R.string.deck_tab_grips), LEFT(R.string.deck_tab_left), RIGHT(R.string.deck_tab_right), BOTH(R.string.deck_tab_both) }
private enum class Tab(val label: String) { GRIPS("Grips"), LEFT("Left pad"), RIGHT("Right pad"), BOTH("Both") }
private val content = FrameLayout(context)
private val tabViews = HashMap<Tab, TextView>()
@@ -59,14 +58,14 @@ class DeckControlsPanel(
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setPadding(dp(12), dp(10), dp(12), dp(6))
addView(roundButton("×", context.getString(R.string.deck_close), onClose))
addView(roundButton("×", "Close second-screen controls", onClose))
val tabs = LinearLayout(context).apply {
orientation = HORIZONTAL
background = outline(CORNER_PILL, SURFACE)
setPadding(dp(4), dp(4), dp(4), dp(4))
for (tab in Tab.values()) {
val view = TextView(context).apply {
text = context.getString(tab.label)
text = tab.label
textSize = 14f
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
gravity = Gravity.CENTER
@@ -82,9 +81,9 @@ class DeckControlsPanel(
addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44), Gravity.CENTER))
}
addView(centre, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f))
addView(roundButton("STEAM", context.getString(R.string.deck_open_steam_menu), onSteamMenu, wide = true))
addView(roundButton("STEAM", "Open Steam menu", onSteamMenu, wide = true))
addView(space(dp(8)))
addView(roundButton("•••", context.getString(R.string.drawer_open_qam), onQam, wide = true))
addView(roundButton("•••", "Open Quick Access Menu", onQam, wide = true))
}
private fun select(tab: Tab) {
@@ -115,9 +114,9 @@ class DeckControlsPanel(
addView(upper, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { bottomMargin = dp(6) })
addView(lower, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { topMargin = dp(6) })
}
addView(column(GripButton(context, "L4", context.getString(R.string.deck_left_upper), DeckControls.L4), GripButton(context, "L5", context.getString(R.string.deck_left_lower), DeckControls.L5)),
addView(column(GripButton(context, "L4", "Left · upper", DeckControls.L4), GripButton(context, "L5", "Left · lower", DeckControls.L5)),
LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { rightMargin = dp(6) })
addView(column(GripButton(context, "R4", context.getString(R.string.deck_right_upper), DeckControls.R4), GripButton(context, "R5", context.getString(R.string.deck_right_lower), DeckControls.R5)),
addView(column(GripButton(context, "R4", "Right · upper", DeckControls.R4), GripButton(context, "R5", "Right · lower", DeckControls.R5)),
LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { leftMargin = dp(6) })
}
@@ -256,7 +255,7 @@ class DeckControlsPanel(
HoldButton(context, label, caption, { DeckControls.setGrip(bit, it) })
private class ClickBar(context: Context, right: Boolean) :
HoldButton(context, context.getString(R.string.deck_click), if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad), { DeckControls.setClick(right, it) })
HoldButton(context, "Click", if (right) "Right trackpad" else "Left trackpad", { DeckControls.setClick(right, it) })
/**
* One trackpad: where the first finger is, as the Deck reports it (-1..1, y up), and a click
@@ -283,7 +282,7 @@ class DeckControlsPanel(
canvas.drawLine(cx, cy - reach, cx, cy + reach, guide)
captionPaint.textSize = 12 * density
captionPaint.color = if (touching) ACCENT else TEXT_DIM
canvas.drawText((if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint)
canvas.drawText(if (right) "RIGHT TRACKPAD" else "LEFT TRACKPAD", cx, 28 * density, captionPaint)
if (touching) {
val radius = 56 * density
glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
@@ -1,7 +1,5 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import androidx.compose.ui.res.stringResource
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.hoverable
@@ -94,17 +92,17 @@ fun DriverPage(
contentAlignment = Alignment.Center,
modifier = Modifier.size(40.dp).clip(RoundedCornerShape(10.dp))
.background(if (refreshHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(refreshHot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.border(if (refreshHot) 2.dp else 1.dp, if (refreshHot) pal.signal else pal.line, RoundedCornerShape(10.dp))
.focusRequester(refreshFocus)
.hoverable(refreshSrc)
.clickable(interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh),
) {
if (checking) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
else Icon(Icons.Outlined.Refresh, contentDescription = stringResource(R.string.comp_check_drivers), tint = colors.onBackground, modifier = Modifier.size(20.dp))
else Icon(Icons.Outlined.Refresh, contentDescription = "Check for new drivers", tint = colors.onBackground, modifier = Modifier.size(20.dp))
}
},
) {
SettingsGroup(stringResource(R.string.driver_installed)) {
SettingsGroup("Installed") {
val focusRow = rows.firstOrNull { it.id == selected } ?: rows.firstOrNull()
rows.forEachIndexed { i, row ->
InstalledRow(
@@ -115,14 +113,14 @@ fun DriverPage(
)
}
}
SettingsGroup(stringResource(R.string.driver_available)) {
SettingsGroup("Available to download") {
if (downloads.isEmpty()) Text(
stringResource(R.string.driver_nothing_new),
"Nothing new from the last check. Tap the refresh button to look for newer releases.",
fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 14.dp),
) else for (d in downloads) {
SettingsRow(d.label, d.detail) {
val p = d.progress
if (p == null) SecondaryButton(stringResource(R.string.common_download)) { onDownload(d.key) }
if (p == null) SecondaryButton("Download") { onDownload(d.key) }
else Column(horizontalAlignment = Alignment.End, modifier = Modifier.width(120.dp)) {
Text("$p%", fontSize = 12.sp, color = colors.onSurfaceVariant)
Spacer(Modifier.height(4.dp))
@@ -133,27 +131,26 @@ fun DriverPage(
}
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 14.dp)) {
SecondaryButton(importLabel, onClick = onImport)
if (canRestore) FocusText(stringResource(R.string.driver_restore_builtin), pal.signal, onClick = onRestore)
if (canRestore) FocusText("Restore built-in drivers", pal.signal, onClick = onRestore)
}
}
confirm?.let { row ->
AlertDialog(
onDismissRequest = { confirm = null },
title = { Text(stringResource(R.string.common_delete_named, row.name) + "?") },
title = { Text("Delete ${row.name}?") },
text = {
Text(
if (row.tag == DriverRow.BUNDLED) stringResource(R.string.driver_delete_builtin)
else if (row.tag == DriverRow.BUNDLE) stringResource(R.string.driver_delete_bundle)
else if (row.id == selected) stringResource(R.string.driver_delete_in_use) else stringResource(R.string.driver_delete_plain),
if (row.tag == DriverRow.BUNDLED) "It is built into the app, so this removes its unpacked files and hides it. \"Restore built-in drivers\" brings it back, and Auto still uses it on a GPU that needs it."
else "Its files are removed from the app." + if (row.id == selected) " It is the driver in use, so the default takes its place." else "",
fontSize = 13.sp,
)
},
// Opens on Cancel, so a stray A press on a controller never deletes anything.
confirmButton = { FocusText(stringResource(R.string.common_delete), colors.error) { confirm = null; onDelete(row.id) } },
confirmButton = { FocusText("Delete", colors.error) { confirm = null; onDelete(row.id) } },
dismissButton = {
val cancelFocus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { cancelFocus.requestFocus() } }
FocusText(stringResource(R.string.common_cancel), colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
FocusText("Cancel", colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
},
)
}
@@ -176,7 +173,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(3.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else if (selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal),
.border(2.dp, if (hot) pal.signal else Color.Transparent, shape),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -212,11 +209,11 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit
contentAlignment = Alignment.Center,
modifier = Modifier.padding(end = 8.dp).size(40.dp).clip(RoundedCornerShape(10.dp))
.background(if (delHot) colors.error.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(delHot, RoundedCornerShape(10.dp), colors.error)
.border(2.dp, if (delHot) colors.error else Color.Transparent, RoundedCornerShape(10.dp))
.focusRequester(delFocus)
.focusProperties { left = mainFocus }
.hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, row.name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
) { Icon(Icons.Outlined.Delete, contentDescription = "Delete ${row.name}", tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) }
}
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
@@ -232,7 +229,7 @@ internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier
text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = color,
modifier = modifier.clip(shape)
.background(if (hot) color.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, shape, color)
.border(2.dp, if (hot) color else Color.Transparent, shape)
.hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
)
@@ -1,340 +0,0 @@
package com.droiddeck.launcher.ui
import android.view.View
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlin.math.abs
import kotlin.math.hypot
import kotlinx.coroutines.coroutineScope
// One focus ring for a whole screen that slides from control to control. When focus moves, the
// edge on the side it is heading springs ahead and the trailing edge catches up a beat later, so
// the ring stretches like a drop and snaps into the new control's shape.
/** A control that can show the ring: where it is and what its ring looks like there. */
internal class GlideSource {
var coords: LayoutCoordinates? = null
var shape: Shape by mutableStateOf<Shape>(androidx.compose.ui.graphics.RectangleShape)
var color by mutableStateOf(Color.Transparent)
var width by mutableStateOf(2.dp)
}
internal class FocusGlide(val view: View) {
var host: LayoutCoordinates? = null
/** Controls that are hot, the latest last: focus and a hovering pointer can each hold one. */
val hot = mutableStateListOf<GlideSource>()
/** Bumped when the current control moves (a scroll, a relayout). */
var moves by mutableIntStateOf(0)
/** Off while a page floods in or out (PageFlood); back on, it appears on whatever has focus. */
var hidden by mutableStateOf(false)
val current: GlideSource? get() = hot.lastOrNull()
fun claim(s: GlideSource) { hot.remove(s); hot.add(s) }
fun release(s: GlideSource) { hot.remove(s) }
fun moved(s: GlideSource) { if (hot.lastOrNull() === s) moves++ }
/** [s]'s bounds in the host, cut to what is on screen; null when it is not laid out or is scrolled away. */
fun boundsOf(s: GlideSource): Rect? {
val h = host ?: return null
val c = s.coords ?: return null
if (!h.isAttached || !c.isAttached) return null
val b = h.localBoundingBoxOf(c, clipBounds = true)
return if (b.width < 1f || b.height < 1f) null else b
}
}
internal val LocalFocusGlide = staticCompositionLocalOf<FocusGlide?> { null }
/** Floods on screen (a launch, a stop, the return from one): every ring keeps out of the way of them. */
internal object RingVeil {
var count by mutableIntStateOf(0)
}
/** Keeps the focus ring off while this is in the composition. */
@Composable
internal fun VeilRing() {
DisposableEffect(Unit) {
RingVeil.count++
onDispose { RingVeil.count-- }
}
}
private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float =
when (val o = shape.createOutline(size, dir, density)) {
is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x
is Outline.Rectangle -> 0f
is Outline.Generic -> minOf(size.width, size.height) / 2f
}
/**
* A control's outline: [restColor] at [restWidth] always, and [hotColor] at [hotWidth] while [hot].
* Under a [FocusGlideHost] the hot outline is the host's one sliding ring; elsewhere (a dialog, a
* popup, a screen with no host) it is drawn here, as a plain border.
*/
@Composable
internal fun Modifier.glideBorder(
hot: Boolean,
shape: Shape,
hotColor: Color,
restColor: Color = Color.Transparent,
hotWidth: Dp = 2.dp,
restWidth: Dp = 1.dp,
): Modifier {
val glide = LocalFocusGlide.current
if (glide == null || glide.view !== LocalView.current) {
return border(if (hot) hotWidth else restWidth, if (hot) hotColor else restColor, shape)
}
val src = remember { GlideSource() }
src.shape = shape
src.color = hotColor
src.width = hotWidth
DisposableEffect(glide, hot) {
if (hot) glide.claim(src)
onDispose { glide.release(src) }
}
val base = if (restColor.alpha > 0f) border(restWidth, restColor, shape) else this
return base.onGloballyPositioned { src.coords = it; glide.moved(src) }
}
/** Leading edge on a focus move: quick and a little loose. */
private fun lead(): AnimationSpec<Float> = Motion.sp(0.62f, 700f)
/** Trailing edge: slower, settles without a bounce to speak of. */
private fun trail(): AnimationSpec<Float> = Motion.sp(0.78f, 360f)
/** Following a control that moves under the ring (a scroll): tight, no wobble. */
private fun follow(): AnimationSpec<Float> = Motion.sp(1f, 2400f)
/** How long after a focus move the ring keeps its stretchy springs and keeps checking where it is. */
private const val SETTLE_MS = 450L
/** Moves closer together than this are a held direction: the ring runs along as one, no stretch. */
private const val REPEAT_MS = 180L
/** A move further than this goes as a droplet: pinched to a drop, carried across, opened onto the control. */
private val FAR = 360.dp
/**
* Hosts the sliding focus ring for everything inside it. The ring is drawn over [content], in the
* host's space, so put the host inside anything that moves as a whole (a sheet that slides in).
*/
@Composable
internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
val view = LocalView.current
val density = LocalDensity.current
val dir = LocalLayoutDirection.current
val glide = remember(view) { FocusGlide(view) }
val edges = remember { List(4) { Animatable(0f) } } // left, top, right, bottom
val corner = remember { Animatable(0f) }
/** How solid the ring is: 1 while it travels as a drop, 0 (an outline) on a control. */
val solid = remember { Animatable(0f) }
val alpha = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
// An edge each, the corner, and a droplet carrying all of them.
val jobs = remember { arrayOfNulls<Job>(6) }
val cur = glide.current
var lastColor by remember { mutableStateOf(Color.Transparent) }
if (cur != null) lastColor = cur.color
val color by animateColorAsState(cur?.color ?: lastColor, Motion.tw(160), label = "glideColor")
var width by remember { mutableStateOf(2.dp) }
if (cur != null) width = cur.width
LaunchedEffect(glide) {
var shown: GlideSource? = null
var movedAt = 0L
var dirSpecs: List<AnimationSpec<Float>> = List(4) { follow() }
var delays = LongArray(4)
var lastMove = 0L
fun go(i: Int, v: Float, spec: AnimationSpec<Float>, wait: Long) {
// A drop cut short by another move turns back into an outline on the way.
if (jobs[5]?.isActive == true || solid.targetValue > 0f) scope.launch { solid.animateTo(0f, Motion.tw(120)) }
jobs[5]?.cancel()
// Picks up the speed it is going at: restarting from rest on every step of a held
// direction is what made it stutter.
val speed = edges[i].velocity
jobs[i]?.cancel()
jobs[i] = scope.launch {
if (wait > 0) delay(Motion.ms(wait.toInt()).toLong())
edges[i].animateTo(v, spec, initialVelocity = if (wait > 0) 0f else speed)
}
}
/** Pinch into a solid dot where it is, carry it over, and open it into [b] as it arrives. */
fun droplet(s: GlideSource, b: Rect) {
jobs.forEach { it?.cancel() }
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
val endCorner = cornerOf(s.shape, size, dir, density)
jobs[5] = scope.launch {
val r = with(density) { 6.dp.toPx() }
fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r)
val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f)
// Pinch into a solid drop where it is.
coroutineScope {
launch { solid.animateTo(1f, Motion.tw(80)) }
launch { corner.animateTo(r, Motion.tw(90)) }
dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } }
}
// Across as a dot, every edge together, on a timed ease.
val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density
val travel = (180 + distance * 0.12f).toInt().coerceIn(220, 380)
dot(b.center).forEachIndexed { i, v ->
jobs[i] = launch { edges[i].animateTo(v, Motion.tw(travel, easing = FastOutSlowInEasing)) }
}
// Takes the control's shape as it arrives, not after: no resting as a dot.
delay(Motion.ms((travel * 0.78f).toInt()).toLong())
launch { solid.animateTo(0f, Motion.tw(150)) }
launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) }
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v ->
jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) }
}
}
}
fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) {
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
val r = cornerOf(s.shape, size, dir, density)
jobs[4]?.cancel()
jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) }
}
snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) ->
if (hidden) {
jobs.forEach { it?.cancel() }
alpha.snapTo(0f)
solid.snapTo(0f)
shown = null
return@collectLatest
}
if (src == null) {
// Focus passing between two controls can let go of one a moment before the next
// takes it: wait a beat, so that reads as a move and not a fade out and back in.
delay(60)
scope.launch { alpha.animateTo(0f, Motion.tw(140)) }
shown = null
return@collectLatest
}
var first = src !== shown
val start = System.nanoTime()
var last: Rect? = null
while (true) {
val b = glide.boundsOf(src)
if (b == null) {
if (first) scope.launch { alpha.animateTo(0f, Motion.tw(140)) }
} else if (first) {
var dropped = false
val prev = shown
val wasShowing = prev != null && alpha.targetValue > 0f
shown = src
first = false
if (!wasShowing) {
// Appearing: a hair bigger, pulled in onto the control as it fades up.
val out = with(density) { 3.dp.toPx() }
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
jobs.forEach { it?.cancel() }
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
dirSpecs = List(4) { Motion.sp(0.6f, 700f) }
delays = LongArray(4)
cornerTo(src, b, snap = true)
scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
} else {
// Moving: the edges on the side it is heading lead.
val dx = b.center.x - (edges[0].value + edges[2].value) / 2f
val dy = b.center.y - (edges[1].value + edges[3].value) / 2f
val horizontal = abs(dx) >= abs(dy)
val leadIdx = if (horizontal) (if (dx >= 0) 2 else 0) else (if (dy >= 0) 3 else 1)
val trailIdx = (leadIdx + 2) % 4
val now = System.nanoTime()
val held = (now - lastMove) / 1_000_000 < REPEAT_MS
lastMove = now
scope.launch { alpha.animateTo(1f, Motion.tw(120)) }
dropped = !held && hypot(dx, dy) > with(density) { FAR.toPx() }
if (dropped) droplet(src, b)
else {
// A held direction runs along as one piece; a single press stretches.
dirSpecs = if (held) List(4) { Motion.sp(0.9f, 900f) }
else List(4) { i -> when (i) { leadIdx -> lead(); trailIdx -> trail(); else -> Motion.sp(0.7f, 520f) } }
delays = LongArray(4) { i -> if (i == trailIdx && !held) 30L else 0L }
cornerTo(src, b, snap = false)
}
}
movedAt = System.nanoTime()
if (!dropped) listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> go(i, v, dirSpecs[i], delays[i]) }
last = b
} else if (b != last && jobs[5]?.isActive != true) {
// It moved under the ring: keep the stretch while the move is fresh, else follow.
val fresh = (System.nanoTime() - movedAt) / 1_000_000 < SETTLE_MS
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> go(i, v, if (fresh) dirSpecs[i] else follow(), 0L) }
if (last == null) scope.launch { alpha.animateTo(1f, Motion.tw(120)) }
last = b
}
// Layer animations (a tile growing, a row sliding) move it without a relayout, so
// look again each frame for a moment after anything changes.
if ((System.nanoTime() - start) / 1_000_000 > SETTLE_MS) break
withFrameNanos { }
}
}
}
Box(
modifier
.onGloballyPositioned { glide.host = it }
.drawWithContent {
drawContent()
val a = alpha.value
if (a <= 0.01f) return@drawWithContent
val w = width.toPx()
val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value
val sw = (r - l - w).coerceAtLeast(0f)
val sh = (b - t - w).coerceAtLeast(0f)
val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f)
val f = solid.value
if (f > 0.01f) drawRoundRect(
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
cornerRadius = CornerRadius(corner.value), alpha = a * f,
)
if (f < 0.99f) drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
)
},
) {
CompositionLocalProvider(LocalFocusGlide provides glide) { content() }
}
}
@@ -1,48 +1,22 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
/**
* The frame generation picker, anchored to whatever opened it (host key "fg"). One copy for Setup,
* a game's launch settings and the session drawer, so they say the same thing. Importing a
* Lossless.dll is offered once the account is known to own Lossless Scaling.
* a game's launch settings and the session drawer, so they say the same thing.
*/
@Composable
internal fun FrameGenMenu(
host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State,
onPick: (FrameGen.Mode) -> Unit,
onImportLossless: () -> Unit,
host: MenuHost, engine: String, multiplier: Int, lsfgReady: Boolean,
onPick: (engine: String, multiplier: Int) -> Unit,
) {
val context = LocalContext.current
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = stringResource(R.string.frame_gen_title)) { firstItemFocus ->
val need = when {
lossless.ready -> null
lossless.owned -> stringResource(R.string.lsfg_needs_install)
else -> stringResource(R.string.lsfg_needs_steam)
}
@Composable
fun item(m: FrameGen.Mode, enabled: Boolean = true, detail: String? = null, focus: FocusRequester? = null) =
MenuItem(FrameGen.label(context, m), checked = mode == m, enabled = enabled, detail = detail, focusRequester = focus) {
onPick(m); host.open = null
}
item(FrameGen.Mode.OFF, focus = firstItemFocus)
for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_WINFG, m))
val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } +
FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) }
lsfg.forEachIndexed { i, m -> item(m, enabled = lossless.ready, detail = need.takeIf { i == 0 }) }
if (lossless.owned) {
val using = when (lossless.source) {
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
Lossless.Source.NONE -> null
}
MenuItem(stringResource(R.string.lsfg_import), checked = false, detail = using) { host.open = null; onImportLossless() }
}
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus ->
val need = if (lsfgReady) null else "Needs Lossless Scaling installed in Steam"
fun pick(e: String, m: Int) { onPick(e, m); host.open = null }
MenuItem("Off", checked = engine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { pick(FrameGen.ENGINE_OFF, 2) }
for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_WINFG, m), checked = engine == FrameGen.ENGINE_WINFG && multiplier == m) { pick(FrameGen.ENGINE_WINFG, m) }
for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_LSFG, m), checked = engine == FrameGen.ENGINE_LSFG && multiplier == m, enabled = lsfgReady, detail = need) { pick(FrameGen.ENGINE_LSFG, m) }
}
}
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff. Show more