Compare commits

..
Author SHA1 Message Date
maxjivi05 b31ab5fa96 Merge remote-tracking branch 'origin/main' into fix/pr103-conflicts
# Conflicts:
#	app/src/main/java/com/droiddeck/launcher/App.kt
#	app/src/main/java/com/droiddeck/launcher/MainActivity.kt
#	app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt
2026-09-30 16:56:59 -04:00
Kurt Himebauch 02fa7983e9 Merge branch 'main' into feat/gpu-driver-auto 2026-09-30 16:20:58 -04:00
MaxsTechReview 5e55189d03 DD-Turnip Driver Support (#106) 2026-09-30 16:20:28 -04:00
xXJsonDeruloXx f76a58ea1e feat: pick GPU drivers as matched pairs, set automatically for the device's GPU 2026-09-30 14:32:58 -04:00
44 changed files with 330 additions and 2266 deletions

No files matched your search

+1 -18
View File
@@ -374,7 +374,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 -->"
@@ -388,15 +387,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. A maintainer can run **PR Release Publish** from \`main\` to create an APK that installs over the release."
;;
failure)
echo "### ERROR: Build failed"
@@ -524,8 +515,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:
@@ -587,9 +576,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
+9 -19
View File
@@ -2,16 +2,14 @@ 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
# (a merged fix is in the next Nightly). 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
permissions: {}
jobs:
cleanup:
@@ -32,18 +30,10 @@ jobs:
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
tag="pr-$PR_NUMBER"
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"
else
echo "No test build for PR #$PR_NUMBER"
fi
+18 -185
View File
@@ -1,52 +1,31 @@
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 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
@@ -56,64 +35,25 @@ jobs:
- 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 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
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; }
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 base "$base" --argjson number "$PR_NUMBER" '
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
@@ -145,11 +85,8 @@ jobs:
.head.sha == $head and .base.sha == $base
' <<<"$current" >/dev/null
{
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"
@@ -163,7 +100,6 @@ jobs:
label: ${{ needs.authorize.outputs.label }}
artifact: droiddeck-pr-signed
secrets: inherit
if: ${{ needs.authorize.outputs.skip != 'true' }}
publish:
needs: [authorize, sign]
@@ -171,8 +107,7 @@ jobs:
permissions:
actions: read
contents: read
issues: write
pull-requests: write
pull-requests: read
steps:
- uses: actions/download-artifact@v4
with:
@@ -184,7 +119,7 @@ jobs:
- 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")
@@ -208,13 +143,10 @@ 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 }}
run: |
set -euo pipefail
repo=Droid-Deck/DroidDeck-CI
@@ -225,20 +157,15 @@ jobs:
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
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 edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
# Drop the previous build's files: anything this build did not just upload.
@@ -248,97 +175,3 @@ jobs:
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
-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 -2
View File
@@ -13,13 +13,13 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big
## 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.
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, nightly 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
-3
View File
@@ -55,8 +55,6 @@ def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getO
?: 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.
@@ -85,7 +83,6 @@ android {
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}\""
+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);
@@ -17,7 +17,6 @@ class App : Application() {
// Before anything else touches the session prefs: a new install's first read decides it.
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)
}
@@ -144,7 +144,6 @@ 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)
@@ -476,16 +475,6 @@ 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)
@@ -635,7 +624,6 @@ class MainActivity : ComponentActivity() {
if (!SessionState.running) Thread({
SessionArtifacts.finishAbandoned(this)
SessionArtifacts.scrubOlder(this)
SessionArtifacts.prune(this)
}, "finish-abandoned").start()
}
@@ -959,7 +947,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,
@@ -995,7 +982,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
@@ -1122,7 +1108,6 @@ 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)
@@ -98,25 +98,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). */
@@ -237,24 +219,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()
@@ -296,7 +269,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 {
@@ -614,9 +586,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
@@ -1556,14 +1526,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 }
@@ -91,7 +91,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
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
@@ -157,7 +157,6 @@ object DeviceReport {
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))
@@ -174,7 +173,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
}
@@ -110,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)
@@ -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) {
@@ -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,15 +16,13 @@ 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
* 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,
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 {
@@ -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",
)
}
}
@@ -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
@@ -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" }
}
@@ -184,12 +184,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
@@ -605,7 +599,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
@@ -299,7 +299,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
@@ -540,7 +540,6 @@ class SessionService : Service() {
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
@@ -617,7 +616,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.
@@ -643,15 +642,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
@@ -664,11 +659,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
}
@@ -681,11 +674,7 @@ 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")
@@ -708,12 +697,9 @@ class SessionService : Service() {
if (library != null) {
val problem = GameStorage.prepare(library.path)
if (problem == null) {
File(LinuxRuntime.rootDir(this), "mnt/droiddeck-sd").mkdirs()
binds.add("${library.path}:/mnt/droiddeck-sd")
// Links, prefixes and Steam entries made before the rename still name the old path.
File(LinuxRuntime.rootDir(this), "mnt/bannerlator-sd").mkdirs()
binds.add("${library.path}:/mnt/bannerlator-sd")
Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\")")
Log.i(TAG, "game storage: ${library.path} -> /mnt/bannerlator-sd (\"${library.label}\")")
} else {
Log.w(TAG, "game storage: $problem; internal only this session")
}
@@ -1197,18 +1183,6 @@ 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. */
@@ -1238,6 +1212,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. */
@@ -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)
@@ -153,7 +153,6 @@ class FrontEndActions(
val onBrowseFiles: (File) -> Unit = {},
val onLogs: () -> Unit,
val onShareLogs: () -> Unit = {},
val onClearLogs: () -> Unit = {},
val onOffline: () -> Unit,
val onPageBack: () -> Unit = {},
val onTheme: (String) -> Unit = {},
@@ -289,7 +289,6 @@ internal fun SetupPanel(
}
ToggleRow(host, "logs", "Session logs", "Saved after each session", s.logsEnabled) { a.onLogs() }
ActionRow("Latest session logs", "Send them with a bug report", "Share logs", a.onShareLogs)
ActionRow("Saved session logs", "The newest ${com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS} are kept", "Clear logs", a.onClearLogs)
ToggleRow(
host, "offline", "Offline mode",
s.offlineAccount?.let { "Signed in as $it" } ?: "Sign in to Steam first",
@@ -68,7 +68,6 @@ class ModeSettings(
val fexPreset: String? = null,
/** Steam only: games are stretched to fill the screen (null = not a Steam page). */
val forceFullscreen: Boolean? = null,
val stretch16x9: Boolean? = null,
/** Steam only: the client branch forced on the command line. */
val steamChannel: String? = null,
/** Steam only: enable the SteamOS client interface and its performance controls. */
@@ -118,7 +117,6 @@ class ModeSettingsActions(
val onPickGameStorageFolder: () -> Unit = {},
val onFexPreset: (String) -> Unit = {},
val onForceFullscreen: (Boolean) -> Unit = {},
val onStretch16x9: (Boolean) -> Unit = {},
val onSteamChannel: (String) -> Unit = {},
val onSteamDeckMode: (Boolean) -> Unit = {},
val onMangoapp: (Boolean) -> Unit = {},
@@ -363,11 +361,6 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
"Keeps games that resize their own window (FlatOut) full screen. Turn it off if a game shows up small in a corner (Quake 3). Applies next session.",
s.forceFullscreen, onChange = a.onForceFullscreen,
)
if (s.stretch16x9 != null) ToggleRow(
host, "stretch169", "Stretch 16:9 games to a narrower screen",
"On a screen squarer than 16:9 (a foldable's inner panel), games render at 16:9 and are stretched to fill it: no bars, slightly wider-looking. Applies next session.",
s.stretch16x9, onChange = a.onStretch16x9,
)
}
if (steam && s.directAudio != null && s.mic != null) SettingsGroup("Audio") {
ToggleRow(host, "da", "DirectAudio for games", "Bypasses PulseAudio for lower latency in games.", s.directAudio, onChange = a.onDirectAudio)
@@ -112,15 +112,10 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
if (LocalNarrowPane.current) {
StatusPanel(s, u, ua, me)
Box(Modifier.height(18.dp))
ChannelLabel()
ChannelPicker(u, ua)
} else {
// The label sits over both columns, so the status card lines up with the first channel.
ChannelLabel()
Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) {
Box(Modifier.weight(1f)) { ChannelPicker(u, ua) }
Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) }
}
} else Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) {
Box(Modifier.weight(1f)) { ChannelPicker(u, ua) }
Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) }
}
}
}
@@ -145,21 +140,20 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
val pal = LocalPalette.current
val catalog = u.catalog
val release = catalog?.let { AppUpdates.release(it, u.follow) }
val offer = if (me.updatable) catalog?.let { AppUpdates.offer(it, u.follow, me) } else null
val offer = if (me.ci) catalog?.let { AppUpdates.offer(it, u.follow, me) } else null
val name = channelName(u.follow)
val offered = release != null && (offer == Offer.UPDATE || offer == Offer.SWITCH)
val installBlock = release?.let { AppUpdates.installBlock(it, me) }
class Look(val tint: Color, val status: String, val headline: String, val detail: String?)
val look = when {
!me.updatable -> Look(colors.onSurfaceVariant, "Signed differently", "Can't update in place",
"This copy isn't signed with DroidDeck's release key, so Android won't install the builds here over it. Uninstall it to switch.")
!me.ci -> Look(colors.onSurfaceVariant, "Local build", "Built on a computer",
"It's signed differently from the builds here, so Android won't update it in place. Uninstall it to switch.")
catalog == null -> Look(colors.onSurfaceVariant, if (u.checking) "Checking…" else "Not checked yet", "Updates", null)
offer == Offer.UPDATE -> Look(AttentionAmber, "Update available", newBuild(u.follow, release!!), null)
offer == Offer.SWITCH -> Look(pal.signal, "Ready to switch", newBuild(u.follow, release!!), null)
offer == Offer.AHEAD -> Look(pal.signal, "Ahead of Stable", "You're ahead of Stable",
"This build is newer than the last Stable release. You'll move onto Stable with its next one.")
offer == Offer.GONE -> Look(AttentionAmber, "Test ended", "This test has ended",
"Its fix was merged or dropped. Follow Preview to keep getting the newest fixes.")
"Its fix was merged or dropped. Follow Nightly to keep getting the newest fixes.")
else -> Look(pal.good, "Up to date", "You have the latest $name", null)
}
Column(
@@ -175,11 +169,8 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
ReleaseNotes(changeTitle(release!!.title.ifBlank { release.tag }), release.summary, release.tag)
}
if (look.detail != null) Text(look.detail, fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 10.dp))
if (installBlock != null && (offered || offer == Offer.AHEAD)) {
Text(installBlock, fontSize = 13.sp, color = AttentionAmber, modifier = Modifier.padding(top = 10.dp))
}
if (u.error != null) Text(u.error, fontSize = 13.sp, color = pal.error, modifier = Modifier.padding(top = 12.dp))
val installable = release?.apk != null && installBlock == null && !s.sessionRunning
val installable = release?.apk != null && !s.sessionRunning
val button = release?.apk?.size?.takeIf { it > 0 }?.let { " · ${megabytes(it)}" }.orEmpty()
Box(Modifier.padding(top = 14.dp)) {
when {
@@ -190,9 +181,8 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
}
offer == Offer.UPDATE -> PrimaryButton("Update$button", enabled = installable, main = true) { ua.onInstall(release!!) }
offer == Offer.SWITCH -> PrimaryButton("Install$button", enabled = installable, main = true) { ua.onInstall(release!!) }
offer == Offer.AHEAD && installBlock == null ->
SecondaryButton("Install Stable ${release?.version.orEmpty()} anyway", enabled = installable) { ua.onInstall(release!!) }
offer == Offer.GONE -> PrimaryButton("Follow Preview", main = true) { ua.onFollow(Follow(Channel.NIGHTLY)) }
offer == Offer.AHEAD -> SecondaryButton("Install Stable ${release?.version.orEmpty()} anyway", enabled = installable) { ua.onInstall(release!!) }
offer == Offer.GONE -> PrimaryButton("Follow Nightly", main = true) { ua.onFollow(Follow(Channel.NIGHTLY)) }
}
}
if (s.sessionRunning && (offered || offer == Offer.AHEAD)) {
@@ -231,10 +221,10 @@ private fun ReleaseNotes(title: String, notes: String, key: String) {
}
}
/** The headline for a build on offer: "DroidDeck 0.3.0", "New Preview build", "PR #93 test build". */
/** The headline for a build on offer: "DroidDeck 0.3.0", "New Nightly build", "PR #93 test build". */
private fun newBuild(f: Follow, r: Release) = when (f.channel) {
Channel.STABLE -> "DroidDeck ${r.version ?: r.tag}"
Channel.NIGHTLY -> "New Preview build"
Channel.NIGHTLY -> "New Nightly build"
Channel.TEST -> "PR #${r.pr} test build"
}
@@ -245,27 +235,20 @@ private fun changeTitle(t: String): String =
private fun megabytes(bytes: Long) = "${(bytes + 524_288) / 1_048_576} MB"
/** The three channels as cards to pick from; Test builds opens its list of PRs under it. */
@Composable
private fun ChannelLabel() {
Text(
"UPDATE CHANNEL", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp),
)
}
@Composable
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
val colors = MaterialTheme.colorScheme
val catalog = u.catalog
val tests = catalog?.tests.orEmpty()
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("UPDATE CHANNEL", fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp))
ChannelCard(
Icons.Outlined.Verified, "Stable", "Tested releases, for most people",
catalog?.stable?.let { "${it.version ?: it.tag} · ${ago(it.publishedAt)}" }, u.follow.channel == Channel.STABLE,
) { ua.onFollow(Follow(Channel.STABLE)) }
ChannelCard(
Icons.Outlined.Bolt, "Preview", "Newest main-branch fixes, before Stable",
catalog?.preview?.let { ago(it.publishedAt) }, u.follow.channel == Channel.NIGHTLY,
Icons.Outlined.Bolt, "Nightly", "Newest fixes, the odd new bug",
catalog?.nightly?.let { ago(it.publishedAt) }, u.follow.channel == Channel.NIGHTLY,
) { ua.onFollow(Follow(Channel.NIGHTLY)) }
ChannelCard(
Icons.Outlined.Science, "Test builds", "Try a fix before it's released",
@@ -348,7 +331,7 @@ private fun TestRow(t: Release, selected: Boolean, onClick: () -> Unit) {
private fun channelName(f: Follow) = when (f.channel) {
Channel.STABLE -> "Stable"
Channel.NIGHTLY -> "Preview"
Channel.NIGHTLY -> "Nightly"
Channel.TEST -> "the PR #${f.pr} test"
}
@@ -1,121 +1,73 @@
package com.droiddeck.launcher.update
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.core.Hashes
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.time.Instant
/**
* DroidDeck's published builds. CI turns GitHub Releases into one static catalog in DroidDeck-CI;
* the app consumes that contract instead of inferring channels from tags and release-note prose.
* DroidDeck's own builds, on three channels: Stable (the org repo's latest release), Nightly (the
* newest `main-<sha>` release on DroidDeck-CI, one per merge to main) and Test (a `pr-<n>` release
* on DroidDeck-CI, a signed build of an open PR). All three are signed with the release key, so any
* of them installs over any other and keeps the app's data.
*
* [Channel.NIGHTLY] is intentionally kept as the internal enum/pref value for upgrades from older
* DroidDeck versions. The channel is presented to users as Preview.
* Which build is newer is decided without a diff of the repo (GitHub's compare answers in
* megabytes): main is linear, so the newest main build is the newest; Stable is ordered by its
* version; a test build is newer when its PR's head moved. The last check is remembered, so the
* page shows it without going online.
*/
object AppUpdates {
private const val REPO = "Droid-Deck/DroidDeck"
private const val CI_REPO = "Droid-Deck/DroidDeck-CI"
private const val CATALOG_URL = "https://raw.githubusercontent.com/$CI_REPO/main/catalog.json"
private const val PREFS = "app_updates"
private const val KEY_CATALOG = "catalog"
private const val KEY_CHANNEL = "channel"
private const val CATALOG_SCHEMA = 1
enum class Channel { STABLE, NIGHTLY, TEST }
/** The channel the user follows; [pr] is the followed test build's PR, for [Channel.TEST]. */
data class Follow(val channel: Channel, val pr: Int = 0)
class Apk(
val name: String,
val url: String,
val size: Long,
val sha256: String,
val packageName: String,
val versionCode: Int,
val signerSha256: String,
)
class Apk(val name: String, val url: String, val size: Long, val sha256: String)
/**
* One published build. [commit] is a full or short SHA of the source it was built from; [pr] is
* 0 for a main or stable build. [apk] is the file for the package this app runs as, or null when
* the build has none (a variant a release predates).
*/
class Release(
val tag: String,
val title: String,
val summary: String,
val commit: String,
val pr: Int,
val version: String?,
val versionCode: Int,
val publishedAt: Long,
val url: String,
val apk: Apk?,
val tag: String, val title: String, val summary: String, val commit: String, val pr: Int,
val version: String?, val publishedAt: Long, val url: String, val apk: Apk?,
)
class Catalog(
val stable: Release?,
val preview: Release?,
val tests: List<Release>,
val checkedAt: Long,
)
class Catalog(val stable: Release?, val nightly: Release?, val tests: List<Release>, val checkedAt: Long)
class Installed(
val commit: String,
val pr: Int,
val version: String,
val versionCode: Int,
val updatable: Boolean,
val committedAt: Long = 0L,
)
/** What is running: the commit it was built from, its PR (0 for none), whether CI made it, and when it was committed. */
class Installed(val commit: String, val pr: Int, val version: String, val ci: Boolean, val committedAt: Long = 0L)
enum class Offer {
/** This is the build the channel has. */
CURRENT,
/** The channel has a newer build of what is running. */
UPDATE,
/** The channel's build is a different line (a test build from Nightly, or back); installing moves over. */
SWITCH,
/** What is running is newer than the channel's build (a Nightly past the last Stable). */
AHEAD,
/** The followed test build is gone: its PR was merged or closed. */
GONE,
}
@Volatile private var releaseSigned = BuildConfig.CI_BUILD
fun init(context: Context) {
releaseSigned = runCatching {
signers(context).any { it.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true) }
}.getOrDefault(BuildConfig.CI_BUILD)
}
private fun signers(context: Context): List<String> {
val pm = context.packageManager
@Suppress("DEPRECATION")
val certs = if (Build.VERSION.SDK_INT >= 28) {
val info = pm.getPackageInfo(
context.packageName,
PackageManager.GET_SIGNING_CERTIFICATES,
).signingInfo ?: return emptyList()
if (info.hasMultipleSigners()) info.apkContentsSigners else info.signingCertificateHistory
} else {
pm.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES).signatures
} ?: return emptyList()
return certs.map { cert ->
MessageDigest.getInstance("SHA-256").digest(cert.toByteArray())
.joinToString("") { "%02x".format(it) }
}
}
fun installed(): Installed = Installed(
BuildConfig.SOURCE_COMMIT,
BuildConfig.PR_NUMBER,
BuildConfig.VERSION_NAME,
BuildConfig.VERSION_CODE,
releaseSigned,
BuildConfig.COMMIT_TIME,
)
fun installed(): Installed = Installed(BuildConfig.SOURCE_COMMIT, BuildConfig.PR_NUMBER, BuildConfig.VERSION_NAME, BuildConfig.CI_BUILD, BuildConfig.COMMIT_TIME)
fun release(catalog: Catalog, follow: Follow): Release? = when (follow.channel) {
Channel.STABLE -> catalog.stable
Channel.NIGHTLY -> catalog.preview
Channel.NIGHTLY -> catalog.nightly
Channel.TEST -> catalog.tests.firstOrNull { it.pr == follow.pr }
}
@@ -133,27 +85,19 @@ object AppUpdates {
}
}
fun hasUpdate(catalog: Catalog?, follow: Follow): Boolean {
if (catalog == null) return false
val me = installed()
val r = release(catalog, follow) ?: return false
return me.updatable && offer(catalog, follow, me) == Offer.UPDATE && installBlock(r, me) == null
}
/** The dot on the rail: the followed channel has a newer build of what is running. */
fun hasUpdate(catalog: Catalog?, follow: Follow): Boolean =
catalog != null && installed().ci && offer(catalog, follow) == Offer.UPDATE
fun isRunning(r: Release, me: Installed = installed()): Boolean {
if (me.commit.length < 7 || r.commit.length < 7 || r.pr != me.pr) return false
return me.commit.startsWith(r.commit, ignoreCase = true) ||
r.commit.startsWith(me.commit, ignoreCase = true)
}
/** Why Android cannot install this published build over [me], before downloading anything. */
fun installBlock(r: Release, me: Installed = installed()): String? = when {
r.apk == null -> "This build has no download for this copy of DroidDeck."
r.apk.versionCode < me.versionCode ->
"Android won't install it over this build because its versionCode ${r.apk.versionCode} is below the installed ${me.versionCode}."
else -> null
return me.commit.startsWith(r.commit, ignoreCase = true) || r.commit.startsWith(me.commit, ignoreCase = true)
}
/**
* The channel followed. Until the user picks one it is worked out once from what is running and
* kept: a test build follows its PR, the Stable release follows Stable, and a main build Nightly.
*/
fun follow(context: Context, catalog: Catalog?): Follow {
stored(context)?.let { return it }
val me = installed()
@@ -161,7 +105,7 @@ object AppUpdates {
me.pr != 0 -> Follow(Channel.TEST, me.pr)
catalog == null -> return Follow(Channel.STABLE)
catalog.stable != null && isRunning(catalog.stable, me) -> Follow(Channel.STABLE)
me.updatable -> Follow(Channel.NIGHTLY)
me.ci -> Follow(Channel.NIGHTLY)
else -> Follow(Channel.STABLE)
}
setFollow(context, inferred)
@@ -169,9 +113,7 @@ object AppUpdates {
}
fun setFollow(context: Context, follow: Follow) {
// Keep "nightly" on disk so an older DroidDeck still understands the preference after rollback.
val value = if (follow.channel == Channel.TEST) "test:${follow.pr}"
else follow.channel.name.lowercase()
val value = if (follow.channel == Channel.TEST) "test:${follow.pr}" else follow.channel.name.lowercase()
prefs(context).edit().putString(KEY_CHANNEL, value).apply()
}
@@ -179,115 +121,129 @@ object AppUpdates {
val v = prefs(context).getString(KEY_CHANNEL, null) ?: return null
return when {
v == "stable" -> Follow(Channel.STABLE)
v == "nightly" || v == "preview" -> Follow(Channel.NIGHTLY)
v.startsWith("test:") -> v.removePrefix("test:").toIntOrNull()?.let {
Follow(Channel.TEST, it)
}
v == "nightly" -> Follow(Channel.NIGHTLY)
v.startsWith("test:") -> v.removePrefix("test:").toIntOrNull()?.let { Follow(Channel.TEST, it) }
else -> null
}
}
/** The last check, or null before the first. */
fun cached(context: Context): Catalog? {
val raw = prefs(context).getString(KEY_CATALOG, null) ?: return null
return runCatching { readCachedCatalog(JSONObject(raw)) }.getOrNull()
return runCatching { readCatalog(JSONObject(raw)) }.getOrNull()
}
/** One static request, rather than several unauthenticated GitHub API requests. */
/** Read every channel now and remember the result: three small requests, four for an annotated tag. */
fun refresh(context: Context): Catalog {
val checkedAt = System.currentTimeMillis()
val catalog = readPublishedCatalog(
JSONObject(get("$CATALOG_URL?checked=$checkedAt")),
context.packageName,
checkedAt,
)
val suffix = variantSuffix(context.packageName)
val stable = runCatching { stable(suffix) }.getOrElse { if (it is NoRelease) null else throw it }
val ci = JSONArray(get("https://api.github.com/repos/$CI_REPO/releases?per_page=50"))
var nightly: Release? = null
val tests = ArrayList<Release>()
for (i in 0 until ci.length()) {
val r = ci.getJSONObject(i)
if (r.optBoolean("draft")) continue
val tag = r.getString("tag_name")
when {
tag.startsWith("main-") -> {
val candidate = ciRelease(r, suffix, tag.removePrefix("main-"), 0)
if (nightly == null || candidate.publishedAt > nightly.publishedAt) nightly = candidate
}
tag.startsWith("pr-") -> {
val pr = tag.removePrefix("pr-").toIntOrNull() ?: continue
val body = r.optString("body")
// Only builds of this repo's PRs: a test build from before the org move names another.
if (!body.contains("github.com/$REPO/pull/$pr")) continue
val commit = Regex("""Commit: `?([0-9a-f]{7,40})""").find(body)?.groupValues?.get(1) ?: continue
tests.add(ciRelease(r, suffix, commit, pr))
}
}
}
tests.sortByDescending { it.publishedAt }
val catalog = Catalog(stable, nightly, tests, System.currentTimeMillis())
prefs(context).edit().putString(KEY_CATALOG, writeCatalog(catalog).toString()).apply()
return catalog
}
internal fun readPublishedCatalog(
root: JSONObject,
packageName: String,
checkedAt: Long,
): Catalog {
val schema = root.optInt("schema")
val sourceRepo = root.optString("sourceRepo")
val ciRepo = root.optString("ciRepo")
if (schema != CATALOG_SCHEMA || sourceRepo != REPO || ciRepo != CI_REPO) {
throw IOException(
"The update catalog has an unsupported format (schema $schema, source $sourceRepo, CI $ciRepo)",
)
private class NoRelease : IOException("no stable release")
private fun stable(suffix: String): Release {
val r = try {
JSONObject(get("https://api.github.com/repos/$REPO/releases/latest"))
} catch (e: IOException) {
if (e.message?.contains("HTTP 404") == true) throw NoRelease() else throw e
}
val tests = root.optJSONArray("tests") ?: JSONArray()
return Catalog(
root.optJSONObject("stable")?.let { readPublishedRelease(it, packageName) },
root.optJSONObject("preview")?.let { readPublishedRelease(it, packageName) },
(0 until tests.length())
.map { readPublishedRelease(tests.getJSONObject(it), packageName) }
.filter { it.pr > 0 }
.sortedByDescending { it.publishedAt },
checkedAt,
)
val tag = r.getString("tag_name")
// The tag's commit; an annotated tag points at a tag object first.
var obj = JSONObject(get("https://api.github.com/repos/$REPO/git/ref/tags/$tag")).getJSONObject("object")
if (obj.getString("type") == "tag") obj = JSONObject(get(obj.getString("url"))).getJSONObject("object")
val (title, summary) = describeStable(r.optString("name").ifBlank { tag }, r.optString("body"))
return Release(tag, title, summary, obj.getString("sha"), 0, tag.removePrefix("v"), published(r),
r.optString("html_url"), apk(r, suffix))
}
private fun readPublishedRelease(o: JSONObject, packageName: String): Release {
val commit = o.getString("commit")
if (!Regex("^[0-9a-fA-F]{7,40}$").matches(commit)) {
throw IOException("The update catalog contains an invalid commit")
}
val versionCode = o.getInt("versionCode")
if (versionCode <= 0) throw IOException("The update catalog contains an invalid versionCode")
val apk = o.optJSONObject("apks")?.optJSONObject(packageName)?.let {
readPublishedApk(it, packageName)
}
if (apk != null && apk.versionCode != versionCode) {
throw IOException("The update catalog disagrees about the APK versionCode")
}
return Release(
o.getString("tag"),
o.optString("title"),
o.optString("summary"),
commit,
o.optInt("pr"),
if (o.isNull("version")) null else o.optString("version").ifEmpty { null },
versionCode,
o.optLong("publishedAt"),
o.optString("url"),
apk,
)
private fun ciRelease(r: JSONObject, suffix: String, commit: String, pr: Int): Release {
val (title, summary) = describeCi(r.optString("name"), r.optString("body"))
return Release(r.getString("tag_name"), title, summary, commit, pr, null, published(r), r.optString("html_url"), apk(r, suffix))
}
private fun readPublishedApk(o: JSONObject, packageName: String): Apk {
val actualPackage = o.getString("packageName")
val versionCode = o.getInt("versionCode")
val signer = o.getString("signerSha256").lowercase()
val sha = o.getString("sha256").lowercase()
val url = o.getString("url")
if (actualPackage != packageName) throw IOException("The update catalog names the wrong Android package")
if (versionCode <= 0) throw IOException("The update catalog has an invalid APK versionCode")
if (!Regex("^[0-9a-f]{64}$").matches(sha)) {
throw IOException("The update catalog has an invalid checksum")
private fun published(r: JSONObject): Long =
runCatching { Instant.parse(r.optString("published_at")).toEpochMilli() }.getOrDefault(0L)
/** The apk for this package: `<name><suffix>.apk`, and for the standard app the one with no other variant's suffix. */
private fun apk(r: JSONObject, suffix: String): Apk? {
val others = variantSuffixes().values.filter { it.isNotEmpty() && it != suffix }
val assets = r.optJSONArray("assets") ?: return null
for (i in 0 until assets.length()) {
val a = assets.getJSONObject(i)
val name = a.getString("name")
if (!name.endsWith("$suffix.apk") || others.any { name.endsWith("$it.apk") }) continue
// Only a file GitHub has a sha256 for: the download is checked against it.
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
return Apk(name, a.getString("browser_download_url"), a.optLong("size"), sha)
}
if (!signer.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true)) {
throw IOException("The update catalog is not signed for DroidDeck's release key")
}
val allowed = listOf(
"https://github.com/$REPO/releases/download/",
"https://github.com/$CI_REPO/releases/download/",
)
if (allowed.none { url.startsWith(it) }) {
throw IOException("The update catalog has an unexpected download URL")
}
return Apk(
o.getString("name"),
url,
o.optLong("size"),
sha,
actualPackage,
versionCode,
signer,
)
return null
}
private fun variantSuffixes(): Map<String, String> = BuildConfig.VARIANT_SUFFIXES.split(';')
.mapNotNull { e -> e.split('=', limit = 2).takeIf { it.size == 2 }?.let { it[0] to it[1] } }.toMap()
private fun variantSuffix(packageName: String): String = variantSuffixes()[packageName] ?: ""
/**
* A CI release's notes open with what it is: "**Merged to main** - [PR #n](…): title (merged …)"
* or "**Not merged** - a test build of open [PR #n](…): title", then a paragraph from the PR.
*/
internal fun describeCi(name: String, body: String): Pair<String, String> {
val paragraphs = paragraphs(body)
val head = paragraphs.firstOrNull().orEmpty()
val title = head.substringAfter("): ", "").substringBeforeLast(" (merged").ifBlank { plain(head) }.ifBlank { name }
val summary = paragraphs.getOrNull(1)?.takeUnless { it.startsWith("Signed build") || it.startsWith("Source:") }.orEmpty()
return plain(title) to lines(summary)
}
/** A stable release: its name, and the first paragraph of its notes that is prose rather than a heading or picture. */
private fun describeStable(name: String, body: String): Pair<String, String> =
name to lines(paragraphs(body).firstOrNull { !it.startsWith("#") && !it.startsWith("![") && !it.startsWith("<") }.orEmpty())
private fun paragraphs(body: String): List<String> =
body.replace("\r", "").split(Regex("\n\\s*\n")).map { it.trim() }.filter { it.isNotEmpty() }
/** A paragraph's lines as text, a list item's marker as a bullet: the page shows them collapsed or in full. */
private fun lines(md: String): String = md.lines().map { line ->
val item = Regex("""^\s*[-*]\s+""").find(line)
if (item != null) "• " + plain(line.substring(item.range.last + 1)) else plain(line)
}.filter { it.isNotEmpty() }.joinToString("\n")
/** Markdown down to text: links to their words, emphasis and code marks gone, on one line. */
private fun plain(md: String): String = md
.replace(Regex("""!\[[^]]*]\([^)]*\)"""), "")
.replace(Regex("""\[([^]]*)]\([^)]*\)"""), "$1")
.replace(Regex("""[*_`]{1,3}"""), "")
.replace(Regex("""\s+"""), " ")
.trim()
/** Dotted versions, number by number: "0.10.0" is past "0.9.2"; a missing part counts as 0. */
fun compareVersions(a: String, b: String): Int {
val x = a.removePrefix("v").split('.', '-').map { it.toIntOrNull() ?: 0 }
val y = b.removePrefix("v").split('.', '-').map { it.toIntOrNull() ?: 0 }
@@ -302,79 +258,40 @@ object AppUpdates {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 15_000
c.readTimeout = 20_000
c.setRequestProperty("Accept", "application/json")
c.setRequestProperty("Accept", "application/vnd.github+json")
c.setRequestProperty("User-Agent", "DroidDeck-app")
c.setRequestProperty("Cache-Control", "no-cache")
try {
val code = c.responseCode
if (code != 200) throw IOException("The update catalog answered HTTP $code")
if (code == 403 || code == 429) throw IOException("GitHub's rate limit was hit - try again later")
if (code != 200) throw IOException("GitHub answered HTTP $code")
return c.inputStream.bufferedReader().use { it.readText() }
} finally {
c.disconnect()
}
}
private fun writeApk(a: Apk): JSONObject = JSONObject()
.put("name", a.name)
.put("url", a.url)
.put("size", a.size)
.put("sha256", a.sha256)
.put("packageName", a.packageName)
.put("versionCode", a.versionCode)
.put("signerSha256", a.signerSha256)
private fun writeRelease(r: Release): JSONObject = JSONObject()
.put("tag", r.tag)
.put("title", r.title)
.put("summary", r.summary)
.put("commit", r.commit)
.put("pr", r.pr)
.put("version", r.version)
.put("versionCode", r.versionCode)
.put("publishedAt", r.publishedAt)
.put("url", r.url)
.put("apk", r.apk?.let(::writeApk))
.put("tag", r.tag).put("title", r.title).put("summary", r.summary).put("commit", r.commit).put("pr", r.pr)
.put("version", r.version).put("publishedAt", r.publishedAt).put("url", r.url)
.put("apk", r.apk?.let { JSONObject().put("name", it.name).put("url", it.url).put("size", it.size).put("sha256", it.sha256) })
private fun readCachedRelease(o: JSONObject): Release = Release(
o.getString("tag"),
o.optString("title"),
o.optString("summary"),
o.getString("commit"),
o.optInt("pr"),
if (o.isNull("version")) null else o.optString("version").ifEmpty { null },
o.getInt("versionCode"),
o.optLong("publishedAt"),
o.optString("url"),
o.optJSONObject("apk")?.let {
Apk(
it.getString("name"),
it.getString("url"),
it.optLong("size"),
it.getString("sha256"),
it.getString("packageName"),
it.getInt("versionCode"),
it.getString("signerSha256"),
)
},
private fun readRelease(o: JSONObject): Release = Release(
o.getString("tag"), o.optString("title"), o.optString("summary"), o.getString("commit"), o.optInt("pr"),
o.optString("version").ifEmpty { null }, o.optLong("publishedAt"), o.optString("url"),
o.optJSONObject("apk")?.let { Apk(it.getString("name"), it.getString("url"), it.optLong("size"), it.getString("sha256")) },
)
private fun writeCatalog(c: Catalog): JSONObject = JSONObject()
.put("stable", c.stable?.let(::writeRelease))
.put("preview", c.preview?.let(::writeRelease))
.put("tests", JSONArray().apply { c.tests.forEach { put(writeRelease(it)) } })
.put("checkedAt", c.checkedAt)
.put("stable", c.stable?.let(::writeRelease)).put("nightly", c.nightly?.let(::writeRelease))
.put("tests", JSONArray().apply { c.tests.forEach { put(writeRelease(it)) } }).put("checkedAt", c.checkedAt)
private fun readCachedCatalog(o: JSONObject): Catalog {
private fun readCatalog(o: JSONObject): Catalog {
val tests = o.optJSONArray("tests") ?: JSONArray()
val preview = o.optJSONObject("preview") ?: o.optJSONObject("nightly")
return Catalog(
o.optJSONObject("stable")?.let(::readCachedRelease),
preview?.let(::readCachedRelease),
(0 until tests.length()).map { readCachedRelease(tests.getJSONObject(it)) },
o.optLong("checkedAt"),
o.optJSONObject("stable")?.let(::readRelease), o.optJSONObject("nightly")?.let(::readRelease),
(0 until tests.length()).map { readRelease(tests.getJSONObject(it)) }, o.optLong("checkedAt"),
)
}
private fun prefs(context: Context) =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}
@@ -4,11 +4,9 @@ import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.Hashes
import java.io.File
@@ -16,7 +14,6 @@ import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
/**
* Installs one of DroidDeck's own builds over itself: download into the cache, check the file
@@ -63,13 +60,9 @@ object SelfInstaller {
}
}
}
if (apk.size > 0 && target.length() != apk.size) {
throw IOException("The download size didn't match the published APK and was discarded - try again")
}
if (!apk.sha256.equals(Hashes.sha256(target), ignoreCase = true)) {
throw IOException("The download didn't match its checksum and was discarded - try again")
}
validateDownloaded(context, target, apk)
return target
} catch (e: Exception) {
FileUtils.delete(target)
@@ -79,48 +72,6 @@ object SelfInstaller {
}
}
/** Inspect the actual downloaded APK before giving it to Android's installer. */
private fun validateDownloaded(context: Context, file: File, apk: AppUpdates.Apk) {
if (apk.packageName != context.packageName) {
throw IOException("The update is for Android package ${apk.packageName}, not ${context.packageName}")
}
if (!apk.signerSha256.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true)) {
throw IOException("The update metadata doesn't name DroidDeck's release signing key")
}
@Suppress("DEPRECATION")
val flags = if (Build.VERSION.SDK_INT >= 28) {
PackageManager.GET_SIGNING_CERTIFICATES
} else {
PackageManager.GET_SIGNATURES
}
val info = context.packageManager.getPackageArchiveInfo(file.absolutePath, flags)
?: throw IOException("Android couldn't read the downloaded APK")
if (info.packageName != context.packageName) {
throw IOException("The downloaded APK is for ${info.packageName}, not ${context.packageName}")
}
@Suppress("DEPRECATION")
val code = if (Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong()
if (code != apk.versionCode.toLong()) {
throw IOException("The downloaded APK says versionCode $code, not the published ${apk.versionCode}")
}
if (code < BuildConfig.VERSION_CODE.toLong()) {
throw IOException("Android won't install versionCode $code over the installed ${BuildConfig.VERSION_CODE}")
}
// Before Android 9 this lineage intentionally presents the public legacy test key. Android
// 9+ understands the v3 hand-over and must see DroidDeck's private release key as current.
if (Build.VERSION.SDK_INT >= 28) {
val signing = info.signingInfo ?: throw IOException("The downloaded APK has no signing information")
val digests = signing.apkContentsSigners.orEmpty().map { cert ->
MessageDigest.getInstance("SHA-256").digest(cert.toByteArray())
.joinToString("") { "%02x".format(it) }
}
if (digests.none { it.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true) }) {
throw IOException("The downloaded APK isn't signed with DroidDeck's release key")
}
}
}
/** Writes [apk] into an install session and commits it; the answer comes as an [ACTION_STATUS] broadcast. */
fun install(context: Context, apk: File) {
val installer = context.packageManager.packageInstaller
@@ -1,50 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class SessionPathsTest {
@get:Rule val tmp = TemporaryFolder()
private fun dir(name: String) = tmp.newFolder(name)
@Test fun bothNamingsAreSessionFolders() {
assertTrue(SessionPaths.isSessionFolder(dir("2026-10-01-03-steam")))
assertTrue(SessionPaths.isSessionFolder(dir("2026-10-01-12-retroarch")))
assertTrue(SessionPaths.isSessionFolder(dir("session-20260930-180642")))
assertTrue(SessionPaths.isSessionFolder(dir("session-20260930-180642-2")))
}
@Test fun otherFoldersAndFilesAreNot() {
assertFalse(SessionPaths.isSessionFolder(dir("tools")))
assertFalse(SessionPaths.isSessionFolder(dir("backup-test")))
assertFalse(SessionPaths.isSessionFolder(dir("2026-10-01")))
assertFalse(SessionPaths.isSessionFolder(tmp.newFile("2026-10-01-01-steam.zip")))
}
@Test fun foldersSortByDayThenNumber() {
val folders = listOf(
dir("2026-10-01-10-desktop"), dir("session-20260930-180642"), dir("2026-10-01-02-steam"),
dir("session-20261001-063000"), dir("2026-09-30-01-steam"), dir("2026-10-01-01-steam"),
)
assertEquals(
listOf(
"session-20260930-180642", "2026-09-30-01-steam", "session-20261001-063000",
"2026-10-01-01-steam", "2026-10-01-02-steam", "2026-10-01-10-desktop",
),
folders.sortedWith(SessionPaths.chronological).map { it.name },
)
}
@Test fun labelsBecomeShortLowercaseWords() {
assertEquals("steam", SessionPaths.slug("steam"))
assertEquals("dolphin-emulator", SessionPaths.slug("Dolphin Emulator"))
assertEquals("org-telegram-desktop", SessionPaths.slug("org.telegram.desktop"))
assertEquals("a-very-long-program-name", SessionPaths.slug("A very long program name that keeps going"))
assertEquals("session", SessionPaths.slug("!!!"))
}
}
@@ -1,69 +1,26 @@
package com.droiddeck.launcher.update
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.update.AppUpdates.Channel
import com.droiddeck.launcher.update.AppUpdates.Follow
import com.droiddeck.launcher.update.AppUpdates.Installed
import com.droiddeck.launcher.update.AppUpdates.Offer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.json.JSONObject
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.io.IOException
@RunWith(RobolectricTestRunner::class)
class AppUpdatesTest {
private fun apk(versionCode: Int = 9) = AppUpdates.Apk(
"DroidDeck.apk",
"https://github.com/Droid-Deck/DroidDeck-CI/releases/download/t/DroidDeck.apk",
10,
"a".repeat(64),
"com.droiddeck.launcher",
versionCode,
BuildConfig.RELEASE_SIGNER,
)
private fun release(commit: String, pr: Int = 0, version: String? = null) =
AppUpdates.Release("t", "title", "", commit, pr, version, 0L, "", null)
private fun release(
commit: String,
pr: Int = 0,
version: String? = null,
versionCode: Int = 9,
withApk: Boolean = true,
) = AppUpdates.Release(
"t",
"title",
"",
commit,
pr,
version,
versionCode,
0L,
"",
if (withApk) apk(versionCode) else null,
)
private val stable = release(
"aaaaaaa1111111111111111111111111111111",
version = "0.2.0",
)
private val stable = release("aaaaaaa1111111111111111111111111111111", version = "0.2.0")
private val catalog = AppUpdates.Catalog(
stable = stable,
preview = release("bbbbbbb"),
nightly = release("bbbbbbb"),
tests = listOf(release("ccccccc2222222222222222222222222222222", pr = 93)),
checkedAt = 0L,
)
private fun me(
commit: String,
pr: Int = 0,
version: String = "0.2.0",
versionCode: Int = 9,
) = Installed(commit, pr, version, versionCode, updatable = true)
private fun me(commit: String, pr: Int = 0, version: String = "0.2.0") = Installed(commit, pr, version, ci = true)
@Test
fun theStableBuildIsCurrentOnStable() {
@@ -71,20 +28,17 @@ class AppUpdatesTest {
}
@Test
fun aPreviewPastStableIsAheadNotBehind() {
fun aNightlyPastStableIsAheadNotBehind() {
assertEquals(Offer.AHEAD, AppUpdates.offer(catalog, Follow(Channel.STABLE), me("ddddddd999")))
}
@Test
fun aNewerStableVersionIsAnUpdate() {
assertEquals(
Offer.UPDATE,
AppUpdates.offer(catalog, Follow(Channel.STABLE), me("eeeeeee999", version = "0.1.9")),
)
assertEquals(Offer.UPDATE, AppUpdates.offer(catalog, Follow(Channel.STABLE), me("eeeeeee999", version = "0.1.9")))
}
@Test
fun previewMatchesItsShortShaAndOffersTheNewest() {
fun nightlyMatchesItsShortShaAndOffersTheNewest() {
assertEquals(Offer.CURRENT, AppUpdates.offer(catalog, Follow(Channel.NIGHTLY), me("bbbbbbb0123456789")))
assertEquals(Offer.UPDATE, AppUpdates.offer(catalog, Follow(Channel.NIGHTLY), me(stable.commit)))
}
@@ -98,7 +52,7 @@ class AppUpdatesTest {
}
@Test
fun aTestBuildIsNeverThePreviewBuildOfTheSameCommit() {
fun aTestBuildIsNeverTheMainBuildOfTheSameCommit() {
assertEquals(Offer.SWITCH, AppUpdates.offer(catalog, Follow(Channel.NIGHTLY), me("bbbbbbb", pr = 5)))
}
@@ -110,77 +64,20 @@ class AppUpdatesTest {
}
@Test
fun aVersionCodeDowngradeIsBlockedBeforeDownload() {
val older = release("ddddddd", versionCode = 8)
assertNotNull(AppUpdates.installBlock(older, me("eeeeeee", versionCode = 9)))
assertNull(AppUpdates.installBlock(stable, me("eeeeeee", versionCode = 9)))
}
@Test
fun aMissingVariantIsBlockedBeforeDownload() {
val missing = release("ddddddd", withApk = false)
assertNotNull(AppUpdates.installBlock(missing, me("eeeeeee")))
}
private fun publishedCatalog(signer: String = BuildConfig.RELEASE_SIGNER): JSONObject {
val raw = """
{
"schema": 1,
"sourceRepo": "Droid-Deck/DroidDeck",
"ciRepo": "Droid-Deck/DroidDeck-CI",
"stable": null,
"preview": {
"tag": "main-deadbee",
"title": "Preview",
"summary": "",
"commit": "deadbee1234567890",
"pr": 0,
"version": null,
"versionCode": 9,
"publishedAt": 1,
"url": "https://github.com/Droid-Deck/DroidDeck-CI/releases/tag/main-deadbee",
"apks": {
"com.droiddeck.launcher": {
"name": "DroidDeck-main-deadbee.apk",
"url": "https://github.com/Droid-Deck/DroidDeck-CI/releases/download/main-deadbee/DroidDeck-main-deadbee.apk",
"size": 10,
"sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"packageName": "com.droiddeck.launcher",
"versionCode": 9,
"signerSha256": "__SIGNER__"
}
}
},
"tests": []
}
""".trimIndent().replace("__SIGNER__", signer)
return JSONObject(raw)
}
@Test
fun publishedCatalogSelectsThisPackagesApk() {
val parsed = AppUpdates.readPublishedCatalog(
publishedCatalog(),
"com.droiddeck.launcher",
123L,
fun ciNotesGiveTheChangeAndItsSummary() {
val (title, summary) = AppUpdates.describeCi(
"main 8a61a18",
"**Merged to main** - [PR #95](https://github.com/Droid-Deck/DroidDeck/pull/95): fix: keep `Steam` alive (merged 2026-09-30)\n\n" +
"Steam no longer **exits** on resume.\n\nSigned build of https://github.com/x - in main.",
)
assertEquals("main-deadbee", parsed.preview!!.tag)
assertEquals("com.droiddeck.launcher", parsed.preview!!.apk!!.packageName)
assertEquals(9, parsed.preview!!.apk!!.versionCode)
assertNull(parsed.preview!!.version)
assertEquals(123L, parsed.checkedAt)
}
@Test
fun publishedCatalogRejectsAnotherSigner() {
try {
AppUpdates.readPublishedCatalog(
publishedCatalog("0".repeat(64)),
"com.droiddeck.launcher",
123L,
)
fail("wrong signer should be rejected")
} catch (_: IOException) {
}
assertEquals("fix: keep Steam alive", title)
assertEquals("Steam no longer exits on resume.", summary)
val (prTitle, prSummary) = AppUpdates.describeCi(
"PR #93",
"**Not merged** - a test build of open [PR #93](https://github.com/Droid-Deck/DroidDeck/pull/93): fix: report Adreno 840v2\n\n" +
"Source: https://github.com/Droid-Deck/DroidDeck/pull/93\nCommit: 93382ff",
)
assertEquals("fix: report Adreno 840v2", prTitle)
assertEquals("", prSummary)
}
}
+6 -11
View File
@@ -21,21 +21,16 @@ The resulting snapshot is stored under that account's `userdata/<id>/config` and
refreshed every 30 seconds while logged in. Title lookups retry every five minutes and
when the source changes, so an early network failure does not end the watcher. Changed
status and probe failures are written to the session log. Startup and post-exit import
use the last successful snapshot for the selected account. The client reads manifests
and shortcuts only at start, so when a snapshot confirms owned titles that are not yet
imported, the watcher restarts the client once (not while a game runs or a download is in
progress) and the importer runs between the exit and the next start. An unavailable client or offline first launch falls back to shortcuts; existing
use the last successful snapshot for the selected account. A newly identified title
therefore starts as a shortcut and becomes a Steam entry after Steam exits and starts
again. An unavailable client or offline first launch falls back to shortcuts; existing
snapshots remain usable offline. Steam still enforces the current license at launch.
For a confirmed game without a manifest, the importer links the source folder into the
internal Steam library and writes an installed manifest with `Universe=1` and
`StateFlags=4`. Steam ignores manifests without the universe field. A manifest without
installed depots makes Steam verify every file, so the importer carries the build another
client recorded: WinNative's `.winnative-steam/steamapps` manifest beside the game folder,
or a completed download's `.DepotDownloader/depot.config` depot manifest IDs. Steam then
only downloads what changed since that build. Bare manifests from earlier imports are
upgraded while Steam has not touched them. Without either record Steam still verifies.
WinNative's manifest also identifies the folder without a store lookup. Steam updates and uninstall
`StateFlags=4`. Steam ignores manifests without the universe field. This registers
existing files; it does not assert a verified build ID or depot manifest. Steam can
still require verification, updates or redistributables. Steam updates and uninstall
operate on the linked game files, so imported folders must be writable. Existing Steam
manifests and directories are preserved. Only the exact minimal manifests generated by
the earlier importer are migrated, with the matching source symlink still present. If
-28
View File
@@ -48,34 +48,6 @@ Device-tested on the AYN Thor (Katamari under Proton Experimental ARM64).
- **Prior art checked**: WinNative and Bannerlator never emulated uinput or hidraw; Bannerlator's
`-steamdeck` mode stopped at "the virtual pad never arrives", which is this missing uinput.
## 2026-09-28 - Cemu's Turnip fix released for every driver; A8xx driver back; proven on the Galaxy Z Fold 8
State: **DroidDeck main unchanged** (`d98c211`); this is driver-side work in `The412Banner/Banners-Turnip`,
released as **`v26.3.0-20260928-r4`** (Latest; r3 is the same code - r4 was the Mesa watcher rebuilding because a
hand-started release does not update `mesa_hash.txt`).
- **The Cemu Vulkan crash is a Mesa bug, now fixed in every Banners-Turnip zip** (Android, Wayland, Linux):
`tu_knl_kgsl.cc` `kgsl_syncobj_merge` converted the wrong syncobj when a timestamp met a sync-file (NULL
dereference; in Mesa since the 2023 KGSL rewrite `9c808043f350`). Cemu waits on both kinds every frame. The fix
moved from `patches/linux/` to `patches/common/` (PR #2) - it is a KGSL bug, not a Linux one. Upstream Mesa MR:
dropped by the user (Mesa's contribution rules need it written and posted by the contributor).
- **A8xx driver building again** (PR #3): it failed on all three legs since 09-27. whitebelyash's
"expose VK1.3 without multiview" is now Mesa's own behaviour (dropped), and Mesa's new `quirks` struct made
fuzz put `gmem_size` in the wrong struct (both hunks re-anchored).
- **Linux zips carry the driconf defaults built in** (PR #4, `-Dxmlconfig=disabled`, from Max's WinNative
Drivers): before, they read `/usr/share/drirc.d` from the rootfs, so vkd3d/DXVK and per-game workarounds
(RDR2, DOOM Eternal, Spider-Man, ...) were whatever Mesa the rootfs ships. Verification now fails any zip
that reads drirc from disk.
- **Adreno 840v2 chip id `0x44050A21`** (PR #1, felipGonzalez; POCO F9 Pro) and **Max's three A8XX hang fixes**
(PR #5: cube-map direction sanitize, bindless invalidate through the A8XX registers - re-targeted because
his mesh-shader patch is not carried - and a KGSL VBO alias for command streams), all A8XX-gated.
- **Device proof - Samsung Galaxy Z Fold 8** (SM-F976U, SM8850, KGSL `Adreno840v2`, Android 17, DroidDeck
0.1.7, rootfs r9): r2 A8xx-Linux imported as the desktop driver ran Cemu Super Mario 3D World at ~36 fps on
Vulkan with sound, empty crash buffer; r3/r4 then "works, no issues" (user). The Fold's GPU matches Mesa's
existing A840 entry, so it did not need the 840v2 id.
- **Backlog:** DroidDeck setup should install the newest Linux driver itself; hand-started Turnip releases
should update `mesa_hash.txt`; Max's mesh-shader/wave32 patches (DX12 Ultimate) not carried.
## 2026-09-25 - main `8cdedbe`: melonDS out of the box, touch in Big Picture, log privacy, Decky
State: **main = `8cdedbe`** (PR #22 merge). Device-tested on the AYANEO Pocket FIT (repacked test builds)
@@ -11,7 +11,7 @@ import sys
HOME = os.environ.get("HOME", "/root")
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HOME, ".local/share/Steam")
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd", "SD Games"))
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/bannerlator-sd", "SD Games"))
# The client's own tools and runtimes live in steamapps beside the games; they are not titles.
NOT_GAMES = {228980, 1493710, 3127680, 4183110, 4427310, 4185400}
APPS_DIR = os.path.join(HOME, ".local/share/applications")
@@ -79,7 +79,7 @@ block=$(printf '%s\n' "$pairs" | awk -F'\t' -v now="$(date +%s)" '
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg; do
/mnt/bannerlator-sd/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] || continue
seeded=$(dirname "$reg")/.bannerlator-redists
[ "$(cat "$seeded" 2>/dev/null)" = "$stamp" ] && continue
@@ -140,16 +140,7 @@ if [ -z "${BL_INSIDE:-}" ]; then
fi
width=${BL_WIDTH:-1280}
height=${BL_HEIGHT:-720}
nested=$width
if [ "$mode" = steam ] && [ "${BL_GAMESCOPE_STRETCH_16X9:-0}" = 1 ]; then
wide=$(( (height * 16 + 4) / 9 / 2 * 2 ))
if [ "$wide" -gt "$width" ]; then
nested=$wide
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
fi
fi
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
[ "$nested" != "$width" ] && args+=(-S stretch)
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
# -r is what gamescope advertises as the refresh rate, and what a game reads as the display's.
# Left unset it defaults to 60, so a 120 Hz panel offers only 60 Hz in game settings. The FPS
# limiter wins when it is on (it is a deliberate cap); otherwise use the panel's own rate.
@@ -159,11 +150,6 @@ if [ -z "${BL_INSIDE:-}" ]; then
args+=(-r "$BL_REFRESH")
fi
[ "$mode" = steam ] && args+=(-e)
# Touch passes through to the client as touch until the client says otherwise, as SteamOS's
# gamescope-session starts it (TOUCH_MODE=4). The client sets the mode itself (STEAM_TOUCH_CLICK_MODE)
# only once it has a controller; until then gamescope's own default made a finger a left-click
# mouse, so the Steam interface took taps but would not scroll on a phone with no pad attached.
[ "$mode" = steam ] && args+=(--default-touch-mode 4)
# A game that resizes its own window when it loses focus (the Steam menu opening over it) comes
# back smaller, and gamescope draws a window that is not flagged fullscreen at its own size in
# the top-left corner. Forcing every window to the output's size keeps it filling the screen.
@@ -248,7 +234,7 @@ case $mode in
bannerlator-steam-install || exit $?
step "Steam client ready"
steam_root=$XDG_DATA_HOME/Steam
# Register the card library (bound at /mnt/droiddeck-sd) with the client - internal storage is
# Register the card library (bound at /mnt/bannerlator-sd) with the client - internal storage is
# its main library already - and the ARM64 Proton that lets it launch the Windows ones.
# A request left in ~/.bl-proton-extra installs a third-party Proton before the client starts,
# so it is in the Compatibility dropdown the first time the user looks. One per line, each the
@@ -445,37 +431,6 @@ case $mode in
prev=$app
done
) &
# Evidence for touch reports: the touch mode the client asks gamescope for (STEAM_TOUCH_CLICK_MODE,
# set once it has a controller, per focused app) and which app has focus, logged as they change.
# A finger that clicks but won't scroll, or touch that stops once a pad is used, shows here as
# the mode in force at that moment. 4 is touch passed through, 1 a left-click mouse.
[ -z "${BL_DESKTOP:-}" ] && (
# What follows "=" in an xprop line, or $2 for a property that is missing or has no value
# yet ("NAME(CARDINAL) =", which read leaves with nothing after the "=").
xprop_value() {
case $1 in *'not found'*|*=) echo "$2"; return ;; esac
local v=${1#*=}
v=${v# }
echo "${v:-$2}"
}
tmode= app=
xprop -spy -root STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP 2>/dev/null | while read -r line; do
case $line in
STEAM_TOUCH_CLICK_MODE*)
v=$(xprop_value "$line" unset)
[ "$v" = "$tmode" ] && continue
tmode=$v
echo "== touch mode: $tmode (focused app ${app:-?}) at $(date +%T)"
;;
GAMESCOPE_FOCUSED_APP*)
v=$(xprop_value "$line" none)
[ "$v" = "$app" ] && continue
app=$v
echo "== focused app: $app (touch mode ${tmode:-unset}) at $(date +%T)"
;;
esac
done
) &
# The library beat. Both helpers are whole programs under proot (the compat one a python
# start and a parse of the client's config), and nearly every beat has nothing new for them.
# The seeder marks Proton's prefix template as well as the prefixes, so a new prefix is born
@@ -491,7 +446,7 @@ case $mode in
local d
[ -e "$compat_stamp" ] && [ "$((beat % 12))" -ne 0 ] || return 0
for d in "$steam_root/steamapps" "$steam_root/steamapps/common" "$steam_root/config" \
"$steam_root/compatibilitytools.d" /mnt/droiddeck-sd/steamapps; do
"$steam_root/compatibilitytools.d" /mnt/bannerlator-sd/steamapps; do
[ "$d" -nt "$compat_stamp" ] && return 0
done
return 1
@@ -13,9 +13,6 @@ import urllib.parse
import urllib.request
STATE = ".droiddeck-games.json"
WINNATIVE = ".winnative-steam/steamapps"
LIBRARY = "/mnt/droiddeck-sd"
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
BASE_ID = 76561197960265728
@@ -43,11 +40,6 @@ def edition_key(name):
return title_key(name)
def legacy_path(path):
path = str(path)
return LEGACY_LIBRARY + path[len(LIBRARY):] if path == LIBRARY or path.startswith(LIBRARY + "/") else path
def source_stamp(game):
try:
exe = Path(game["exe"])
@@ -61,23 +53,19 @@ def source_stamp(game):
return None
def manifest_ids(steamapps, name):
matches = []
for manifest in Path(steamapps).glob("appmanifest_*.acf"):
try:
install = re.search(r'"installdir"\s*"([^"\\]*)"', manifest.read_text(), re.I)
if install and install[1] == name:
matches.append(int(manifest.stem.removeprefix("appmanifest_")))
except (OSError, ValueError):
pass
return matches
def identify(game):
folder = Path(game["folder"])
steamapps = folder.parent.parent
for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]:
matches = manifest_ids(library, folder.name)
if folder.parent.name == "common" and steamapps.name == "steamapps":
matches = []
for manifest in steamapps.glob("appmanifest_*.acf"):
try:
text = manifest.read_text()
install = re.search(r'"installdir"\s*"([^"\\]*)"', text, re.I)
if install and install[1] == folder.name:
matches.append(int(manifest.stem.removeprefix("appmanifest_")))
except (OSError, ValueError):
pass
if matches:
return matches[0] if len(matches) == 1 else None
ids = set()
@@ -156,27 +144,6 @@ def game_running():
return False
def downloads_idle(steam_root):
try:
return not any(Path(steam_root, "steamapps/downloading").iterdir())
except OSError:
return True
def request_restart(steam_root):
"""The client reads manifests and shortcuts only at start, so an import needs one restart;
the session's loop runs the importer between the exit and the next start."""
Path(os.environ.get("HOME", "/root"), ".bl-restart-once").touch()
subprocess.run([str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
def unimported(steam_root, snapshot, candidates):
routes = read_json(Path(steam_root) / "userdata" / snapshot["account"] / "config/.droiddeck-routes.json", {})
routed = set(routes.values()) if isinstance(routes, dict) else set()
return sorted({appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True} - routed)
def watch(steam_root, listing):
games = read_json(listing, [])
if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
@@ -191,7 +158,6 @@ def watch(steam_root, listing):
# beat (a client that is not logged on fails it for as long as it stays that way), and none
# starts while a game is running: the answer can wait, the game's cores cannot.
probed, next_probe, failures = None, 0, 0
pending, requested = [], []
while True:
now = time.monotonic()
for game in games:
@@ -229,7 +195,6 @@ def watch(steam_root, listing):
snapshot["candidates"] = candidates
snapshot["sources"] = sources
save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot)
pending = unimported(steam_root, snapshot, candidates)
status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values()))
except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error:
status = "ownership check unavailable: " + str(error)
@@ -237,51 +202,12 @@ def watch(steam_root, listing):
next_probe = now + min(300, 30 * 2 ** failures)
elif candidates:
status = last_status
if pending and pending != requested and not game_running() and downloads_idle(steam_root):
requested = pending
print("bannerlator-steam-games: restarting the client once to import %s" % pending, flush=True)
try:
request_restart(steam_root)
except (OSError, subprocess.TimeoutExpired) as error:
print("bannerlator-steam-games: restart unavailable: %s" % error, flush=True)
if status != last_status:
print("bannerlator-steam-games: " + status, flush=True)
last_status = status
time.sleep(30)
def installed_build(folder, appid, installdir):
"""The build another Steam client recorded for these files, so Steam updates from it
instead of verifying every file."""
try:
text = (folder.parent / WINNATIVE / f"appmanifest_{appid}.acf").read_text()
install = re.search(r'("installdir"\s*")([^"\\]*)(")', text, re.I)
flags = re.search(r'"StateFlags"\s*"(\d+)"', text)
if (install and install[2] == folder.name and flags and flags[1] == "4"
and re.search(rf'"appid"\s*"{appid}"', text) and '"InstalledDepots"' in text):
return text[:install.start(2)] + installdir + text[install.end(2):]
except OSError:
pass
if not (folder / ".download_complete").is_file():
return None
try:
ids = json.loads((folder / ".DepotDownloader/depot.config").read_text())["installedManifestIDs"]
depots = sorted((int(depot), int(gid)) for depot, gid in ids.items())
except (OSError, ValueError, KeyError, TypeError, AttributeError):
return None
if not depots or not all(0 < depot < 0x80000000 and 0 < gid < 0x7FFFFFFFFFFFFFFF for depot, gid in depots):
return None
return "".join(f' "{depot}"\n {{\n "manifest" "{gid}"\n }}\n' for depot, gid in depots)
def update_not_started(text, steamapps, appid, installdir):
fields = dict(re.findall(r'^\s*"(\w+)"\s*"([^"]*)"', text, re.M))
return (fields.get("installdir") == installdir and fields.get("buildid", "0") == "0"
and fields.get("BytesDownloaded", "0") == "0" and fields.get("BytesStaged", "0") == "0"
and re.search(r'"InstalledDepots"\s*\{\s*\}', text) is not None
and not (steamapps / "downloading" / str(appid)).exists())
def seed_install(steam_root, game, appid):
steamapps = Path(steam_root) / "steamapps"
common = steamapps / "common"
@@ -289,30 +215,16 @@ def seed_install(steam_root, game, appid):
target = common / name
source = Path(game["folder"])
title = game["name"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
minimal = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n'
content = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n'
+ f' "StateFlags" "4"\n "installdir" "{name}"\n' + '}\n')
legacy = minimal.replace(' "Universe" "1"\n', '')
build = installed_build(source, appid, name)
if build is None:
content = minimal
elif build.lstrip().startswith('"AppState"'):
content = build
else:
content = minimal[:-2] + ' "InstalledDepots"\n {\n' + build + ' }\n}\n'
legacy = content.replace(' "Universe" "1"\n', '')
manifest = steamapps / f"appmanifest_{appid}.acf"
if target.is_symlink() and os.readlink(target) != str(source) and os.readlink(target) == legacy_path(source):
relink = target.with_name(name + ".droiddeck")
relink.unlink(missing_ok=True)
relink.symlink_to(source, target_is_directory=True)
os.replace(relink, target)
for root in [Path(steam_root), Path(LIBRARY)]:
for root in [Path(steam_root), Path("/mnt/bannerlator-sd")]:
existing = root / "steamapps" / manifest.name
if existing.is_file():
if (existing == manifest and source.is_dir() and target.is_symlink()
and os.readlink(target) == str(source)
and existing.read_text() != content
and (existing.read_text() in (minimal, legacy, legacy.replace('"StateFlags" "4"', '"StateFlags" "2"'))
or (build is not None and update_not_started(existing.read_text(), steamapps, appid, name)))):
and existing.read_text() in (legacy, legacy.replace('"StateFlags" "4"', '"StateFlags" "2"'))):
temp = manifest.with_suffix(".droiddeck")
temp.write_text(content)
os.replace(temp, manifest)
@@ -344,13 +256,11 @@ def route(steam_root, acct, games):
owned, candidates, sources = {}, {}, {}
shortcuts, routes = [], {}
for game in games:
folder = game.get("folder", "")
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
appid = candidates.get(game.get("folder"))
stamp = source_stamp(game)
recorded = sources.get(folder, sources.get(legacy_path(folder)))
confirmed = (isinstance(appid, int) and 0 < appid < 0x80000000
and owned.get(str(appid)) is True and stamp is not None
and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:]))
and sources.get(game.get("folder")) == stamp)
if confirmed:
try:
if seed_install(steam_root, game, appid):
@@ -1,5 +1,5 @@
#!/usr/bin/python3
# Registers the card the app installs to (bound at /mnt/droiddeck-sd) as a library folder of the
# Registers the card the app installs to (bound at /mnt/bannerlator-sd) as a library folder of the
# native Steam client, so they show as installed there instead of being downloaded a second time.
#
# bannerlator-steam-library <steam root>
@@ -14,7 +14,7 @@ import sys
# The app binds the storage the user chose (Steam cog -> Game storage) at this path and names it
# in BL_LIBRARY_LABEL; nothing bound = internal only, and the entry is removed so the client does
# not keep offering a place that is not there.
LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),)
LIBRARIES = (("/mnt/bannerlator-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),)
# The client calls its own library "Local Drive (/)", which says nothing about where that is.
# It is the phone's internal storage, so say so.
MAIN_LABEL = "Internal Storage"
@@ -66,26 +66,6 @@ def register(steam_root, library, label):
RETIRED = ("/mnt/bannerlator",)
RENAMED = (("/mnt/bannerlator-sd", "/mnt/droiddeck-sd"),)
def rename(steam_root, old, new):
"""Moves a library registered under an earlier mount point to the current one, keeping its
entry (content id, app sizes) rather than registering it anew."""
path = os.path.join(steam_root, "steamapps", "libraryfolders.vdf")
if not os.path.isfile(path):
return
with open(path, encoding="utf-8", errors="replace") as f:
text = f.read()
old_path = re.compile(r'("path"\s+")%s(")' % re.escape(old))
if not old_path.search(text):
return
if re.search(r'"path"\s+"%s"' % re.escape(new), text):
forget(steam_root, old)
return
with open(path, "w", encoding="utf-8") as f:
f.write(old_path.sub(lambda m: m.group(1) + new + m.group(2), text))
print("bannerlator-steam-library: moved %s to %s" % (old, new))
def forget(steam_root, library):
@@ -172,8 +152,6 @@ def main():
steam_root = sys.argv[1]
for library in RETIRED:
forget(steam_root, library)
for old, new in RENAMED:
rename(steam_root, old, new)
relabel(steam_root, steam_root, MAIN_LABEL)
for library, label in LIBRARIES:
if os.path.isdir(os.path.join(library, "steamapps")):
@@ -97,7 +97,7 @@ def write(obj):
return bytes(out)
def shortcut(game, launch_options=""):
def shortcut(game):
appid = int(game["appid"]) & 0xFFFFFFFF
return {
"appid": struct.unpack("<i", struct.pack("<I", appid))[0],
@@ -106,7 +106,7 @@ def shortcut(game, launch_options=""):
"StartDir": '"%s"' % game["dir"],
"icon": (game.get("art") or {}).get("icon", "") or "",
"ShortcutPath": "",
"LaunchOptions": launch_options,
"LaunchOptions": "",
"IsHidden": 0,
"AllowDesktopConfig": 1,
"AllowOverlay": 1,
@@ -208,22 +208,8 @@ def main():
routing = importlib.util.module_from_spec(spec)
loader.exec_module(routing)
games, routes = routing.route(steam_root, acct, games)
# Steam saves Big Picture's per-shortcut launch options in shortcuts.vdf. Keep them when
# refreshing our entries, keyed by the appid that stays stable across session starts.
managed = {
v.get("appid"): v for v in existing.values()
if isinstance(v, dict) and TAG in (v.get("tags") or {}).values()
}
kept = [v for v in existing.values() if isinstance(v, dict) and TAG not in (v.get("tags") or {}).values()]
ours = []
for game in games:
if not game.get("exe") or not game.get("name"):
continue
entry = shortcut(game)
previous = managed.get(entry["appid"])
if previous and isinstance(previous.get("LaunchOptions"), str):
entry["LaunchOptions"] = previous["LaunchOptions"]
ours.append(entry)
ours = [shortcut(g) for g in games if g.get("exe") and g.get("name")]
entries = {str(i): v for i, v in enumerate(kept + ours)}
tmp = path + ".bannerlator"
with open(tmp, "wb") as f:
-58
View File
@@ -1,58 +0,0 @@
/*
* Adreno revisions the runtime's Turnip does not know, reported as the revision it does.
*
* Retail SM8850 phones report their A840 as chip_id 0x44050A21 (KGSL gpu_model "Adreno840v2").
* Mesa only lists 0x44050A31, so the runtime's glibc Turnip refuses the device outright
* ("device (chip_id = 44050A21, gpu_id = 6860) is unsupported") and gamescope exits before Steam
* starts. Banners-Turnip fixes its own builds by registering the v2 id on the same A840 GPU info
* (patches/a840v2.py); answering KGSL's device-info query with the known id has the same effect
* on any Turnip in the session, including the one the runtime was built with. A driver that
* already knows the v2 id resolves the rewritten one to the same entry.
*
* Only the KGSL device-info property is touched. Its layout is the kernel's uapi (msm_kgsl.h).
*/
#define _GNU_SOURCE 1
#include <stddef.h>
#include <sys/ioctl.h>
struct kgsl_devinfo {
unsigned int device_id;
unsigned int chip_id;
unsigned int mmu_enabled;
unsigned long gmem_gpubaseaddr;
unsigned int gpu_id;
size_t gmem_sizebytes;
};
struct kgsl_device_getproperty {
unsigned int type;
void *value;
size_t sizebytes;
};
#define KGSL_IOC_TYPE 0x09
#define IOCTL_KGSL_DEVICE_GETPROPERTY _IOWR(KGSL_IOC_TYPE, 0x2, struct kgsl_device_getproperty)
#define KGSL_PROP_DEVICE_INFO 0x1
static const struct {
unsigned int reported;
unsigned int known;
} CHIP_IDS[] = {
{0x44050A21, 0x44050A31}, /* Adreno 840v2 -> Adreno 840 */
};
void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc) {
if (rc != 0 || request != IOCTL_KGSL_DEVICE_GETPROPERTY || arg == NULL) return;
struct kgsl_device_getproperty *prop = arg;
if (prop->type != KGSL_PROP_DEVICE_INFO || prop->value == NULL
|| prop->sizebytes < sizeof(struct kgsl_devinfo)) {
return;
}
struct kgsl_devinfo *info = prop->value;
for (size_t i = 0; i < sizeof(CHIP_IDS) / sizeof(CHIP_IDS[0]); i++) {
if (info->chip_id == CHIP_IDS[i].reported) {
info->chip_id = CHIP_IDS[i].known;
return;
}
}
}
+2 -3
View File
@@ -349,7 +349,6 @@ static int is_link_query(unsigned long request) {
|| request == SIOCGIFBRDADDR;
}
void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc); /* kgslid.c */
int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, int *rc) __attribute__((visibility("hidden")));
@@ -365,8 +364,8 @@ int ioctl(int fd, unsigned long request, ...) {
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
int rc;
if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = real(fd, request, arg);
bl_kgsl_chip_id_fixup(request, arg, rc);
if (bl_kgsl_poll(real, fd, request, arg, &rc)) return rc;
rc = real(fd, request, arg);
if (arg == NULL || !is_link_query(request)) return rc;
int saved = errno;
if (answer_ifreq(request, (struct ifreq *) arg, rc)) return 0;
-419
View File
@@ -1,419 +0,0 @@
#!/usr/bin/env python3
"""Build and publish the one-file update catalog consumed by DroidDeck.
The catalog is derived from GitHub releases, but the Android app never has to infer
channels, parse release notes, dereference tags, or spend unauthenticated API quota.
"""
from __future__ import annotations
import argparse
import base64
import datetime as dt
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
API = "https://api.github.com"
SHA256 = re.compile(r"^[0-9a-f]{64}$")
PR_TAG = re.compile(r"^pr-([1-9][0-9]*)$")
MAIN_TAG = re.compile(r"^main-([0-9a-f]{7,40})$")
class ApiError(RuntimeError):
def __init__(self, status: int, message: str):
super().__init__(f"GitHub API {status}: {message}")
self.status = status
class GitHub:
def __init__(self, token: str):
self.token = token
def request(self, method: str, path: str, body=None):
data = None
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "DroidDeck-update-catalog",
"X-GitHub-Api-Version": "2022-11-28",
}
if self.token:
headers["Authorization"] = f"Bearer {self.token}"
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
req = urllib.request.Request(API + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=30) as response:
raw = response.read()
return json.loads(raw) if raw else None
except urllib.error.HTTPError as e:
raw = e.read().decode(errors="replace")
raise ApiError(e.code, raw[:500]) from e
def get(self, path: str):
return self.request("GET", path)
def put(self, path: str, body):
return self.request("PUT", path, body)
def q(value: str) -> str:
return urllib.parse.quote(value, safe="")
def repo_file(gh: GitHub, repo: str, path: str, ref: str) -> str:
obj = gh.get(f"/repos/{repo}/contents/{q(path)}?ref={q(ref)}")
if obj.get("encoding") != "base64":
raise RuntimeError(f"{repo}:{ref}:{path} was not base64 content")
return base64.b64decode(obj["content"]).decode()
def resolve_tag(gh: GitHub, repo: str, tag: str) -> str:
obj = gh.get(f"/repos/{repo}/git/ref/tags/{q(tag)}")["object"]
while obj["type"] == "tag":
obj = gh.get(f"/repos/{repo}/git/tags/{q(obj['sha'])}")["object"]
if obj["type"] != "commit":
raise RuntimeError(f"{repo} tag {tag} points to {obj['type']}, not a commit")
return obj["sha"]
def parse_gradle(text: str) -> tuple[int, str | None]:
code = re.search(r"(?m)^\s*versionCode\s+(\d+)\s*$", text)
name = re.search(r'(?m)^\s*versionName\s+"([^"]+)"\s*$', text)
if not code:
raise RuntimeError("app/build.gradle has no numeric versionCode")
return int(code.group(1)), name.group(1) if name else None
def parse_variants(text: str) -> list[tuple[str, str]]:
out = []
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
fields = line.split()
if len(fields) < 3:
raise RuntimeError(f"bad variants.txt row: {raw!r}")
out.append((fields[1], "" if fields[2] == "-" else fields[2]))
if not out:
raise RuntimeError("variants.txt has no packages")
return out
def published_millis(release: dict, prefer_updated: bool = False) -> int:
value = (
release.get("updated_at") if prefer_updated else None
) or release.get("published_at") or release.get("created_at")
if not value:
return 0
return int(dt.datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() * 1000)
def paragraphs(markdown: str) -> list[str]:
return [p.strip() for p in re.split(r"\n\s*\n", markdown.replace("\r", "")) if p.strip()]
def plain(markdown: str) -> str:
text = re.sub(r"!\[[^]]*]\([^)]*\)", "", markdown)
text = re.sub(r"\[([^]]*)]\([^)]*\)", r"\1", text)
text = re.sub(r"[*_`]{1,3}", "", text)
return re.sub(r"\s+", " ", text).strip()
def prose_lines(markdown: str) -> str:
lines = []
for raw in markdown.splitlines():
match = re.match(r"^\s*[-*]\s+", raw)
value = ("• " + plain(raw[match.end():])) if match else plain(raw)
if value:
lines.append(value)
return "\n".join(lines)
def ci_description(release: dict) -> tuple[str, str]:
ps = paragraphs(release.get("body") or "")
head = ps[0] if ps else ""
title = ""
if "): " in head:
title = head.split("): ", 1)[1]
title = re.sub(r" \(merged[^)]*\)$", "", title)
title = plain(title or head or release.get("name") or release["tag_name"])
summary = ps[1] if len(ps) > 1 else ""
if summary.startswith("Signed build") or summary.startswith("Source:"):
summary = ""
return title, prose_lines(summary)
def stable_description(release: dict) -> tuple[str, str]:
name = release.get("name") or release["tag_name"]
summary = ""
for p in paragraphs(release.get("body") or ""):
if not (p.startswith("#") or p.startswith("![") or p.startswith("<")):
summary = prose_lines(p)
break
return name, summary
def source_meta(source: GitHub, repo: str, ref: str):
gradle = repo_file(source, repo, "app/build.gradle", ref)
code, version = parse_gradle(gradle)
variants = parse_variants(repo_file(source, repo, "tools/release/variants.txt", ref))
signer = repo_file(source, repo, "keystore/release-signer.sha256", ref).strip().lower()
if not SHA256.fullmatch(signer):
raise RuntimeError(f"{repo}:{ref} has an invalid release signer digest")
return code, version, variants, signer
def asset_for_suffix(assets: list[dict], suffix: str, all_suffixes: list[str]):
others = [s for s in all_suffixes if s and s != suffix]
for asset in assets:
name = asset.get("name", "")
if not name.endswith(f"{suffix}.apk"):
continue
if any(name.endswith(f"{other}.apk") for other in others):
continue
digest = (asset.get("digest") or "").lower()
if not digest.startswith("sha256:") or not SHA256.fullmatch(digest[7:]):
continue
return {
"name": name,
"url": asset["browser_download_url"],
"size": int(asset.get("size") or 0),
"sha256": digest[7:],
}
return None
def release_entry(
release: dict,
commit: str,
pr: int,
version: str | None,
version_code: int,
variants: list[tuple[str, str]],
signer: str,
title: str,
summary: str,
prefer_updated: bool = False,
):
suffixes = [suffix for _, suffix in variants]
apks = {}
for package, suffix in variants:
asset = asset_for_suffix(release.get("assets") or [], suffix, suffixes)
if not asset:
continue
asset.update(
{
"packageName": package,
"versionCode": version_code,
"signerSha256": signer,
}
)
apks[package] = asset
return {
"tag": release["tag_name"],
"title": title,
"summary": summary,
"commit": commit,
"pr": pr,
"version": version,
"versionCode": version_code,
"publishedAt": published_millis(release, prefer_updated),
"url": release.get("html_url") or "",
"apks": apks,
}
def release_body_value(body: str, key: str):
match = re.search(rf"(?mi)^\s*{re.escape(key)}:\s*`?([^\s`]+)", body or "")
return match.group(1) if match else None
def main_commit(release: dict) -> str | None:
body = release.get("body") or ""
explicit = release_body_value(body, "Commit")
if explicit and re.fullmatch(r"[0-9a-f]{7,40}", explicit):
return explicit
match = re.search(r"/commit/([0-9a-f]{40})", body)
return match.group(1) if match else None
def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str) -> dict:
try:
stable_release = source.get(f"/repos/{source_repo}/releases/latest")
except ApiError as e:
if e.status != 404:
raise
stable_release = None
stable = None
if stable_release:
stable_commit = resolve_tag(source, source_repo, stable_release["tag_name"])
code, version_name, variants, signer = source_meta(source, source_repo, stable_commit)
title, summary = stable_description(stable_release)
stable = release_entry(
stable_release,
stable_commit,
0,
version_name or stable_release["tag_name"].removeprefix("v"),
code,
variants,
signer,
title,
summary,
)
releases = ci.get(f"/repos/{ci_repo}/releases?per_page=100")
previews = []
tests = []
for release in releases:
if release.get("draft"):
continue
tag = release.get("tag_name") or ""
main_match = MAIN_TAG.fullmatch(tag)
if main_match:
commit = main_commit(release)
if not commit:
continue
try:
code, _, variants, signer = source_meta(source, source_repo, commit)
except ApiError:
continue
title, summary = ci_description(release)
previews.append(
release_entry(release, commit, 0, None, code, variants, signer, title, summary)
)
continue
pr_match = PR_TAG.fullmatch(tag)
if not pr_match:
continue
pr = int(pr_match.group(1))
body = release.get("body") or ""
if f"github.com/{source_repo}/pull/{pr}" not in body:
continue
try:
pull = source.get(f"/repos/{source_repo}/pulls/{pr}")
except ApiError:
continue
if pull.get("state") != "open" or pull.get("draft") or pull.get("base", {}).get("ref") != "main":
continue
commit = release_body_value(body, "Commit")
if not commit or not re.fullmatch(r"[0-9a-f]{7,40}", commit):
continue
base_ref = release_body_value(body, "Base") or pull["base"]["sha"]
try:
base_code, _, variants, signer = source_meta(source, source_repo, base_ref)
except ApiError:
continue
version_code_text = release_body_value(body, "VersionCode")
if version_code_text and version_code_text.isdigit():
version_code = int(version_code_text)
else:
# Legacy test releases did not record it. If the PR did not change build.gradle,
# the base value is exact; otherwise use the PR head's value.
version_code = base_code
try:
changed = source.get(f"/repos/{source_repo}/pulls/{pr}/files?per_page=100")
if any(item.get("filename") == "app/build.gradle" for item in changed):
head_repo = pull["head"]["repo"]["full_name"]
version_code = parse_gradle(repo_file(source, head_repo, "app/build.gradle", pull["head"]["sha"]))[0]
except (ApiError, KeyError):
pass
title, summary = ci_description(release)
tests.append(
release_entry(
release,
commit,
pr,
None,
version_code,
variants,
signer,
title,
summary,
prefer_updated=True,
)
)
previews.sort(key=lambda r: r["publishedAt"], reverse=True)
tests.sort(key=lambda r: r["publishedAt"], reverse=True)
return {
"schema": 1,
"sourceRepo": source_repo,
"ciRepo": ci_repo,
"generatedAt": int(time.time() * 1000),
"stable": stable,
"preview": previews[0] if previews else None,
"tests": tests,
}
def current_file(ci: GitHub, repo: str, path: str):
try:
return ci.get(f"/repos/{repo}/contents/{q(path)}?ref=main")
except ApiError as e:
if e.status == 404:
return None
raise
def publish_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, path: str):
for attempt in range(4):
catalog = build_catalog(source, ci, source_repo, ci_repo)
content = (json.dumps(catalog, indent=2, sort_keys=False) + "\n").encode()
old = current_file(ci, ci_repo, path)
body = {
"message": "ci: refresh DroidDeck update catalog",
"content": base64.b64encode(content).decode(),
"branch": "main",
}
if old:
body["sha"] = old["sha"]
try:
old_bytes = base64.b64decode(old["content"])
old_json = json.loads(old_bytes)
old_json.pop("generatedAt", None)
new_json = dict(catalog)
new_json.pop("generatedAt", None)
if old_json == new_json:
print("catalog contents are already current")
return catalog
except Exception:
pass
try:
ci.put(f"/repos/{ci_repo}/contents/{q(path)}", body)
print(f"published https://raw.githubusercontent.com/{ci_repo}/main/{path}")
return catalog
except ApiError as e:
if e.status not in (409, 422) or attempt == 3:
raise
time.sleep(1 + attempt)
raise RuntimeError("catalog publish retry loop exhausted")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--source-repo", default="Droid-Deck/DroidDeck")
parser.add_argument("--ci-repo", default="Droid-Deck/DroidDeck-CI")
parser.add_argument("--path", default="catalog.json")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
source = GitHub(os.environ.get("SOURCE_GITHUB_TOKEN", ""))
ci = GitHub(os.environ.get("CI_GITHUB_TOKEN", os.environ.get("SOURCE_GITHUB_TOKEN", "")))
if args.dry_run:
print(json.dumps(build_catalog(source, ci, args.source_repo, args.ci_repo), indent=2))
else:
if not os.environ.get("CI_GITHUB_TOKEN"):
raise SystemExit("CI_GITHUB_TOKEN is required to publish")
publish_catalog(source, ci, args.source_repo, args.ci_repo, args.path)
if __name__ == "__main__":
main()
-146
View File
@@ -20,7 +20,6 @@ def load(name):
imports = load('bannerlator-steam-games')
shortcuts = load('bannerlator-steam-shortcuts')
library = load('bannerlator-steam-library')
class ImportsTest(unittest.TestCase):
@@ -74,7 +73,6 @@ class ImportsTest(unittest.TestCase):
from unittest.mock import Mock
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
with patch.object(imports, 'identify', side_effect=[None, 42]) as identify, \
patch.object(imports, 'request_restart'), \
patch.object(imports.time, 'monotonic', side_effect=[0, 301]), \
patch.object(imports.time, 'sleep', side_effect=[None, RuntimeError('stop')]), \
patch.object(imports.subprocess, 'run', return_value=result), \
@@ -85,35 +83,6 @@ class ImportsTest(unittest.TestCase):
snapshot = imports.read_json(self.acct / 'config' / imports.STATE, {})
self.assertTrue(snapshot['owned']['42'])
def run_watch(self, beats, routes=None, busy=False):
listing = self.root / 'games.json'
listing.write_text(json.dumps([self.game]))
if routes is not None:
imports.save_json(self.acct / 'config/.droiddeck-routes.json', routes)
if busy:
(self.steam / 'steamapps/downloading/7').mkdir(parents=True)
from unittest.mock import Mock
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
with patch.object(imports, 'identify', return_value=42), \
patch.object(imports, 'game_running', return_value=False), \
patch.object(imports, 'request_restart') as restart, \
patch.object(imports.time, 'monotonic', side_effect=list(range(0, 30 * beats, 30))), \
patch.object(imports.time, 'sleep', side_effect=[None] * (beats - 1) + [RuntimeError('stop')]), \
patch.object(imports.subprocess, 'run', return_value=result), \
patch('builtins.print'):
with self.assertRaisesRegex(RuntimeError, 'stop'):
imports.watch(self.steam, listing)
return restart
def test_newly_owned_game_restarts_the_client_once(self):
self.assertEqual(1, self.run_watch(3).call_count)
def test_imported_game_does_not_restart_the_client(self):
self.assertEqual(0, self.run_watch(2, routes={'1': 42}).call_count)
def test_restart_waits_for_downloads(self):
self.assertEqual(0, self.run_watch(2, busy=True).call_count)
def test_unowned_unknown_and_different_account_stay_shortcuts(self):
for owned, account in [(False, '123'), (True, '456')]:
self.snapshot(owned, account)
@@ -122,93 +91,6 @@ class ImportsTest(unittest.TestCase):
self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
self.assertFalse((self.steam / 'steamapps').exists())
def winnative_manifest(self, flags='4', installdir='Example'):
path = self.folder.parent / imports.WINNATIVE / 'appmanifest_42.acf'
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('"AppState"\n{\n\t"appid"\t\t"42"\n\t"StateFlags"\t\t"%s"\n\t"installdir"\t\t"%s"\n'
'\t"buildid"\t\t"7"\n\t"InstalledDepots"\n\t{\n\t\t"43"\n\t\t{\n\t\t\t"manifest"\t\t"99"\n'
'\t\t\t"size"\t\t"4"\n\t\t}\n\t}\n}\n' % (flags, installdir))
return path
def test_winnative_manifest_carries_installed_build(self):
source = self.winnative_manifest()
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
text = (self.steam / 'steamapps/appmanifest_42.acf').read_text()
self.assertEqual(source.read_text().replace('"Example"', '"DroidDeck-42"'), text)
def test_winnative_manifest_identifies_folder(self):
self.winnative_manifest()
with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError):
self.assertEqual(42, imports.identify(self.game))
def test_incomplete_winnative_manifest_is_ignored(self):
for flags, installdir in [('1026', 'Example'), ('4', 'Other')]:
self.winnative_manifest(flags, installdir)
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
def test_depot_config_records_installed_depots(self):
config = self.folder / '.DepotDownloader/depot.config'
config.parent.mkdir()
config.write_text(json.dumps({'installedManifestIDs': {'43': 99}}))
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
(self.folder / '.download_complete').touch()
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
text = (self.steam / 'steamapps/appmanifest_42.acf').read_text()
self.assertIn('"InstalledDepots"\n {\n "43"\n {\n "manifest" "99"', text)
self.assertTrue(text.endswith(' }\n}\n'))
config.write_text(json.dumps({'installedManifestIDs': {'43': 0x7FFFFFFFFFFFFFFF}}))
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
def test_bare_import_manifest_gains_installed_build(self):
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
self.winnative_manifest()
imports.route(self.steam, self.acct, [self.game])
self.assertIn('"buildid"\t\t"7"', (self.steam / 'steamapps/appmanifest_42.acf').read_text())
def steam_fresh_install(self, downloaded='0'):
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
path = self.steam / 'steamapps/appmanifest_42.acf'
path.write_text('"AppState"\n{\n\t"appid"\t\t"42"\n\t"StateFlags"\t\t"6"\n\t"installdir"\t\t"DroidDeck-42"\n'
'\t"buildid"\t\t"0"\n\t"BytesDownloaded"\t\t"%s"\n\t"BytesStaged"\t\t"0"\n'
'\t"InstalledDepots"\n\t{\n\t}\n}\n' % downloaded)
self.winnative_manifest()
return path
def test_queued_fresh_install_takes_installed_build(self):
path = self.steam_fresh_install()
imports.route(self.steam, self.acct, [self.game])
self.assertIn('"buildid"\t\t"7"', path.read_text())
def test_started_fresh_install_is_left_to_steam(self):
for downloaded, staging in [('5', False), ('0', True)]:
path = self.steam_fresh_install(downloaded)
if staging:
(self.steam / 'steamapps/downloading/42').mkdir(parents=True)
before = path.read_text()
imports.route(self.steam, self.acct, [self.game])
self.assertEqual(before, path.read_text())
def test_links_and_snapshots_from_the_old_mount_carry_over(self):
old = self.root / 'old-mount'
with patch.object(imports, 'LIBRARY', str(self.root / 'Games')), \
patch.object(imports, 'LEGACY_LIBRARY', str(old)):
legacy_game = dict(self.game, folder=str(old / 'Example'), exe=str(old / 'Example/Example.exe'))
stamp = imports.source_stamp(self.game)
imports.save_json(self.acct / 'config' / imports.STATE,
dict(account='123', owned={'42': True}, candidates={legacy_game['folder']: 42},
sources={legacy_game['folder']: [stamp[0], legacy_game['exe']] + stamp[2:]}))
link = self.steam / 'steamapps/common/DroidDeck-42'
link.parent.mkdir(parents=True)
link.symlink_to(legacy_game['folder'], target_is_directory=True)
games, routes = imports.route(self.steam, self.acct, [self.game])
self.assertEqual([], games)
self.assertEqual({str(self.game['appid']): 42}, routes)
self.assertEqual(str(self.folder), imports.os.readlink(link))
def test_existing_manifest_is_never_overwritten(self):
manifest = self.steam / 'steamapps/appmanifest_42.acf'
manifest.parent.mkdir(parents=True)
@@ -306,34 +188,6 @@ class ImportsTest(unittest.TestCase):
self.assertEqual({str(self.game['appid']): 42}, json.loads((path.parent / '.droiddeck-routes.json').read_text()))
class LibraryRenameTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.steam = Path(temp.name)
self.vdf = self.steam / 'steamapps/libraryfolders.vdf'
self.vdf.parent.mkdir()
def entry(self, index, path):
return '\t"%d"\n\t{\n\t\t"path"\t\t"%s"\n\t\t"contentid"\t\t"%d"\n\t}\n' % (index, path, 7 + index)
def test_old_mount_keeps_its_entry_under_the_new_path(self):
self.vdf.write_text('"libraryfolders"\n{\n' + self.entry(0, '/root') + self.entry(1, '/mnt/bannerlator-sd') + '}\n')
with patch('builtins.print'):
library.rename(str(self.steam), '/mnt/bannerlator-sd', '/mnt/droiddeck-sd')
text = self.vdf.read_text()
self.assertIn('"path"\t\t"/mnt/droiddeck-sd"\n\t\t"contentid"\t\t"8"', text)
self.assertNotIn('bannerlator-sd', text)
def test_old_mount_is_dropped_when_new_path_is_registered(self):
self.vdf.write_text('"libraryfolders"\n{\n' + self.entry(0, '/mnt/droiddeck-sd') + self.entry(1, '/mnt/bannerlator-sd') + '}\n')
with patch('builtins.print'):
library.rename(str(self.steam), '/mnt/bannerlator-sd', '/mnt/droiddeck-sd')
text = self.vdf.read_text()
self.assertEqual(1, text.count('"path"'))
self.assertIn('/mnt/droiddeck-sd', text)
class SteamProbeTest(unittest.TestCase):
def test_probe_reads_account_and_licenses_and_releases_handles(self):
import ctypes as C
-91
View File
@@ -1,91 +0,0 @@
import unittest
from tools.release.update_catalog import (
asset_for_suffix,
ci_description,
parse_gradle,
parse_variants,
published_millis,
release_body_value,
)
class UpdateCatalogTest(unittest.TestCase):
def test_gradle_metadata(self):
code, name = parse_gradle("""android {
defaultConfig {
versionCode 12
versionName "0.3.1"
}
}
""")
self.assertEqual(12, code)
self.assertEqual("0.3.1", name)
def test_variants(self):
rows = parse_variants("""
# name package suffix
standard com.droiddeck.launcher -
pubg com.tencent.ig -pubg
""")
self.assertEqual(
[("com.droiddeck.launcher", ""), ("com.tencent.ig", "-pubg")],
rows,
)
def test_standard_asset_does_not_take_a_variant(self):
assets = [
{
"name": "DroidDeck-main-deadbee-pubg.apk",
"size": 10,
"digest": "sha256:" + "a" * 64,
"browser_download_url": "https://example/pubg",
},
{
"name": "DroidDeck-main-deadbee.apk",
"size": 11,
"digest": "sha256:" + "b" * 64,
"browser_download_url": "https://example/standard",
},
]
standard = asset_for_suffix(assets, "", ["", "-pubg"])
pubg = asset_for_suffix(assets, "-pubg", ["", "-pubg"])
self.assertEqual("DroidDeck-main-deadbee.apk", standard["name"])
self.assertEqual("DroidDeck-main-deadbee-pubg.apk", pubg["name"])
def test_ci_description(self):
title, summary = ci_description(
{
"tag_name": "main-deadbee",
"name": "main deadbee",
"body": (
"**Merged to main** - [PR #9](https://github.com/Droid-Deck/DroidDeck/pull/9): "
"fix: keep Steam alive (merged 2026-09-30)\n\n"
"Steam no longer **exits** on resume.\n\n"
"Signed build of https://example"
),
}
)
self.assertEqual("fix: keep Steam alive", title)
self.assertEqual("Steam no longer exits on resume.", summary)
def test_release_body_metadata(self):
tick = chr(96)
body = f"Commit: {tick}abcdef1234567{tick}\nBase: 1234567\nVersionCode: 42\n"
self.assertEqual("abcdef1234567", release_body_value(body, "Commit"))
self.assertEqual("1234567", release_body_value(body, "Base"))
self.assertEqual("42", release_body_value(body, "VersionCode"))
def test_republished_pr_uses_updated_time_but_other_channels_use_publish_time(self):
release = {
"published_at": "2026-09-30T10:00:00Z",
"updated_at": "2026-09-30T12:00:00Z",
}
self.assertLess(
published_millis(release),
published_millis(release, prefer_updated=True),
)
if __name__ == "__main__":
unittest.main()