mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bec08e2134 | ||
|
|
a67c5cd3b2 | ||
|
|
5771cb89a2 | ||
|
|
b15bdd5739 | ||
|
|
4dfb9a5ae9 | ||
|
|
6c25bb1cd5 | ||
|
|
7d3fe09b01 | ||
|
|
f1d5dcd505 | ||
|
|
3f6fd9b40f | ||
|
|
70d3d1f6a4 |
No files matched your search
@@ -157,7 +157,7 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -176,9 +176,6 @@ jobs:
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
@@ -211,13 +208,9 @@ jobs:
|
||||
rm mango-pkgs/pkg.tar.zst
|
||||
done
|
||||
install -m644 mango-pkgs/usr/bin/mangoapp "$M/mangoapp"
|
||||
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
|
||||
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1 libtracefs.so.1; do
|
||||
cp -L "mango-pkgs/usr/lib/$so" "$M/$so"
|
||||
done
|
||||
# Ours, not the package's: GPU memory without tracefs (tools/mangoapp/libtracefs-shim.c).
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
|
||||
-o "$M/libtracefs.so.1" tools/mangoapp/libtracefs-shim.c
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$M/libtracefs.so.1"
|
||||
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
|
||||
rm -rf mango-pkgs
|
||||
ls -l "$M"
|
||||
@@ -298,7 +291,6 @@ jobs:
|
||||
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
|
||||
done
|
||||
test -f "$D/usr/local/bin/bannerlator-session"
|
||||
test -f "$D/usr/local/bin/bannerlator-gog"
|
||||
test -f "$D/usr/local/bin/bannerlator-proton-extra"
|
||||
|
||||
- name: Cache the CMake build tree
|
||||
@@ -382,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 -->"
|
||||
@@ -396,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"
|
||||
@@ -532,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:
|
||||
@@ -595,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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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}\""
|
||||
|
||||
|
||||
@@ -118,6 +118,19 @@
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<!-- A second compositor and Linux session need their own process-global JNI state and
|
||||
runtime sockets, while the handheld's current session remains in the main process. -->
|
||||
<activity
|
||||
android:name=".ExternalSessionActivity"
|
||||
android:process=":externalDisplay"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTop"
|
||||
android:theme="@style/SessionTheme"
|
||||
android:preferMinimalPostProcessing="true"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<!--
|
||||
Owns the session - gamescope, the Steam client, audio - so it survives the activity
|
||||
going away. Without it Android demotes the process as soon as the last visible
|
||||
@@ -128,14 +141,15 @@
|
||||
android:name=".session.SessionService"
|
||||
android:exported="false"
|
||||
android:stopWithTask="false" />
|
||||
<service
|
||||
android:name=".session.ExternalSessionService"
|
||||
android:process=":externalDisplay"
|
||||
android:exported="false"
|
||||
android:stopWithTask="false" />
|
||||
<!-- Holds the process in the foreground while the Linux runtime downloads and unpacks. -->
|
||||
<service
|
||||
android:name=".runtime.RuntimeInstallService"
|
||||
android:exported="false" />
|
||||
<!-- Holds the process in the foreground while a GOG game downloads. -->
|
||||
<service
|
||||
android:name=".store.gog.GogInstallService"
|
||||
android:exported="false" />
|
||||
<service
|
||||
android:name=".core.WirelessAdbPairingService"
|
||||
android:exported="false" />
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -24,6 +24,7 @@ add_library(bannerwayland SHARED
|
||||
generated/xdg-shell-protocol.c
|
||||
generated/linux-dmabuf-v1-protocol.c
|
||||
generated/viewporter-protocol.c
|
||||
generated/single-pixel-buffer-v1-protocol.c
|
||||
generated/banner-desktop-v1-protocol.c
|
||||
generated/presentation-time-protocol.c
|
||||
generated/pointer-constraints-unstable-v1-protocol.c
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/* Protocol description for wp_single_pixel_buffer_manager_v1. */
|
||||
|
||||
#include <stddef.h>
|
||||
#include "wayland-util.h"
|
||||
|
||||
extern const struct wl_interface wl_buffer_interface;
|
||||
|
||||
static const struct wl_interface *single_pixel_buffer_types[] = {
|
||||
&wl_buffer_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message single_pixel_buffer_requests[] = {
|
||||
{ "destroy", "", NULL },
|
||||
{ "create_u32_rgba_buffer", "nuuuu", single_pixel_buffer_types },
|
||||
};
|
||||
|
||||
WL_EXPORT const struct wl_interface wp_single_pixel_buffer_manager_v1_interface = {
|
||||
"wp_single_pixel_buffer_manager_v1", 1,
|
||||
2, single_pixel_buffer_requests,
|
||||
0, NULL,
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
#ifndef SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H
|
||||
#define SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include "wayland-server.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct wp_single_pixel_buffer_manager_v1_interface {
|
||||
void (*destroy)(struct wl_client *client, struct wl_resource *resource);
|
||||
void (*create_u32_rgba_buffer)(struct wl_client *client, struct wl_resource *resource,
|
||||
uint32_t id, uint32_t red, uint32_t green,
|
||||
uint32_t blue, uint32_t alpha);
|
||||
};
|
||||
|
||||
extern const struct wl_interface wp_single_pixel_buffer_manager_v1_interface;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="single_pixel_buffer_v1">
|
||||
<copyright>
|
||||
Copyright © 2022 Simon Ser
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
</copyright>
|
||||
<description summary="single pixel buffer factory">
|
||||
Create one-pixel buffers that clients can scale with the viewporter protocol.
|
||||
</description>
|
||||
<interface name="wp_single_pixel_buffer_manager_v1" version="1">
|
||||
<request name="destroy" type="destructor">
|
||||
<description summary="destroy the manager">Child buffers are unaffected.</description>
|
||||
</request>
|
||||
<request name="create_u32_rgba_buffer">
|
||||
<description summary="create a 1x1 buffer from 32-bit RGBA values">
|
||||
Channel values are premultiplied and range from 0 to 0xffffffff.
|
||||
</description>
|
||||
<arg name="id" type="new_id" interface="wl_buffer"/>
|
||||
<arg name="r" type="uint"/>
|
||||
<arg name="g" type="uint"/>
|
||||
<arg name="b" type="uint"/>
|
||||
<arg name="a" type="uint"/>
|
||||
</request>
|
||||
</interface>
|
||||
</protocol>
|
||||
@@ -42,6 +42,7 @@
|
||||
#include "sc_layer.h"
|
||||
#include "ahb_swapchain.h"
|
||||
#include "viewporter-server-protocol.h"
|
||||
#include "single-pixel-buffer-v1-server-protocol.h"
|
||||
#include "banner-desktop-v1-server-protocol.h"
|
||||
#include "presentation-time-server-protocol.h"
|
||||
#include "pointer-constraints-unstable-v1-server-protocol.h"
|
||||
@@ -745,13 +746,28 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
if (ci && ci->asked_feedback) ci->shm_frames++; /* since it asked for GPU buffers */
|
||||
}
|
||||
|
||||
static int get_single_pixel_buffer(struct wl_resource *buffer, uint32_t *pixel);
|
||||
|
||||
/* Copy a wp_single_pixel_buffer into the surface's image and release the resource. */
|
||||
static void take_single_pixel(struct surface *s, uint32_t pixel,
|
||||
struct wl_resource *resource) {
|
||||
if (s->shm_img && (vkp_image_width(s->shm_img) != 1 || vkp_image_height(s->shm_img) != 1)) {
|
||||
vkp_image_destroy(s->shm_img);
|
||||
s->shm_img = NULL;
|
||||
}
|
||||
if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1);
|
||||
if (s->shm_img) vkp_image_upload_shm(s->shm_img, &pixel, 4);
|
||||
wl_buffer_send_release(resource);
|
||||
s->buf_w = 1;
|
||||
s->buf_h = 1;
|
||||
s->has_content = s->shm_img != NULL;
|
||||
}
|
||||
|
||||
/* The window the app's performance HUD follows: the latest one at least as big as the last to
|
||||
* start presenting GPU frames (take_dmabuf) (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
|
||||
static struct surface *g_hud_surface;
|
||||
/* When the HUD's window last presented a frame (now_ns), to let a replacement take over. */
|
||||
static int64_t g_hud_last_ns;
|
||||
/* That window committed a frame the screen has not drawn yet. */
|
||||
static int g_hud_fresh;
|
||||
extern void banner_on_game_surface(const char *window, const char *gpu); /* window NULL = gone */
|
||||
extern void banner_on_game_frame(void);
|
||||
/* The program behind that window: its Linux pid (the Wayland client's credentials) and executable name
|
||||
@@ -854,7 +870,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
* Asking whether the compositor could import it, as this used to, is a question about the
|
||||
* copy path and not about whether a frame happened: a game whose buffers go straight to
|
||||
* the display layer draws on screen while the counter sat at 0.0 fps and 1000.0 ms. */
|
||||
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); g_hud_fresh = 1; banner_on_game_frame(); }
|
||||
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); banner_on_game_frame(); }
|
||||
}
|
||||
|
||||
/* ---- hooks for ahb_swapchain.c (zero-copy layers) */
|
||||
@@ -1083,6 +1099,8 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
if (s->pending_attach) {
|
||||
struct wl_resource *buffer = s->pending_buffer;
|
||||
struct dmabuf_buffer *db = get_dmabuf(buffer);
|
||||
uint32_t pixel = 0;
|
||||
int has_single_pixel = get_single_pixel_buffer(buffer, &pixel);
|
||||
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
|
||||
|
||||
/* The previous content is replaced before reaching the screen. */
|
||||
@@ -1101,10 +1119,12 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
* rather than composited, so it survives the zero-copy and HDR layer paths. */
|
||||
if (!buffer) {
|
||||
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
|
||||
} else if (has_single_pixel) {
|
||||
cursor_publish_pixels((const uint8_t *)&pixel, 1, 1, 4, g_cursor_hx, g_cursor_hy);
|
||||
} else {
|
||||
cursor_publish_buffer(s, buffer);
|
||||
wl_buffer_send_release(buffer);
|
||||
}
|
||||
if (buffer) wl_buffer_send_release(buffer);
|
||||
} else if (s->role == ROLE_NONE) {
|
||||
/* Role-less surface: never drawn, but its buffer is kept for a set_cursor to come. */
|
||||
if (buffer) surface_hold_idle(s, buffer);
|
||||
@@ -1113,6 +1133,9 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
} else if (shm) {
|
||||
drop_dmabuf(s, 1);
|
||||
take_shm(s, shm, buffer);
|
||||
} else if (has_single_pixel) {
|
||||
drop_dmabuf(s, 1);
|
||||
take_single_pixel(s, pixel, buffer);
|
||||
} else {
|
||||
drop_dmabuf(s, 1);
|
||||
s->has_content = 0;
|
||||
@@ -1416,6 +1439,80 @@ static void bind_viewporter(struct wl_client *c, void *data, uint32_t ver, uint3
|
||||
wl_resource_set_implementation(r, &viewporter_impl, NULL, NULL);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- wp_single_pixel_buffer_manager_v1
|
||||
* KWin's nested Wayland backend uses one-pixel buffers for its output background. */
|
||||
|
||||
struct single_pixel_buffer {
|
||||
uint32_t pixel;
|
||||
};
|
||||
|
||||
static void single_pixel_buffer_destroy_req(struct wl_client *c, struct wl_resource *r) {
|
||||
wl_resource_destroy(r);
|
||||
}
|
||||
|
||||
static const struct wl_buffer_interface single_pixel_buffer_impl = {
|
||||
.destroy = single_pixel_buffer_destroy_req,
|
||||
};
|
||||
|
||||
static int get_single_pixel_buffer(struct wl_resource *buffer, uint32_t *pixel) {
|
||||
if (!buffer || !wl_resource_instance_of(buffer, &wl_buffer_interface, &single_pixel_buffer_impl))
|
||||
return 0;
|
||||
struct single_pixel_buffer *single = wl_resource_get_user_data(buffer);
|
||||
if (!single) return 0;
|
||||
*pixel = single->pixel;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void single_pixel_buffer_resource_destroy(struct wl_resource *r) {
|
||||
free(wl_resource_get_user_data(r));
|
||||
}
|
||||
|
||||
static void single_pixel_manager_destroy(struct wl_client *c, struct wl_resource *r) {
|
||||
wl_resource_destroy(r);
|
||||
}
|
||||
|
||||
static uint32_t single_pixel_channel(uint32_t value) {
|
||||
return (uint32_t)(((uint64_t)value * 255u + UINT32_MAX / 2u) / UINT32_MAX);
|
||||
}
|
||||
|
||||
static void single_pixel_create_buffer(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
||||
uint32_t red, uint32_t green, uint32_t blue, uint32_t alpha) {
|
||||
struct single_pixel_buffer *buffer = calloc(1, sizeof(*buffer));
|
||||
if (!buffer) {
|
||||
wl_client_post_no_memory(c);
|
||||
return;
|
||||
}
|
||||
|
||||
/* wl_shm's ARGB8888 word layout is 0xAARRGGBB. */
|
||||
buffer->pixel = (single_pixel_channel(alpha) << 24)
|
||||
| (single_pixel_channel(red) << 16)
|
||||
| (single_pixel_channel(green) << 8)
|
||||
| single_pixel_channel(blue);
|
||||
|
||||
struct wl_resource *resource = wl_resource_create(c, &wl_buffer_interface, 1, id);
|
||||
if (!resource) {
|
||||
free(buffer);
|
||||
wl_client_post_no_memory(c);
|
||||
return;
|
||||
}
|
||||
wl_resource_set_implementation(resource, &single_pixel_buffer_impl, buffer,
|
||||
single_pixel_buffer_resource_destroy);
|
||||
}
|
||||
|
||||
static const struct wp_single_pixel_buffer_manager_v1_interface single_pixel_manager_impl = {
|
||||
.destroy = single_pixel_manager_destroy,
|
||||
.create_u32_rgba_buffer = single_pixel_create_buffer,
|
||||
};
|
||||
|
||||
static void bind_single_pixel_manager(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
|
||||
struct wl_resource *r = wl_resource_create(c, &wp_single_pixel_buffer_manager_v1_interface, ver, id);
|
||||
if (!r) {
|
||||
wl_client_post_no_memory(c);
|
||||
return;
|
||||
}
|
||||
wl_resource_set_implementation(r, &single_pixel_manager_impl, NULL, NULL);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ xdg_shell */
|
||||
|
||||
static void xdg_toplevel_destroy_req(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
@@ -2023,7 +2120,6 @@ static void render_scene(void) {
|
||||
int copy = 0; /* this scene went through the screen swapchain (the perf line's "copy") */
|
||||
|
||||
g_dirty = 0;
|
||||
g_hud_fresh = 0;
|
||||
g_hdr_unimported = NULL; /* found again while the scene is built (HDR gate open only) */
|
||||
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
|
||||
scene_size(&w, &h);
|
||||
@@ -2239,13 +2335,6 @@ static void schedule_render(void) {
|
||||
wl_event_source_timer_update(g_fallback_timer, 8);
|
||||
}
|
||||
|
||||
/* With frame generation on, every scene is the engine's next source frame, so one drawn for
|
||||
* another window (Steam's overlay) counted as a game frame and took its present slots. Such a
|
||||
* change waits for the game's next frame, unless the game has been still for 100 ms. */
|
||||
static int scene_waits_for_game(int64_t now) {
|
||||
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
|
||||
}
|
||||
|
||||
/* A screen refresh (Choreographer tick): draw the newest state once. */
|
||||
static void on_vsync(int64_t frame_time_ns) {
|
||||
int64_t now = now_ns();
|
||||
@@ -2261,7 +2350,7 @@ static void on_vsync(int64_t frame_time_ns) {
|
||||
if (vkp_apply_window_request()) g_dirty = 1;
|
||||
/* A screen-effect setting changed (JNI, any thread): redraw so it shows on a static scene too. */
|
||||
if (vkp_effects_sync()) g_dirty = 1;
|
||||
if (g_dirty && !scene_waits_for_game(now)) render_scene();
|
||||
if (g_dirty) render_scene();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ wl_seat */
|
||||
@@ -3474,6 +3563,7 @@ int banner_wayland_run(void) {
|
||||
wl_global_create(display, &wl_compositor_interface, 6, NULL, bind_compositor);
|
||||
wl_global_create(display, &wl_subcompositor_interface, 1, NULL, bind_subcompositor);
|
||||
wl_global_create(display, &wp_viewporter_interface, 1, NULL, bind_viewporter);
|
||||
wl_global_create(display, &wp_single_pixel_buffer_manager_v1_interface, 1, NULL, bind_single_pixel_manager);
|
||||
wl_display_init_shm(display); /* wl_shm global + pool/buffer handling */
|
||||
/* libdecor binds wl_output at 4; a lower version is a protocol error for the client. */
|
||||
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
/** SessionActivity hosted in its own process so the external display gets an independent compositor. */
|
||||
class ExternalSessionActivity : SessionActivity()
|
||||
@@ -125,6 +125,8 @@ class MainActivity : ComponentActivity() {
|
||||
private var pkgStage by mutableStateOf<String?>(null)
|
||||
private var pkgPercent by mutableIntStateOf(-1)
|
||||
private var desktopInstalled by mutableStateOf(false)
|
||||
private var plasmaMobileInstalled by mutableStateOf(false)
|
||||
private var desktopEnvironment by mutableStateOf(SessionPrefs.DESKTOP_ENV_LXQT)
|
||||
private var offlineAccount by mutableStateOf<String?>(null)
|
||||
private var offline by mutableStateOf(false)
|
||||
private var showPerformance by mutableStateOf(false)
|
||||
@@ -137,7 +139,6 @@ class MainActivity : ComponentActivity() {
|
||||
private var gamescopeRealtime by mutableStateOf(false)
|
||||
private var gpuClockPin by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
||||
@@ -145,7 +146,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)
|
||||
@@ -477,16 +477,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)
|
||||
@@ -636,7 +626,6 @@ class MainActivity : ComponentActivity() {
|
||||
if (!SessionState.running) Thread({
|
||||
SessionArtifacts.finishAbandoned(this)
|
||||
SessionArtifacts.scrubOlder(this)
|
||||
SessionArtifacts.prune(this)
|
||||
}, "finish-abandoned").start()
|
||||
}
|
||||
|
||||
@@ -960,9 +949,10 @@ 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,
|
||||
desktopEnvironment = if (mode == SessionService.MODE_DESKTOP) desktopEnvironment else null,
|
||||
plasmaMobileInstalled = plasmaMobileInstalled,
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
storageOptions = storageOptions,
|
||||
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
|
||||
@@ -996,7 +986,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
|
||||
@@ -1007,6 +996,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
},
|
||||
onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
|
||||
onDesktopEnvironment = { value ->
|
||||
SessionPrefs.setDesktopEnvironment(this, value)
|
||||
desktopEnvironment = SessionPrefs.desktopEnvironment(this)
|
||||
},
|
||||
onGameStorage = { path, label -> setGameStorage(path, label) },
|
||||
onPickGameStorageFolder = {
|
||||
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, "Choose the game storage folder", gameStorage.ifEmpty { null }))
|
||||
@@ -1053,7 +1046,7 @@ class MainActivity : ComponentActivity() {
|
||||
tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
|
||||
gamescopeRealtime = gamescopeRealtime,
|
||||
gpuClockPin = gpuClockPin,
|
||||
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, guestHostname = guestHostname, phantomWarning = phantomWarning,
|
||||
prootNoSeccomp = prootNoSeccomp, guestHostname = guestHostname, phantomWarning = phantomWarning,
|
||||
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
|
||||
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
|
||||
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
|
||||
@@ -1063,7 +1056,6 @@ class MainActivity : ComponentActivity() {
|
||||
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
|
||||
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
|
||||
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
|
||||
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
|
||||
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
|
||||
onClientCore = { core, on ->
|
||||
clientCores = if (on) clientCores + core else clientCores - core
|
||||
@@ -1124,7 +1116,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)
|
||||
@@ -1164,7 +1155,6 @@ class MainActivity : ComponentActivity() {
|
||||
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
||||
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
prootFastPath = SessionPrefs.prootFastPath(this)
|
||||
guestHostname = SessionPrefs.guestHostname(this)
|
||||
refreshPhantomStatus()
|
||||
}
|
||||
@@ -1172,6 +1162,8 @@ class MainActivity : ComponentActivity() {
|
||||
private fun refresh() {
|
||||
if (!busy && LinuxRuntimeInstaller.isInstalling()) followInstall { LinuxRuntimeInstaller.attach(it) }
|
||||
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
||||
plasmaMobileInstalled = DesktopCatalog.plasmaMobileInstalled(this)
|
||||
desktopEnvironment = SessionPrefs.desktopEnvironment(this)
|
||||
offlineAccount = OfflineMode.account(this)
|
||||
offline = OfflineMode.enabled(this)
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
|
||||
@@ -58,6 +58,7 @@ import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionLogShare
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionProcess
|
||||
import com.droiddeck.launcher.wayland.HdrSupport
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
@@ -88,7 +89,7 @@ import kotlin.math.abs
|
||||
* since it is input rather than a menu), and one Compose layer on top for everything else -
|
||||
* the HUD line, the loading overlay, the drawer and its dialogs.
|
||||
*/
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
open class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private lateinit var sessionOverlay: ComposeView
|
||||
private lateinit var loading: LoadingState
|
||||
@@ -98,25 +99,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 +220,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()
|
||||
@@ -289,14 +263,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
surfaceView.holder.addCallback(this)
|
||||
root.addView(surfaceView)
|
||||
|
||||
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
|
||||
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this, SessionProcess.isExternalDisplay(this)), "dev/input"))
|
||||
padBridge = bridge
|
||||
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
||||
@Suppress("DEPRECATION")
|
||||
(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 {
|
||||
@@ -315,12 +288,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
loading = LoadingState(this, steam = loadingMode() == SessionService.MODE_STEAM)
|
||||
if (!SessionState.running) {
|
||||
val requestedMode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||
val needRuntime = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
|
||||
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
|
||||
val desktopMode = requestedMode == SessionService.MODE_DESKTOP || requestedMode == SessionService.MODE_PLASMA_MOBILE
|
||||
val needDesktop = desktopMode &&
|
||||
!com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this)
|
||||
val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM &&
|
||||
val wantsPlasma = requestedMode == SessionService.MODE_PLASMA_MOBILE ||
|
||||
(requestedMode == SessionService.MODE_DESKTOP &&
|
||||
SessionPrefs.desktopEnvironment(this) == SessionPrefs.DESKTOP_ENV_PLASMA_MOBILE)
|
||||
val plasmaInstalled = com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this)
|
||||
val needPlasma = wantsPlasma && !plasmaInstalled && requestedMode == SessionService.MODE_DESKTOP
|
||||
val needProton = requestedMode == SessionService.MODE_STEAM &&
|
||||
com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
|
||||
if (needRuntime || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton)
|
||||
if (requestedMode == SessionService.MODE_PLASMA_MOBILE && (!plasmaInstalled || needDesktop || needRuntime)) {
|
||||
loading.showEnded("Open Desktop with KDE Plasma Mobile once before selecting it for the second screen.")
|
||||
} else if (needRuntime || needDesktop || needPlasma || needProton) {
|
||||
installThenStart(needRuntime, needDesktop, needPlasma, needProton)
|
||||
}
|
||||
}
|
||||
hud = PerfHud(this)
|
||||
hud.onPresentingWindowChanged = {
|
||||
@@ -337,6 +321,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
floodColor = it
|
||||
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(it))
|
||||
}
|
||||
}
|
||||
sessionOverlay = createSessionOverlay()
|
||||
root.addView(sessionOverlay)
|
||||
setContentView(root)
|
||||
@@ -369,9 +354,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun createSessionOverlay(): ComposeView = ComposeView(this).apply {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
// Compose draws each control's focus ring. Android's default highlight would cover
|
||||
// this full-screen host and remain as a white veil after the drawer closes.
|
||||
defaultFocusHighlightEnabled = false
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
|
||||
@@ -423,11 +405,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
frameGen = frameGen,
|
||||
lossless = lossless,
|
||||
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
|
||||
directTouchOnly = SessionProcess.isExternalDisplay(this@SessionActivity),
|
||||
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
|
||||
shapeMode = shapeMode, fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
plasmaMobileInstalled = com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this@SessionActivity) &&
|
||||
com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this@SessionActivity),
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
|
||||
onFrameGenPick = { mode ->
|
||||
@@ -513,6 +498,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun refreshHomeApp() {
|
||||
isHomeApp = HomeApp.isDefault(this)
|
||||
androidApps = if (isHomeApp) HomeApp.launchableApps(this) else emptyList()
|
||||
@@ -617,9 +603,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
|
||||
@@ -645,7 +629,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun readPrefs() {
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
fillScreen = SessionPrefs.forceFullscreen(this)
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
touchMode = if (SessionProcess.isExternalDisplay(this)) SessionPrefs.TOUCH_DIRECT
|
||||
else SessionPrefs.touchMode(this)
|
||||
frameGen = FrameGen.mode(this)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
@@ -669,17 +654,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
* dialog, download or client restart. Not being able to fetch it stops nothing: the session
|
||||
* then asks the client for it after sign-in, as it always has.
|
||||
*/
|
||||
private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false) {
|
||||
private fun installThenStart(runtime: Boolean, desktop: Boolean, plasmaMobile: Boolean, proton: Boolean) {
|
||||
if (SessionState.stopRequested) return
|
||||
installingRuntime = true
|
||||
SessionState.installing = if (runtime) "runtime" else if (desktop) "desktop" else "proton"
|
||||
SessionState.installing = when {
|
||||
runtime -> "runtime"
|
||||
desktop -> "desktop"
|
||||
plasmaMobile -> "plasma-mobile"
|
||||
else -> "proton"
|
||||
}
|
||||
SessionEvents.transition(
|
||||
SessionPhase.INSTALLING_RUNTIME,
|
||||
"${SessionState.installing}.installing",
|
||||
mapOf("component" to SessionState.installing),
|
||||
)
|
||||
loading.step = if (runtime) "downloading the Linux runtime" else if (desktop) "downloading the desktop"
|
||||
else "downloading Proton Experimental (ARM64)"
|
||||
loading.step = when {
|
||||
runtime -> "downloading the Linux runtime"
|
||||
desktop -> "downloading the desktop"
|
||||
plasmaMobile -> "installing KDE Plasma Mobile"
|
||||
else -> "downloading Proton Experimental (ARM64)"
|
||||
}
|
||||
loading.percent = -1
|
||||
Thread({
|
||||
var failedComponent: String? = null
|
||||
@@ -694,6 +688,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
problem = installDesktop()
|
||||
if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop"
|
||||
}
|
||||
if (problem == null && plasmaMobile && !SessionState.stopRequested) {
|
||||
SessionState.installing = "plasma-mobile"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "plasma-mobile.installing", mapOf("component" to "plasma-mobile"))
|
||||
problem = installPlasmaMobile()
|
||||
if (problem == null) SessionEvents.record("plasma-mobile.ready") else failedComponent = "plasma-mobile"
|
||||
}
|
||||
if (problem == null && proton && !SessionState.stopRequested) {
|
||||
SessionState.installing = "proton"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "proton.installing", mapOf("component" to "proton"))
|
||||
@@ -701,6 +701,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (protonProblem == null) SessionEvents.record("proton.ready")
|
||||
else SessionEvents.record("proton.skipped", mapOf("reason" to protonProblem))
|
||||
}
|
||||
}
|
||||
uiHandler.post {
|
||||
installingRuntime = false
|
||||
SessionState.installing = null
|
||||
@@ -712,7 +713,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return@post
|
||||
}
|
||||
if (problem != null) {
|
||||
val code = if (failedComponent == "runtime") "RUNTIME_INSTALL_FAILED" else "DESKTOP_INSTALL_FAILED"
|
||||
val code = when (failedComponent) {
|
||||
"runtime" -> "RUNTIME_INSTALL_FAILED"
|
||||
"plasma-mobile" -> "PLASMA_MOBILE_INSTALL_FAILED"
|
||||
else -> "DESKTOP_INSTALL_FAILED"
|
||||
}
|
||||
SessionEvents.fail(code, problem)
|
||||
collectStartArtifacts("session start failed")
|
||||
loading.showEnded(problem)
|
||||
@@ -767,6 +772,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return problem?.let { "The desktop did not install ($it). Check the connection and press Desktop again." }
|
||||
}
|
||||
|
||||
private fun installPlasmaMobile(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.step = "installing KDE Plasma Mobile packages" }
|
||||
val problem = com.droiddeck.launcher.runtime.PlasmaMobileInstaller.install(
|
||||
this,
|
||||
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { stage, percent ->
|
||||
uiHandler.post { loading.percent = percent; loading.step = stage }
|
||||
},
|
||||
)
|
||||
return problem?.let { "KDE Plasma Mobile did not install: $it. Press Desktop again to retry." }
|
||||
}
|
||||
|
||||
/** Null when the ARM64 Proton is in, else why not; the session goes on either way. */
|
||||
private fun installProton(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.step = "downloading Proton Experimental (ARM64)" }
|
||||
@@ -775,13 +791,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
?: return "catalog unreachable"
|
||||
return catalog.install(this, entry, progressFor("Proton Experimental (ARM64)", entry.size / 1_000_000))
|
||||
}
|
||||
}
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
if (installingRuntime || SessionState.stopRequested) return
|
||||
if (!SessionState.running) {
|
||||
SessionState.mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
|
||||
}
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
val externalDisplay = SessionProcess.isExternalDisplay(this)
|
||||
val runtimeDir = File(filesDir, if (externalDisplay) ".wayland-rt-external-display" else ".wayland-rt").apply { mkdirs() }
|
||||
// The compositor hands this keymap to wl_keyboard clients, which is how the guest reads
|
||||
// the evdev codes we inject.
|
||||
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
|
||||
@@ -898,6 +917,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
val panelW = maxOf(bounds.width(), bounds.height()).toFloat()
|
||||
val panelH = minOf(bounds.width(), bounds.height()).toFloat()
|
||||
// Plasma Mobile on a secondary display is a full external desktop. Use that display's
|
||||
// logical panel size directly; the handheld's saved 16:9 floor and 720p cap otherwise
|
||||
// leave large bars on the external screen.
|
||||
if (SessionProcess.isExternalDisplay(this)) {
|
||||
return Pair(panelW.toInt() and 1.inv(), panelH.toInt() and 1.inv())
|
||||
}
|
||||
// Never narrower than 16:9. A foldable's inner panel is nearly square, and a game handed a
|
||||
// square display draws for the frame it was made for and cuts the sides off itself.
|
||||
// Wider than 16:9 is fine - games and the client cope with a phone's 20:9 - so the
|
||||
@@ -1006,7 +1031,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun onSessionEnded(status: Int) {
|
||||
closeSecondScreen(reset = true)
|
||||
closeSecondScreen(reset = true, stopPlasma = true)
|
||||
if (status == 0) {
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
@@ -1385,29 +1410,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
secondScreenDisplays = candidates
|
||||
val newIds = candidates.map { it.id }.toSet()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) {
|
||||
closeSecondScreen(reset = true)
|
||||
closeSecondScreen(reset = true, stopPlasma = true)
|
||||
return
|
||||
}
|
||||
if (selectedSecondScreenDisplay !in newIds) selectedSecondScreenDisplay = candidates.firstOrNull()?.id ?: -1
|
||||
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) closeSecondScreen(reset = true)
|
||||
// A choice kept while its display was away (asleep, waking): back as soon as it is.
|
||||
else if (started && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) {
|
||||
closeSecondScreen(reset = true, stopPlasma = true)
|
||||
} else if (started && secondScreenMode != SecondScreenMode.NONE &&
|
||||
secondScreenMode != SecondScreenMode.PLASMA_MOBILE && secondScreenPresentation == null) {
|
||||
// A regular presentation can be restored when its display returns. Plasma Mobile owns
|
||||
// a separate activity and is deliberately not relaunched from display callbacks.
|
||||
showSecondScreen(secondScreenMode)
|
||||
}
|
||||
}
|
||||
|
||||
private fun selectSecondScreenDisplay(displayId: Int) {
|
||||
if (secondScreenDisplays.none { it.id == displayId }) return
|
||||
val movePlasma = secondScreenMode == SecondScreenMode.PLASMA_MOBILE && selectedSecondScreenDisplay != displayId
|
||||
if (movePlasma) closeSecondScreen(reset = true, stopPlasma = true)
|
||||
selectedSecondScreenDisplay = displayId
|
||||
SessionState.secondScreenDisplay = displayId
|
||||
if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode)
|
||||
if (movePlasma) {
|
||||
uiHandler.postDelayed({ if (displayId in secondScreenDisplays.map { it.id }) showSecondScreen(SecondScreenMode.PLASMA_MOBILE) }, 700)
|
||||
} else if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode)
|
||||
}
|
||||
|
||||
private fun selectSecondScreenMode(mode: SecondScreenMode) {
|
||||
if (mode == SecondScreenMode.NONE) {
|
||||
closeSecondScreen(reset = true)
|
||||
closeSecondScreen(reset = true, stopPlasma = true)
|
||||
return
|
||||
}
|
||||
if (secondScreenDisplays.isEmpty()) {
|
||||
secondScreenMode = SecondScreenMode.NONE
|
||||
closeSecondScreen(reset = true, stopPlasma = true)
|
||||
return
|
||||
}
|
||||
if (selectedSecondScreenDisplay !in secondScreenDisplays.map { it.id }) {
|
||||
@@ -1419,11 +1453,49 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun showSecondScreen(mode: SecondScreenMode) {
|
||||
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
|
||||
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
|
||||
// Not there right now - a panel still waking, say. The choice is kept; the display
|
||||
// listener shows it again when the display comes back (refreshSecondScreenDisplays).
|
||||
closeSecondScreen(reset = false)
|
||||
if (mode == SecondScreenMode.PLASMA_MOBILE) {
|
||||
closeSecondScreen(reset = true, stopPlasma = true)
|
||||
refreshSecondScreenDisplays()
|
||||
} else {
|
||||
// A regular presentation may be restored when its display wakes or returns.
|
||||
closeSecondScreen(reset = false)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (mode == SecondScreenMode.PLASMA_MOBILE) {
|
||||
if (!com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this) ||
|
||||
!com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this)) {
|
||||
secondScreenMode = SecondScreenMode.NONE
|
||||
SessionState.secondScreenMode = SecondScreenMode.NONE
|
||||
Toast.makeText(this, "Open Desktop with KDE Plasma Mobile once to install it.", Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
secondScreenPresentation?.closeControls()
|
||||
secondScreenPresentation = null
|
||||
try {
|
||||
val launch = Intent(this, ExternalSessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_PLASMA_MOBILE)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
|
||||
val options = android.app.ActivityOptions.makeBasic()
|
||||
.setLaunchDisplayId(target.displayId)
|
||||
.toBundle()
|
||||
startActivity(launch, options)
|
||||
secondScreenMode = mode
|
||||
SessionState.secondScreenMode = mode
|
||||
SessionState.secondScreenDisplay = selectedSecondScreenDisplay
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not open Plasma Mobile on ${target.name}", e)
|
||||
Toast.makeText(this, "Could not open KDE Plasma Mobile on ${target.name}.", Toast.LENGTH_LONG).show()
|
||||
secondScreenMode = SecondScreenMode.NONE
|
||||
SessionState.secondScreenMode = SecondScreenMode.NONE
|
||||
}
|
||||
return
|
||||
}
|
||||
if (secondScreenMode == SecondScreenMode.PLASMA_MOBILE) {
|
||||
SessionService.stopExternalDisplaySession(this)
|
||||
secondScreenMode = SecondScreenMode.NONE
|
||||
SessionState.secondScreenMode = SecondScreenMode.NONE
|
||||
}
|
||||
var presentation = secondScreenPresentation
|
||||
if (presentation?.display?.displayId != target.displayId) {
|
||||
presentation?.closeControls()
|
||||
@@ -1471,7 +1543,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeSecondScreen(reset: Boolean) {
|
||||
private fun closeSecondScreen(reset: Boolean, stopPlasma: Boolean = false) {
|
||||
if (stopPlasma && secondScreenMode == SecondScreenMode.PLASMA_MOBILE) {
|
||||
SessionService.stopExternalDisplaySession(this)
|
||||
}
|
||||
secondScreenPresentation?.closeControls()
|
||||
secondScreenPresentation = null
|
||||
if (reset) {
|
||||
@@ -1480,11 +1555,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
/** Touchpad on the desktop, direct in Steam, unless the drawer says otherwise. */
|
||||
private fun usingTouchpad(): Boolean = when (SessionPrefs.touchMode(this)) {
|
||||
SessionPrefs.TOUCH_PAD -> true
|
||||
SessionPrefs.TOUCH_DIRECT -> false
|
||||
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
|
||||
/** Direct touch on external desktops; otherwise use the user's touch setting. */
|
||||
private fun usingTouchpad(): Boolean {
|
||||
if (SessionProcess.isExternalDisplay(this)) return false
|
||||
return when (SessionPrefs.touchMode(this)) {
|
||||
SessionPrefs.TOUCH_PAD -> true
|
||||
SessionPrefs.TOUCH_DIRECT -> false
|
||||
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
|
||||
}
|
||||
}
|
||||
|
||||
/** The picture's rectangle inside the view: where the pointer may go. */
|
||||
@@ -1559,14 +1637,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 }
|
||||
@@ -1582,7 +1652,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// Auto: the touch pad when there is no controller - except on the desktop, where the
|
||||
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
|
||||
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
|
||||
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
|
||||
else -> !PadBridge.anyControllerConnected() &&
|
||||
SessionState.mode != SessionService.MODE_DESKTOP && SessionState.mode != SessionService.MODE_PLASMA_MOBILE
|
||||
}
|
||||
if (show == (controls.visibility == View.VISIBLE)) return
|
||||
if (!show) controls.releaseAll()
|
||||
@@ -1601,7 +1672,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = true
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
refreshSecondScreenDisplays()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
// The external activity owns Plasma Mobile on the second display. Reopening it whenever
|
||||
// this activity returns caused a failed guest to relaunch in a loop.
|
||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenMode != SecondScreenMode.PLASMA_MOBILE &&
|
||||
secondScreenPresentation == null) {
|
||||
showSecondScreen(secondScreenMode)
|
||||
}
|
||||
SessionService.setActivityVisible(this, true)
|
||||
}
|
||||
|
||||
@@ -1609,8 +1685,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = false
|
||||
displayManager.unregisterDisplayListener(displayListener)
|
||||
// Closed while the session is out of sight (sleep, a closed lid, another app), and kept:
|
||||
// onStart puts it back.
|
||||
closeSecondScreen(reset = false)
|
||||
// onStart puts a regular presentation back. Plasma Mobile runs in its own activity.
|
||||
if (secondScreenMode != SecondScreenMode.PLASMA_MOBILE) closeSecondScreen(reset = false)
|
||||
SessionService.setActivityVisible(this, false)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.droiddeck.launcher.core.FileUtils;
|
||||
import com.droiddeck.launcher.core.SessionPart;
|
||||
import com.droiddeck.launcher.core.HostProcess;
|
||||
import com.droiddeck.launcher.core.TarZst;
|
||||
import com.droiddeck.launcher.session.SessionProcess;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
@@ -50,7 +51,8 @@ public class PulseAudioComponent extends SessionPart {
|
||||
|
||||
/** As above, with a microphone fed from {@code micFifoPath}; null for output only. */
|
||||
public PulseAudioComponent(Context context, String micFifoPath) {
|
||||
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
|
||||
this.workingDir = new File(context.getFilesDir(),
|
||||
SessionProcess.INSTANCE.isExternalDisplay(context) ? "pulseaudio-external-display" : "pulseaudio");
|
||||
this.micFifoPath = micFifoPath;
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,12 @@ object DeviceReport {
|
||||
b.append("DroidDeck session report\n")
|
||||
b.append("========================\n")
|
||||
k("Written", SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.US).format(Date()))
|
||||
k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (labwc/LXQt)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" })
|
||||
k("Session mode", when (mode) {
|
||||
SessionService.MODE_DESKTOP -> if (SessionPrefs.desktopEnvironment(context) == SessionPrefs.DESKTOP_ENV_PLASMA_MOBILE) "desktop (KDE Plasma Mobile)" else "desktop (labwc/LXQt)"
|
||||
SessionService.MODE_PLASMA_MOBILE -> "secondary desktop (KDE Plasma Mobile)"
|
||||
SessionService.MODE_RUN -> "a program under gamescope"
|
||||
else -> "Steam client (gamescope)"
|
||||
})
|
||||
|
||||
h("App")
|
||||
runCatching {
|
||||
@@ -154,11 +159,9 @@ object DeviceReport {
|
||||
k("Skip xalia", SessionPrefs.noXalia(context))
|
||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch games to fill", SessionPrefs.forceFullscreen(context))
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic")
|
||||
k("Microphone", SessionPrefs.micEnabled(context))
|
||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||
@@ -175,7 +178,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)")
|
||||
|
||||
@@ -6,8 +6,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import org.json.JSONObject
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.store.gog.GogGameInfo
|
||||
import com.droiddeck.launcher.store.gog.GogManager
|
||||
import java.io.File
|
||||
import java.util.zip.CRC32
|
||||
|
||||
@@ -25,10 +23,6 @@ object AddedGames {
|
||||
val gameId: Long,
|
||||
val candidates: List<File>,
|
||||
val steamAppId: Int? = null,
|
||||
/** Launch arguments the game's store gives (a GOG play task's); empty for most games. */
|
||||
val args: String = "",
|
||||
/** The store a game was installed from ("gog"), or null for a folder the user added. */
|
||||
val store: String? = null,
|
||||
) {
|
||||
fun folderName(): String = folder.name
|
||||
}
|
||||
@@ -75,9 +69,6 @@ object AddedGames {
|
||||
GameStorage.effective(context)?.let { lib ->
|
||||
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
|
||||
}
|
||||
// The runtime's own disk (the store's internal GOG folder) is the session's root.
|
||||
val rootfs = LinuxRuntime.rootDir(context).absolutePath
|
||||
if (path.startsWith("$rootfs/")) return "/" + path.removePrefix("$rootfs/")
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -99,38 +90,25 @@ object AddedGames {
|
||||
|
||||
fun scan(context: Context): List<Game> {
|
||||
val out = ArrayList<Game>()
|
||||
val stores = GogManager.bases(context).map { it.host }
|
||||
val folders = roots(context).map { it.host } + listOfNotNull(
|
||||
GameStorage.effective(context)?.let { File(it.path) },
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||
) + stores.filter { it.isDirectory }
|
||||
val storePaths = stores.map { it.absolutePath }.toSet()
|
||||
)
|
||||
for (dir in folders.distinctBy { it.absolutePath }) {
|
||||
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
|
||||
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
|
||||
// The store's folder is a folder of games, not one; its games are scanned on their own.
|
||||
if (folder.absolutePath in storePaths) continue
|
||||
scanGame(context, folder, out)
|
||||
}
|
||||
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) scanGame(context, folder, out)
|
||||
}
|
||||
return out.distinctBy { it.folder.canonicalPath }
|
||||
}
|
||||
|
||||
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
|
||||
run {
|
||||
// A store download still running (or stopped partway) is not a game yet.
|
||||
if (GogManager.incomplete(folder)) return
|
||||
// A game the store installed says which exe it is, where it starts and with what
|
||||
// arguments. Folders the user added keep the guess: changing their exe would change
|
||||
// their shortcut id, and with it the prefix their saves are in.
|
||||
val task = if (File(folder, GogManager.MARKER).isFile) GogGameInfo.read(folder)?.task else null
|
||||
val candidates = candidates(folder)
|
||||
val chosen = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||
val exe = chosen ?: task?.exe ?: candidates.firstOrNull() ?: return
|
||||
val exe = chosen ?: candidates.firstOrNull() ?: return
|
||||
val guestExe = guestPath(context, exe)
|
||||
if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return }
|
||||
val startDir = if (chosen == null && task != null) task.workingDir else exe.parentFile ?: folder
|
||||
val guestDir = guestPath(context, startDir) ?: 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
|
||||
@@ -138,8 +116,7 @@ object AddedGames {
|
||||
val steamRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||
val steamId = steamRoute(steamRoot, appId)
|
||||
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
||||
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
|
||||
args = if (chosen == null) task?.arguments.orEmpty() else "", store = if (task != null) "gog" else null))
|
||||
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,8 +139,6 @@ object AddedGames {
|
||||
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
|
||||
.append(",\"folder\":").append(quote(guestPath(context, g.folder) ?: g.guestDir))
|
||||
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
|
||||
if (g.args.isNotEmpty()) json.append(",\"args\":").append(quote(g.args))
|
||||
g.store?.let { json.append(",\"store\":").append(quote(it)) }
|
||||
// The art, as the session sees it: the app's cache is bound at its own path, a file in
|
||||
// the game's folder at the folder's guest path.
|
||||
val art = AddedGameArt.resolve(context, g)
|
||||
|
||||
@@ -5,7 +5,6 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
@@ -85,11 +84,7 @@ object Library {
|
||||
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
|
||||
fun protonPrefix(context: Context, appId: Long, preferredLibrary: File? = null): File? {
|
||||
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
|
||||
val secondary = GameStorage.effective(context)?.let { File(it.path) }
|
||||
fun prefixRoot(root: File): File = if (secondary != null && root.canonicalPath == secondary.canonicalPath)
|
||||
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
|
||||
else root
|
||||
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first }).map(::prefixRoot)
|
||||
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first })
|
||||
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
|
||||
return roots.asSequence()
|
||||
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -8,6 +8,7 @@ enum class SecondScreenMode(val id: String, val label: String) {
|
||||
NONE("none", "None"),
|
||||
KEYBOARD_TRACKPAD("keyboard-trackpad", "Keyboard + trackpad"),
|
||||
TERMINAL("terminal", "Terminal"),
|
||||
PLASMA_MOBILE("plasma-mobile", "KDE Plasma Mobile"),
|
||||
/** The Steam Deck controller's back grips and trackpads; offered while the pad is one. */
|
||||
DECK_CONTROLS("deck-controls", "Deck grips + trackpads"),
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import java.io.File
|
||||
*/
|
||||
object DesktopCatalog {
|
||||
private const val TAG = "DesktopCatalog"
|
||||
/** Advance this when the Plasma root's required package set changes. */
|
||||
internal const val PLASMA_MOBILE_PACKAGE_REVISION = "archlinuxarm-plasma-apps-v2"
|
||||
const val CATALOG_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/desktop.json"
|
||||
/**
|
||||
* Valve's Proton Experimental (ARM64) with its appmanifest, laid out as the client keeps it.
|
||||
@@ -78,6 +80,19 @@ object DesktopCatalog {
|
||||
fun desktopInstalled(context: Context): Boolean =
|
||||
File(LinuxRuntime.rootDir(context), "usr/bin/labwc").isFile
|
||||
|
||||
/** Plasma Mobile lives in a copied Arch root so its package updates never touch Steam's root. */
|
||||
fun plasmaMobileInstalled(context: Context): Boolean {
|
||||
val root = LinuxRuntime.plasmaRootDir(context)
|
||||
return LinuxRuntime.isPlasmaRootCurrent(context) &&
|
||||
FileUtils.readString(plasmaMobileMarker(context))?.trim() == PLASMA_MOBILE_PACKAGE_REVISION &&
|
||||
File(root, "usr/bin/kwin_wayland").isFile &&
|
||||
File(root, "usr/bin/plasmashell").isFile &&
|
||||
File(root, "usr/share/plasma/shells/org.kde.plasma.mobileshell").isDirectory
|
||||
}
|
||||
|
||||
internal fun plasmaMobileMarker(context: Context): File =
|
||||
File(context.filesDir, ".droiddeck-plasma-mobile-installed")
|
||||
|
||||
/** Downloads, verifies and installs one package. Returns null on success, else a message. */
|
||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
|
||||
@@ -89,7 +89,7 @@ object FlatpakManager {
|
||||
/** Runs [argv] in the runtime, its output also in Download/DroidDeck/flatpak-<verb>.log. */
|
||||
private fun runGuest(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
|
||||
val name = "flatpak-" + (argv.getOrNull(2)?.takeIf { argv.getOrNull(1) == HELPER } ?: "setup")
|
||||
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
|
||||
return GuestCommand.run(context, argv, fakeRoot, name, onLine)
|
||||
}
|
||||
|
||||
private inline fun <T> exclusive(what: String, block: () -> T): T? {
|
||||
|
||||
@@ -5,7 +5,6 @@ import android.os.Environment
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionFiles
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
|
||||
@@ -17,29 +16,23 @@ object GuestCommand {
|
||||
/**
|
||||
* Runs [argv] and hands each output line to [onLine]; returns the exit status. [fakeRoot] is
|
||||
* for the package tools, which refuse any uid but 0. With [logName], everything the command
|
||||
* says also goes to Download/DroidDeck/tools/<logName>.log beside the session logs, so a problem can
|
||||
* be handed over like a session's. [extraBinds] are proot binds beyond the usual ones (a game
|
||||
* library on an SD card), and [onProcess] gets the process as it starts, for a caller that may
|
||||
* have to stop it.
|
||||
* 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,
|
||||
extraBinds: List<String> = emptyList(), onProcess: ((Process) -> Unit)? = 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 {
|
||||
return runLogged(context, argv, fakeRoot, extraBinds, onProcess) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
return runLogged(context, argv, fakeRoot) { line -> log?.println(line); log?.flush(); onLine(line) }
|
||||
} finally {
|
||||
log?.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, extraBinds: List<String>,
|
||||
onProcess: ((Process) -> Unit)?, onLine: (String) -> Unit): Int {
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
@@ -49,10 +42,9 @@ object GuestCommand {
|
||||
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
|
||||
LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), null)
|
||||
.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
extraBinds.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
cmd += listOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
|
||||
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
|
||||
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${runtimeDir.path}",
|
||||
"XDG_DATA_HOME=/root/.local/share", "FLATPAK_BWRAP=${FlatpakManager.BWRAP}",
|
||||
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
|
||||
)
|
||||
@@ -67,7 +59,6 @@ object GuestCommand {
|
||||
val process = builder.start()
|
||||
val pid = HostProcess.pidOf(process)
|
||||
OrphanReaper.keep(pid)
|
||||
onProcess?.invoke(process)
|
||||
try {
|
||||
process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) }
|
||||
return process.waitFor()
|
||||
|
||||
@@ -34,14 +34,6 @@ public final class LinuxRuntime {
|
||||
/** Shortcut extra naming which of the modes above a Linux entry launches. */
|
||||
public static final String EXTRA_LINUX_MODE = "linux_mode";
|
||||
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
|
||||
/**
|
||||
* Where the guest sees a command's XDG_RUNTIME_DIR. A Unix socket's path must fit in 108 bytes,
|
||||
* and libwayland checks the guest's path before proot ever sees it: with the app on an SD card
|
||||
* adopted as internal storage the files directory is /mnt/expand/<uuid>/user/0/<package>/files,
|
||||
* and gamescope-0 under it is one byte over, so gamescope could not open its socket and the
|
||||
* session ended at once. A long host path behind it is proot's to shorten.
|
||||
*/
|
||||
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
|
||||
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
|
||||
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
||||
|
||||
@@ -97,7 +89,12 @@ public final class LinuxRuntime {
|
||||
|
||||
/** The Vulkan ICD manifest the rootfs ships for the device GPU, or null when it has none. */
|
||||
public static File vulkanIcd(Context context) {
|
||||
File icdDir = new File(rootDir(context), "usr/share/vulkan/icd.d");
|
||||
return vulkanIcd(rootDir(context));
|
||||
}
|
||||
|
||||
/** The Vulkan ICD manifest under a selected rootfs, or null when it has none. */
|
||||
public static File vulkanIcd(File root) {
|
||||
File icdDir = new File(root, "usr/share/vulkan/icd.d");
|
||||
File[] manifests = icdDir.listFiles((dir, name) -> name.endsWith(".json"));
|
||||
if (manifests == null) return null;
|
||||
for (File manifest : manifests) {
|
||||
@@ -122,11 +119,25 @@ public final class LinuxRuntime {
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand) {
|
||||
File root = rootDir(context);
|
||||
List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds);
|
||||
return commandForRoot(context, rootDir(context), sessionRoot, runtimeDir, externalStorage, extraBinds,
|
||||
guestCommand, false);
|
||||
}
|
||||
|
||||
/** Builds a command for a selected rootfs; installers may also request PRoot's fake-root identity. */
|
||||
public static List<String> commandForRoot(Context context, File root, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand) {
|
||||
return commandForRoot(context, root, sessionRoot, runtimeDir, externalStorage, extraBinds,
|
||||
guestCommand, false);
|
||||
}
|
||||
|
||||
public static List<String> commandForRoot(Context context, File root, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand, boolean fakeRoot) {
|
||||
List<String> binds = binds(context, root, sessionRoot, runtimeDir, externalStorage, extraBinds);
|
||||
// A session's binds are the view its programs have; a one-off command's are not recorded.
|
||||
if (sessionRoot != null) lastBinds = binds;
|
||||
List<String> cmd = prootPrefix(context, root, "/root");
|
||||
List<String> cmd = prootPrefix(context, root, "/root", fakeRoot);
|
||||
for (String spec : binds) bind(cmd, spec);
|
||||
cmd.addAll(guestCommand);
|
||||
return cmd;
|
||||
@@ -180,7 +191,12 @@ public final class LinuxRuntime {
|
||||
/** The {@code host:guest} (or same-path) bind specs of a session; see {@link #command}. */
|
||||
public static List<String> binds(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds) {
|
||||
File root = rootDir(context);
|
||||
return binds(context, rootDir(context), sessionRoot, runtimeDir, externalStorage, extraBinds);
|
||||
}
|
||||
|
||||
/** As above, using the selected rootfs for files prepared inside the guest. */
|
||||
public static List<String> binds(Context context, File root, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds) {
|
||||
List<String> cmd = new ArrayList<>();
|
||||
bind(cmd, "/dev");
|
||||
bind(cmd, "/proc");
|
||||
@@ -193,10 +209,7 @@ public final class LinuxRuntime {
|
||||
bind(cmd, new File(root, "etc/bannerlator/empty").getPath() + ":/sys/fs/selinux");
|
||||
bind(cmd, context.getFilesDir().getPath());
|
||||
bind(cmd, context.getCacheDir().getPath());
|
||||
if (runtimeDir != null) {
|
||||
bind(cmd, runtimeDir.getPath());
|
||||
bind(cmd, runtimeDir.getPath() + ":" + GUEST_RUNTIME_DIR);
|
||||
}
|
||||
if (runtimeDir != null) bind(cmd, runtimeDir.getPath());
|
||||
if (sessionRoot != null) bind(cmd, sessionRoot.getPath());
|
||||
if (externalStorage != null && externalStorage.isDirectory()) {
|
||||
bind(cmd, externalStorage.getPath());
|
||||
@@ -242,15 +255,12 @@ public final class LinuxRuntime {
|
||||
};
|
||||
for (String[] entry : procFiles) {
|
||||
File fake = new File(fakeProc, entry[0]);
|
||||
// A live stand-in the session binds itself (CpuStatComponent's /proc/stat) wins.
|
||||
boolean live = false;
|
||||
if (extraBinds != null) for (String spec : extraBinds) live |= spec.endsWith(":" + entry[1]);
|
||||
if (!live && fake.isFile() && !new File(entry[1]).canRead()) {
|
||||
if (fake.isFile() && !new File(entry[1]).canRead()) {
|
||||
bind(cmd, fake.getPath() + ":" + entry[1]);
|
||||
}
|
||||
}
|
||||
bindGpuNode(context, cmd);
|
||||
bindAdrenoStats(cmd, extraBinds);
|
||||
bindAdrenoStats(cmd);
|
||||
bindCpuTemps(cmd, root);
|
||||
if (extraBinds != null) {
|
||||
for (String spec : extraBinds) bind(cmd, spec);
|
||||
@@ -296,71 +306,12 @@ public final class LinuxRuntime {
|
||||
if (!Files.isSymbolicLink(subsystem.toPath())) {
|
||||
Os.symlink("/sys/bus/platform", subsystem.getPath());
|
||||
}
|
||||
// What MangoHud names a GPU's driver by; msm_drm is how an Adreno's render node reads
|
||||
// on a mainline kernel, and the driver it reads the load of (bindAdrenoStats).
|
||||
File driver = new File(device, "driver");
|
||||
if (!Files.isSymbolicLink(driver.toPath())) {
|
||||
Os.symlink("/sys/bus/platform/drivers/msm_drm", driver.getPath());
|
||||
}
|
||||
} catch (IOException | ErrnoException e) {
|
||||
return;
|
||||
}
|
||||
bind(cmd, new File(base, "sys").getPath() + ":/sys/dev/char");
|
||||
bind(cmd, dri.getPath() + ":/dev/dri");
|
||||
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
|
||||
bindDrmClass(base, cmd, node, major + ":" + minor);
|
||||
}
|
||||
|
||||
/**
|
||||
* MangoHud (Deck mode's performance overlay, mangoapp) finds the GPU by listing
|
||||
* {@code /sys/class/drm}, and an exception from that listing ends the process: under an
|
||||
* enforcing SELinux policy - every retail phone - an app may not list it, so mangoapp died on
|
||||
* start, gamescope restarted it until the session gave up, and there was no overlay. Where the
|
||||
* app cannot list it, the session's {@code /sys/class/drm} is ours: the render node above,
|
||||
* named as an Adreno's is. MangoHud then reads the GPU's stats from KGSL's sysfs, which such a
|
||||
* device refuses too - SessionService's GpuStatsComponent stands in for that. Where the
|
||||
* listing is allowed it is left alone.
|
||||
*/
|
||||
private static void bindDrmClass(File base, List<String> cmd, String node, String devNumbers) {
|
||||
if (new File("/sys/class/drm").list() != null) return;
|
||||
File drmClass = new File(base, "class");
|
||||
try {
|
||||
if (!drmClass.isDirectory() && !drmClass.mkdirs()) return;
|
||||
// Only symlinks are ever made here; deleting them must not follow one into its target.
|
||||
File[] old = drmClass.listFiles();
|
||||
if (old != null) for (File f : old) Files.deleteIfExists(f.toPath());
|
||||
Os.symlink("/sys/dev/char/" + devNumbers, new File(drmClass, node).getPath());
|
||||
} catch (IOException | ErrnoException e) {
|
||||
return;
|
||||
}
|
||||
bind(cmd, drmClass.getPath() + ":/sys/class/drm");
|
||||
android.util.Log.i("LinuxRuntime", "hud: /sys/class/drm is not listable here; the session's lists " + node);
|
||||
// Also refused to list, also asked for by MangoHud twice a second - an error line each
|
||||
// time in the session log - and holding nothing it reads on an Adreno phone.
|
||||
if (new File("/sys/class/powercap").list() == null) {
|
||||
File empty = new File(base, "empty-powercap");
|
||||
if (empty.isDirectory() || empty.mkdirs()) bind(cmd, empty.getPath() + ":/sys/class/powercap");
|
||||
}
|
||||
}
|
||||
|
||||
/** The temperature of a CPU zone the app may read (the first by name), or null. */
|
||||
public static String cpuTempSource() {
|
||||
for (java.util.Map.Entry<String, File> e : new java.util.TreeMap<>(thermalZones()).entrySet()) {
|
||||
File temp = new File(e.getValue(), "temp");
|
||||
if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) return temp.getPath();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The file the GPU's temperature reads from, or null where the app may read none. */
|
||||
public static String gpuTempSource() {
|
||||
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
|
||||
return firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
|
||||
}
|
||||
|
||||
private static String gpuLoadSource() {
|
||||
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
|
||||
return firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -371,11 +322,11 @@ public final class LinuxRuntime {
|
||||
* Android PC emulators (GameNative, Winlator forks) read them in. A value found nowhere is left
|
||||
* alone.
|
||||
*/
|
||||
private static void bindAdrenoStats(List<String> cmd, List<String> extraBinds) {
|
||||
private static void bindAdrenoStats(List<String> cmd) {
|
||||
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
|
||||
String gpuTemp = gpuTempSource();
|
||||
String gpuTemp = firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
|
||||
String[][] stats = {
|
||||
{gpuLoadSource(), "/sys/kernel/debug/dri/0/perf_now"},
|
||||
{firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load"), "/sys/kernel/debug/dri/0/perf_now"},
|
||||
{firstReadable(kgsl + "devfreq/cur_freq", kgsl + "gpuclk"),
|
||||
"/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"},
|
||||
{gpuTemp, "/sys/class/thermal/thermal_zone28/temp"},
|
||||
@@ -383,21 +334,8 @@ public final class LinuxRuntime {
|
||||
{thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"},
|
||||
};
|
||||
for (String[] stat : stats) {
|
||||
// A value the session feeds itself (GpuStatsComponent, where KGSL is refused) wins.
|
||||
boolean fed = false;
|
||||
if (extraBinds != null) for (String spec : extraBinds) fed |= spec.endsWith(":" + stat[1]);
|
||||
if (stat[0] != null && !fed) bind(cmd, stat[0] + ":" + stat[1]);
|
||||
if (stat[0] != null) bind(cmd, stat[0] + ":" + stat[1]);
|
||||
}
|
||||
// Which of the overlay's GPU values this device lets the app read: a phone under an
|
||||
// enforcing policy refuses some of them, and the overlay then has no line for that value.
|
||||
android.util.Log.i("LinuxRuntime", "hud sources: gpu load " + orNone(stats[0][0]) + ", gpu clock "
|
||||
+ orNone(stats[1][0]) + ", gpu temp " + orNone(gpuTemp) + ", ddr temp " + orNone(stats[4][0])
|
||||
+ ", thermal zones " + thermalZones().size()
|
||||
+ ", kgsl gpubusy " + (new File(kgsl + "gpubusy").canRead() ? "readable" : "refused"));
|
||||
}
|
||||
|
||||
private static String orNone(String path) {
|
||||
return path != null ? path : "none";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import java.io.File
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.nio.file.Files
|
||||
|
||||
/** Installs the optional Plasma Mobile shell into its isolated Arch Linux ARM package root. */
|
||||
object PlasmaMobileInstaller {
|
||||
private val packages = listOf("plasma-mobile", "plasma-settings", "angelfish")
|
||||
|
||||
@Synchronized
|
||||
fun install(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
if (!LinuxRuntime.isInstalled(context)) return "The Linux runtime is not installed"
|
||||
if (!DesktopCatalog.desktopInstalled(context)) return "The Linux desktop package is not installed"
|
||||
listener?.onProgress("Preparing an isolated Linux runtime for KDE", -1)
|
||||
LinuxRuntime.preparePlasmaRoot(context, listener)?.let { return it }
|
||||
val root = LinuxRuntime.plasmaRootDir(context)
|
||||
if (!File(root, "usr/bin/pacman").isFile) return "This Linux runtime has no pacman package manager"
|
||||
val pacmanConfig = File(root, "etc/pacman.conf")
|
||||
if (!pacmanConfig.isFile) return "This Linux runtime has no pacman configuration"
|
||||
val originalPacmanConfig = try {
|
||||
pacmanConfig.readText()
|
||||
} catch (e: Exception) {
|
||||
return "Could not read the pacman configuration: ${e.message ?: e.javaClass.simpleName}"
|
||||
}
|
||||
|
||||
val sessionRoot = File(context.filesDir, "plasma-install-session").apply { mkdirs() }
|
||||
val runtimeDir = File(context.filesDir, ".plasma-install-rt").apply { mkdirs() }
|
||||
val packageLock = File(root, "var/lib/pacman/db.lck")
|
||||
if (packageLock.exists()) {
|
||||
val age = System.currentTimeMillis() - packageLock.lastModified()
|
||||
if (age < 60_000L) return "The isolated package manager is still active; wait a moment and retry"
|
||||
if (!packageLock.delete()) return "Could not clear the stale isolated package-manager lock"
|
||||
}
|
||||
prepareKeyringPermissions(File(root, "etc/pacman.d/gnupg"))?.let {
|
||||
return "Could not make the isolated Arch package keyring writable: $it"
|
||||
}
|
||||
val guest = listOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root",
|
||||
"PATH=/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8", "TERM=xterm",
|
||||
// The isolated root inherits sync databases from the runtime image. Force fresh
|
||||
// repository databases so the rolling package filenames match the live mirrors.
|
||||
// Replace only paths present in incoming packages when the cloned runtime has
|
||||
// unowned files from its base image; the Steam root remains untouched.
|
||||
"/bin/sh", "-c",
|
||||
"/usr/bin/pacman-key --init && /usr/bin/pacman-key --populate archlinuxarm && " +
|
||||
"/usr/bin/pacman -Syyu --needed --noconfirm --overwrite '*' ${packages.joinToString(" ")} && " +
|
||||
// Keep Firefox and Discover out of the Plasma-only clone even if the base root
|
||||
// already installed them; the original desktop root remains unchanged.
|
||||
"for excluded in firefox discover; do " +
|
||||
"if /usr/bin/pacman -Qq \"\$excluded\" >/dev/null 2>&1; then " +
|
||||
"/usr/bin/pacman -Rns --noconfirm \"\$excluded\" || exit; fi; done",
|
||||
)
|
||||
val command = LinuxRuntime.commandForRoot(
|
||||
context, root, sessionRoot, runtimeDir, null, null, guest, true,
|
||||
)
|
||||
return try {
|
||||
pacmanConfig.writeText(withInstallerDownloadSettings(originalPacmanConfig))
|
||||
listener?.onProgress("Preparing KDE Plasma Mobile", -1)
|
||||
val builder = ProcessBuilder(command).redirectErrorStream(true)
|
||||
builder.directory(root)
|
||||
val hostEnv = builder.environment()
|
||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
|
||||
hostEnv["PROOT_TMP_DIR"] = context.cacheDir.path
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let {
|
||||
hostEnv["LD_LIBRARY_PATH"] = it
|
||||
}
|
||||
|
||||
val process = builder.start()
|
||||
val tail = ArrayDeque<String>()
|
||||
BufferedReader(InputStreamReader(process.inputStream)).use { reader ->
|
||||
while (true) {
|
||||
val line = reader.readLine() ?: break
|
||||
if (line.isNotBlank()) {
|
||||
if (tail.size == 5) tail.removeFirst()
|
||||
tail.addLast(line.take(180))
|
||||
val lower = line.lowercase()
|
||||
listener?.onProgress(
|
||||
when {
|
||||
"synchronizing" in lower || "database" in lower -> "Refreshing KDE package list"
|
||||
"downloading" in lower || "retrieving" in lower -> "Downloading KDE Plasma Mobile packages"
|
||||
"installing" in lower || "checking" in lower -> "Installing KDE Plasma Mobile"
|
||||
else -> "Installing KDE Plasma Mobile"
|
||||
},
|
||||
-1,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
val status = process.waitFor()
|
||||
if (status != 0) {
|
||||
val detail = tail.joinToString(" · ")
|
||||
return "pacman exited with status $status" + if (detail.isNotEmpty()) ": $detail" else ""
|
||||
}
|
||||
val packageMarker = DesktopCatalog.plasmaMobileMarker(context)
|
||||
FileUtils.writeString(packageMarker, "${DesktopCatalog.PLASMA_MOBILE_PACKAGE_REVISION}\n")
|
||||
if (!packageMarker.isFile) return "Plasma Mobile packages installed, but DroidDeck could not save the installation marker"
|
||||
if (!DesktopCatalog.plasmaMobileInstalled(context)) {
|
||||
packageMarker.delete()
|
||||
return "pacman finished, but the Plasma Mobile shell was not found in the runtime"
|
||||
}
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
"Could not install KDE Plasma Mobile: ${e.message ?: e.javaClass.simpleName}"
|
||||
} finally {
|
||||
try {
|
||||
pacmanConfig.writeText(originalPacmanConfig)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("PlasmaMobileInstaller", "could not restore pacman config", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Pacman downloads as its caller, without Landlock, inside the confined guest root. */
|
||||
private fun withInstallerDownloadSettings(config: String): String {
|
||||
val lines = config.lines().toMutableList()
|
||||
val optionsIndex = lines.indexOfFirst { it.trim().equals("[options]", ignoreCase = true) }
|
||||
if (optionsIndex < 0) {
|
||||
lines.add(0, "[options]")
|
||||
lines.add(1, "#DownloadUser =")
|
||||
lines.add(2, "DisableSandbox = true")
|
||||
return lines.joinToString("\n")
|
||||
}
|
||||
var sectionEnd = optionsIndex + 1
|
||||
while (sectionEnd < lines.size) {
|
||||
val line = lines[sectionEnd].trim()
|
||||
if (line.startsWith("[") && line.endsWith("]")) break
|
||||
sectionEnd++
|
||||
}
|
||||
val overrides = listOf("DownloadUser" to "#DownloadUser =", "DisableSandbox" to "DisableSandbox = true")
|
||||
for ((name, setting) in overrides) {
|
||||
val matcher = Regex("^\\s*#?\\s*${name}\\s*=.*$", RegexOption.IGNORE_CASE)
|
||||
var replaced = false
|
||||
for (index in optionsIndex + 1 until sectionEnd) {
|
||||
if (matcher.matches(lines[index])) {
|
||||
lines[index] = setting
|
||||
replaced = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!replaced) lines.add(sectionEnd++, setting)
|
||||
}
|
||||
return lines.joinToString("\n")
|
||||
}
|
||||
|
||||
/** Keep GnuPG's private keyring writable by this app-private PRoot root. */
|
||||
private fun prepareKeyringPermissions(directory: File): String? {
|
||||
if (!directory.exists() && !directory.mkdirs()) return directory.path
|
||||
if (Files.isSymbolicLink(directory.toPath()) || !directory.isDirectory) return directory.path
|
||||
|
||||
fun makeOwnerWritable(file: File): String? {
|
||||
if (Files.isSymbolicLink(file.toPath())) return file.path
|
||||
val ok = if (file.isDirectory) {
|
||||
file.setReadable(true, true) && file.setWritable(true, true) &&
|
||||
file.setExecutable(true, true)
|
||||
} else {
|
||||
file.setReadable(true, true) && file.setWritable(true, true)
|
||||
}
|
||||
if (!ok) return file.path
|
||||
if (file.isDirectory) {
|
||||
val children = file.listFiles() ?: return file.path
|
||||
for (child in children) makeOwnerWritable(child)?.let { return it }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
return makeOwnerWritable(directory)
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* proot's fast path: the session's path lookups answered inside each process by libblfastpath
|
||||
* (tools/proot/fastpath), which issues the translated call from a trampoline page proot's seccomp
|
||||
* filter lets through (tools/proot/patches/0014). A stat or an open costs about a microsecond
|
||||
* instead of a 15-60 us round trip through the tracer.
|
||||
*
|
||||
* The library maps guest paths to host paths itself, so it has to be told the rootfs and the
|
||||
* binds exactly as proot was given them. Both sides carry a key derived from that view - proot
|
||||
* PROOT_FASTPATH=<key>, the guest PROOT_FP_KEY=<key> - and the library answers nothing unless the
|
||||
* process that traces it has the same key: a program that inherited the variables but runs under
|
||||
* another proot (a Flatpak sandbox, a one-off command) leaves every call to its own proot.
|
||||
*
|
||||
* Needs proot's seccomp filter, so "Run proot without seccomp" turns it off as well.
|
||||
*/
|
||||
object ProotFastPath {
|
||||
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
|
||||
|
||||
fun enabled(context: Context): Boolean =
|
||||
SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context)
|
||||
|
||||
/** The key for this rootfs and these binds, or null when the library cannot be told them. */
|
||||
fun key(root: File, binds: List<String>): String? {
|
||||
if (binds.any { it.contains('|') } || root.path.contains('|')) return null
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest((root.path + "\n" + binds.joinToString("\n")).toByteArray())
|
||||
return digest.take(12).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/** What proot's own environment carries. */
|
||||
fun hostEnv(key: String): Pair<String, String> = "PROOT_FASTPATH" to key
|
||||
|
||||
/** The guest's assignments (for `env -i`), describing the view proot was given. */
|
||||
fun guestEnv(root: File, binds: List<String>, key: String): List<String> = listOf(
|
||||
"PROOT_FP_ROOT=" + root.path,
|
||||
"PROOT_FP_BINDS=" + binds.joinToString("|"),
|
||||
"PROOT_FP_KEY=$key",
|
||||
)
|
||||
}
|
||||
@@ -18,15 +18,11 @@ import kotlin.math.abs
|
||||
* from Android's own battery API - the same on every device - into a directory the session binds
|
||||
* over `/sys/class/power_supply`, refreshed every few seconds while the session runs.
|
||||
*
|
||||
* Steam's Quick Access Menu takes its time estimates from neither: it reads the files in `/run/vpower` (as on
|
||||
* SteamOS), and with those absent showed "?h ?m" for projected battery life and for time to full.
|
||||
* The same estimates are written there too, into [vpowerDir] in the guest's own `/run`.
|
||||
*
|
||||
* Values: charge in µAh from the charge counter; energy in µWh from charge × voltage; power in µW
|
||||
* from |current| × voltage; time to empty from charge ÷ |average current| while discharging. Where
|
||||
* a device reports no current, the client still gets status and percentage.
|
||||
*/
|
||||
class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart() {
|
||||
class BatteryComponent(val dir: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
|
||||
@@ -46,8 +42,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
// Stale estimates would outlive the session in the rootfs; Steam falls back to "?h ?m".
|
||||
for (name in VPOWER_FILES) File(vpowerDir, name).delete()
|
||||
}
|
||||
|
||||
private fun write() {
|
||||
@@ -121,17 +115,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
for ((k, v) in attrs) uevent.append("POWER_SUPPLY_").append(k.uppercase()).append('=').append(v).append('\n')
|
||||
put(File(bat, "uevent"), uevent.toString())
|
||||
}
|
||||
val plugged = (sticky?.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) ?: 0) != 0
|
||||
vpowerDir.mkdirs()
|
||||
val vpower = linkedMapOf(
|
||||
"ac_status" to if (plugged) "Connected" else "Disconnected",
|
||||
"battery_percent" to "%.2f".format(java.util.Locale.ROOT, pct.toDouble()),
|
||||
"battery_status" to statusText,
|
||||
// Steam reads a separate file for each direction; -1 = no estimate.
|
||||
"secs_until_battery_full" to (if (timeToFullS > 0) timeToFullS else -1L).toString(),
|
||||
"secs_until_shutdown_request" to (if (timeToEmptyS > 0) timeToEmptyS else -1L).toString(),
|
||||
)
|
||||
for ((k, v) in vpower) put(File(vpowerDir, k), v + "\n")
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "battery: could not write", t)
|
||||
}
|
||||
@@ -147,9 +130,5 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val PERIOD_MS = 5_000L
|
||||
private val VPOWER_FILES = listOf(
|
||||
"ac_status", "battery_percent", "battery_status",
|
||||
"secs_until_battery_full", "secs_until_shutdown_request",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* A `/proc/stat` that moves.
|
||||
*
|
||||
* Android has refused apps `/proc/stat` since 8.0, and the session's stand-in for it was one
|
||||
* `cpu0` line of zeros - enough for glibc and Steam to start, but every CPU load in the session
|
||||
* read 0 % (the performance overlay showed one core, idle). The kernel still lets apps read each
|
||||
* core's idle residency (`cpuidle/stateN/time`, µs, the same label as the cpufreq files), which is
|
||||
* how overlays on Android work out CPU load: a core's busy time is the time that passed less the
|
||||
* time it spent idle. This writes `/proc/stat` from that, one line per core, refreshed twice a
|
||||
* second. Counters only grow - a sample's idle is never more than the time that passed - so a
|
||||
* reader taking the difference of two reads never sees a negative. Where `/proc/stat` is readable,
|
||||
* or the idle times are not, nothing is done.
|
||||
*/
|
||||
class CpuStatComponent(val file: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
private val cores = (0 until coreCount()).toList()
|
||||
private val busy = LongArray(cores.size)
|
||||
private val idle = LongArray(cores.size)
|
||||
private val lastIdleUs = LongArray(cores.size)
|
||||
private var lastMs = 0L
|
||||
private val bootSeconds = (System.currentTimeMillis() - SystemClock.elapsedRealtime()) / 1000
|
||||
|
||||
/** Writes the first sample; true when it should be bound over `/proc/stat`. */
|
||||
fun prepare(): Boolean {
|
||||
if (File("/proc/stat").canRead() || cores.isEmpty() || idleUs(0) == null) return false
|
||||
lastMs = SystemClock.elapsedRealtime()
|
||||
for (i in cores) lastIdleUs[i] = idleUs(i) ?: 0L
|
||||
write()
|
||||
Log.i(TAG, "hud: /proc/stat from the cores' idle times (${cores.size} cores)")
|
||||
return true
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
running = true
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
if (!running) break
|
||||
sample()
|
||||
write()
|
||||
}
|
||||
}, "cpu-stat").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
|
||||
private fun sample() {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val elapsed = (now - lastMs) / MS_PER_TICK
|
||||
if (elapsed <= 0) return
|
||||
lastMs += elapsed * MS_PER_TICK
|
||||
for (i in cores) {
|
||||
// An offline core has no idle residency to count and runs nothing: all idle.
|
||||
val us = idleUs(i)
|
||||
val idleTicks = if (us == null) elapsed else ((us - lastIdleUs[i]) / US_PER_TICK).coerceIn(0, elapsed)
|
||||
if (us != null) lastIdleUs[i] = us
|
||||
idle[i] += idleTicks
|
||||
busy[i] += elapsed - idleTicks
|
||||
}
|
||||
}
|
||||
|
||||
/** The whole file at once, renamed into place: a reader opens either the last sample or this one. */
|
||||
private fun write() {
|
||||
val text = StringBuilder()
|
||||
text.append("cpu ${busy.sum()} 0 0 ${idle.sum()} 0 0 0 0 0 0\n")
|
||||
for (i in cores) text.append("cpu$i ${busy[i]} 0 0 ${idle[i]} 0 0 0 0 0 0\n")
|
||||
text.append("intr 0\nctxt 0\nbtime $bootSeconds\nprocesses 1\nprocs_running 1\nprocs_blocked 0\n")
|
||||
try {
|
||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
||||
tmp.writeText(text.toString())
|
||||
if (!tmp.renameTo(file)) tmp.delete()
|
||||
} catch (e: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val PERIOD_MS = 500L
|
||||
/** /proc/stat counts in USER_HZ, 100 a second on every Linux the guest runs. */
|
||||
private const val MS_PER_TICK = 10L
|
||||
private const val US_PER_TICK = 10_000L
|
||||
|
||||
private fun coreCount(): Int =
|
||||
File("/sys/devices/system/cpu").list()?.count { it.matches(Regex("cpu\\d+")) } ?: 0
|
||||
|
||||
/** The core's total idle residency in µs, or null when it has none to read (offline). */
|
||||
private fun idleUs(core: Int): Long? {
|
||||
val states = File("/sys/devices/system/cpu/cpu$core/cpuidle").listFiles { f -> f.name.startsWith("state") }
|
||||
?: return null
|
||||
if (states.isEmpty()) return null
|
||||
var total = 0L
|
||||
for (state in states) {
|
||||
total += runCatching { File(state, "time").readText().trim().toLong() }.getOrNull() ?: return null
|
||||
}
|
||||
return total
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ object CrashHandler {
|
||||
worker.join(8000)
|
||||
}
|
||||
// The session's tree would outlive us otherwise, and block the next launch.
|
||||
OrphanReaper.reap("app crash")
|
||||
OrphanReaper.reap("app crash", context)
|
||||
} catch (e: Throwable) {
|
||||
// Nothing more to do for a crash inside the crash handler.
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** Separate service process for a full Linux desktop running on an external Android display. */
|
||||
class ExternalSessionService : SessionService()
|
||||
@@ -1,118 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The GPU memory in use, for the performance overlay's VRAM and PVRAM lines.
|
||||
*
|
||||
* Valve's mangoapp reads it from the kernel's gpu_mem_total tracepoint, which no Android app may
|
||||
* reach, so both lines read 0. Our libtracefs for mangoapp (tools/mangoapp/libtracefs-shim.c) hands
|
||||
* it what this writes to [file] - `/run/droiddeck-hud/gpu-mem` in the guest - every few seconds, in
|
||||
* bytes, from the best of what KGSL lets the app read:
|
||||
*
|
||||
* - `/sys/class/kgsl/kgsl/page_alloc`, every GPU page on the device - what the tracepoint's total
|
||||
* counts, where the policy allows it;
|
||||
* - else KGSL's own accounting of each of the session's processes
|
||||
* (`/sys/class/kgsl/kgsl/proc/<pid>/gpumem_mapped` and `gpumem_unmapped`);
|
||||
* - else the size of the KGSL mappings in each of the session's processes' `maps` - only the
|
||||
* buffers the CPU has mapped, so less than the GPU holds (about 40 % of KGSL's own count in a
|
||||
* game on an AYN Thor), but always readable: every process the app can see in `/proc` is one of
|
||||
* its own. `maps` rather than `smaps`, which gives the same sizes but walks page tables to do it:
|
||||
* in a game, 180,000 lines and most of a second of CPU a pass.
|
||||
*
|
||||
* Sampled only while the overlay shows (OverlayShown).
|
||||
*/
|
||||
class GpuMemComponent(private val file: File, private val root: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
private var source = ""
|
||||
|
||||
/** True when there is a source to write from. */
|
||||
fun prepare(): Boolean {
|
||||
val bytes = sample() ?: return false
|
||||
write(bytes)
|
||||
Log.i(TAG, "hud: gpu memory from $source (${bytes / (1024 * 1024)} MiB now)")
|
||||
return true
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
running = true
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
if (running && OverlayShown.check(root)) sample()?.let { write(it) }
|
||||
}
|
||||
}, "gpu-mem").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
file.delete()
|
||||
}
|
||||
|
||||
private fun sample(): Long? {
|
||||
readLong("$KGSL_ROOT/page_alloc")?.let { source = "$KGSL_ROOT/page_alloc"; return it }
|
||||
val pids = sessionPids()
|
||||
var perProcess = 0L
|
||||
var anyProcess = false
|
||||
for (pid in pids) {
|
||||
val mapped = readLong("$KGSL_ROOT/proc/$pid/gpumem_mapped") ?: continue
|
||||
perProcess += mapped + (readLong("$KGSL_ROOT/proc/$pid/gpumem_unmapped") ?: 0L)
|
||||
anyProcess = true
|
||||
}
|
||||
if (anyProcess) { source = "$KGSL_ROOT/proc/<pid>/gpumem_*"; return perProcess }
|
||||
var mappedKb = 0L
|
||||
var anyMap = false
|
||||
for (pid in pids) {
|
||||
val kb = kgslMappedKb(pid) ?: continue
|
||||
mappedKb += kb
|
||||
anyMap = true
|
||||
}
|
||||
if (anyMap) { source = "/proc/<pid>/maps (KGSL mappings)"; return mappedKb * 1024 }
|
||||
return null
|
||||
}
|
||||
|
||||
/** The processes this app may see in /proc: Android hides every other uid's. */
|
||||
private fun sessionPids(): List<String> =
|
||||
File("/proc").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) }.orEmpty()
|
||||
|
||||
/** Size of a process's mappings of the KGSL device, in kB; null where its maps cannot be read. */
|
||||
private fun kgslMappedKb(pid: String): Long? = runCatching {
|
||||
var bytes = 0L
|
||||
File("/proc/$pid/maps").forEachLine { line ->
|
||||
if (line.endsWith("kgsl-3d0") || line.contains("/dev/dri/renderD")) {
|
||||
val dash = line.indexOf('-')
|
||||
val space = line.indexOf(' ')
|
||||
if (dash > 0 && space > dash) {
|
||||
bytes += line.substring(dash + 1, space).toLong(16) - line.substring(0, dash).toLong(16)
|
||||
}
|
||||
}
|
||||
}
|
||||
bytes / 1024
|
||||
}.getOrNull()
|
||||
|
||||
/** Whole, renamed into place: the reader opens either the last value or this one. */
|
||||
private fun write(bytes: Long) {
|
||||
try {
|
||||
file.parentFile?.mkdirs()
|
||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
||||
tmp.writeText("$bytes\n")
|
||||
if (!tmp.renameTo(file)) tmp.delete()
|
||||
} catch (e: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val KGSL_ROOT = "/sys/class/kgsl/kgsl"
|
||||
/** GPU memory moves slowly; a pass over every process's maps is ~40 ms of CPU in a game. */
|
||||
private const val PERIOD_MS = 5_000L
|
||||
|
||||
private fun readLong(path: String): Long? =
|
||||
runCatching { File(path).readText().trim().toLong() }.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
|
||||
/**
|
||||
* The Adreno's stats as mangoapp (Deck mode's performance overlay) reads them.
|
||||
*
|
||||
* MangoHud takes an Adreno's load, clock and temperature from `gpu_busy_percentage`, `clock_mhz`
|
||||
* and `temp` in `/sys/class/kgsl/kgsl-3d0`, and ends the process on one of them it may not read -
|
||||
* not on one that is missing, which it skips. An enforcing SELinux policy (every retail phone)
|
||||
* refuses apps some or all of KGSL's sysfs, each vendor differently, so mangoapp died on start and
|
||||
* the session ran with no overlay. Where any of the three is refused, a directory of our own is
|
||||
* bound there instead, each value fed twice a second from the first source this device lets the
|
||||
* app read - the places other Android overlays (GameNative, WinNative, Bannerlator) read an
|
||||
* Adreno's numbers from, across Snapdragon generations and vendor kernels. A value with no
|
||||
* readable source is left out, and the overlay shows no line for it. Where all three are
|
||||
* readable, nothing is done.
|
||||
*
|
||||
* Valve's build also reads load and clock where a mainline msm kernel has them (debugfs
|
||||
* `perf_now`, the GPU's devfreq `cur_freq` in Hz) - the paths LinuxRuntime.bindAdrenoStats points
|
||||
* at KGSL's own files when it may - so the same values are fed there too, in the same formats
|
||||
* ([binds]).
|
||||
*/
|
||||
class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
private val feeds = ArrayList<Feed>()
|
||||
|
||||
/** One of MangoHud's files and where its value comes from. */
|
||||
private class Feed(
|
||||
val file: File, val source: String, val read: () -> Long?, val format: String, val percent: Boolean = false,
|
||||
)
|
||||
|
||||
/** Where Valve's msm reader looks, and the feed for it, as host:guest binds. */
|
||||
fun binds(): List<String> {
|
||||
val list = mutableListOf(dir.path + ":" + KGSL)
|
||||
if (File(dir, "perf_now").exists()) list.add(File(dir, "perf_now").path + ":" + MSM_LOAD)
|
||||
if (File(dir, "cur_freq").exists()) list.add(File(dir, "cur_freq").path + ":" + MSM_CLOCK)
|
||||
return list
|
||||
}
|
||||
|
||||
/** Writes the directory; true when it should be bound over [KGSL]. */
|
||||
fun prepare(): Boolean {
|
||||
if (!File(KGSL).exists() || MANGOHUD_FILES.none { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }) return false
|
||||
return try {
|
||||
dir.mkdirs()
|
||||
dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) }
|
||||
feeds.clear()
|
||||
loadFeed()?.let { load ->
|
||||
feeds.add(load)
|
||||
// KGSL's gpu_busy_percentage reads "37 %"; padded after, so a shorter value
|
||||
// written over a longer one leaves no digits behind.
|
||||
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
|
||||
}
|
||||
pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) }?.let { clock ->
|
||||
feeds.add(clock)
|
||||
feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n"))
|
||||
}
|
||||
pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
|
||||
feeds.forEach { feed -> feed.read()?.let { write(feed, it) } }
|
||||
Log.i(TAG, "hud: kgsl stats from the session's own: " + MANGOHUD_FILES.joinToString { name ->
|
||||
"$name " + (feeds.firstOrNull { it.file.name == name }?.source ?: "none")
|
||||
})
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "hud: could not stand in for kgsl stats: $e")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
if (feeds.isEmpty()) return
|
||||
running = true
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
if (!running) break
|
||||
for (feed in feeds) feed.read()?.let { write(feed, it) }
|
||||
}
|
||||
}, "gpu-stats").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
|
||||
/** Load: a file that states it in percent, else KGSL's busy and total of the last sample. */
|
||||
private fun loadFeed(): Feed? {
|
||||
pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }?.let { return it }
|
||||
val gpubusy = "$KGSL/gpubusy"
|
||||
val read = {
|
||||
runCatching {
|
||||
val parts = File(gpubusy).readText().trim().split(Regex("\\s+"))
|
||||
val total = parts[1].toLong()
|
||||
if (total > 0) (parts[0].toLong() * 100 / total).coerceIn(0, 100) else 0L
|
||||
}.getOrNull()
|
||||
}
|
||||
return if (read() != null) Feed(File(dir, "gpu_busy_percentage"), gpubusy, read, "%3d %%\n") else null
|
||||
}
|
||||
|
||||
/** The first of [sources] that reads as a number, its value put in MangoHud's unit by [unit]. */
|
||||
private fun pick(name: String, sources: List<String>, format: String, unit: (Long) -> Long?): Feed? {
|
||||
for (source in sources) {
|
||||
val read = { firstNumber(source)?.let(unit) }
|
||||
if (read() != null) return Feed(File(dir, name), source, read, format)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
|
||||
private fun write(feed: Feed, value: Long) {
|
||||
try {
|
||||
val text = if (feed.percent) String.format(feed.format, "$value %") else String.format(feed.format, value)
|
||||
RandomAccessFile(feed.file, "rw").use { it.seek(0); it.write(text.toByteArray()) }
|
||||
} catch (e: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
const val KGSL = "/sys/class/kgsl/kgsl-3d0"
|
||||
/** Must match LinuxRuntime.bindAdrenoStats. */
|
||||
const val MSM_LOAD = "/sys/kernel/debug/dri/0/perf_now"
|
||||
const val MSM_CLOCK = "/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"
|
||||
private const val PERIOD_MS = 500L
|
||||
private val MANGOHUD_FILES = listOf("gpu_busy_percentage", "clock_mhz", "temp")
|
||||
/** Qualcomm's own GPU summary, beside KGSL in vendor kernels, under the plain sysfs label. */
|
||||
private const val QCOM_GPU = "/sys/kernel/gpu"
|
||||
private val LOAD_SOURCES = listOf(
|
||||
"$KGSL/gpu_busy_percentage", "$KGSL/devfreq/gpu_load", "$KGSL/gpuload", "$QCOM_GPU/gpu_busy",
|
||||
)
|
||||
/** The GPU's devfreq node is named by its register address, which differs between Snapdragons. */
|
||||
private val DEVFREQ_NODES = listOf(
|
||||
"kgsl-3d0", "3d00000.qcom,kgsl-3d0", "2c00000.qcom,kgsl-3d0", "5000000.qcom,kgsl-3d0", "5900000.qcom,kgsl-3d0",
|
||||
)
|
||||
|
||||
private fun clockSources(): List<String> {
|
||||
val sources = mutableListOf(
|
||||
"$KGSL/clock_mhz", "$KGSL/gpu_clock", "$KGSL/gpuclk", "$KGSL/devfreq/cur_freq", "$QCOM_GPU/gpu_clock",
|
||||
)
|
||||
DEVFREQ_NODES.forEach { sources.add("/sys/class/devfreq/$it/cur_freq") }
|
||||
File("/sys/class/devfreq").list()?.sorted()?.forEach { node ->
|
||||
if (node.contains("kgsl") || node.contains("gpu")) sources.add("/sys/class/devfreq/$node/cur_freq")
|
||||
}
|
||||
return sources.distinct()
|
||||
}
|
||||
|
||||
private fun tempSources(): List<String> =
|
||||
listOfNotNull("$KGSL/temp", "$KGSL/devfreq/temp", "$QCOM_GPU/temp", LinuxRuntime.gpuTempSource()).distinct()
|
||||
|
||||
/** The first integer in the file ("550", "37 %", "550000000"), or null. */
|
||||
private fun firstNumber(path: String): Long? =
|
||||
runCatching { Regex("-?\\d+").find(File(path).readText())?.value?.toLong() }.getOrNull()
|
||||
|
||||
/** Hz, kHz or MHz to MHz, as the files differ; a stopped clock reads 0. */
|
||||
private fun mhz(raw: Long): Long? = when {
|
||||
raw < 0 -> null
|
||||
raw > 10_000_000 -> raw / 1_000_000
|
||||
raw > 10_000 -> raw / 1_000
|
||||
else -> raw
|
||||
}
|
||||
|
||||
/** °C or m°C to MangoHud's m°C; nothing a GPU reads at is below 1 °C or above 1000. */
|
||||
private fun milliCelsius(raw: Long): Long? = when {
|
||||
raw <= 0 -> null
|
||||
raw < 1000 -> raw * 1000
|
||||
else -> raw
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
|
||||
/**
|
||||
* The session's `/sys/class/hwmon`, as mangoapp (Deck mode's performance overlay) looks there.
|
||||
*
|
||||
* MangoHud finds a CPU's temperature by an hwmon sensor named `cpuN_thermal`, and an Adreno's
|
||||
* temperature, fan and power by one whose name has `gpuss` in it - a mainline Arm kernel's names.
|
||||
* An Android kernel has neither (its hwmon holds the PMIC's sensors, or nothing), and where the
|
||||
* app may not list hwmon at all the overlay logged an error twice a second. So the overlay showed
|
||||
* no CPU temperature and no fan. This is two sensors named so:
|
||||
*
|
||||
* - `hwmon0` (`cpu0_thermal`): `temp1_input` linked to a CPU thermal zone the app can read;
|
||||
* - `hwmon1` (`gpuss0_thermal`): `temp1_input` linked to the GPU's zone, and `fan1_input` with
|
||||
* the device's fan speed where it has a fan the app can read - an AYN handheld's tachometer
|
||||
* (`/sys/class/gpio5_pwm2/speed`), or a `fan*_input` in the device's own hwmon;
|
||||
* - `hwmon2` (`slg4ax46073v`): the same fan, for Valve's own Qualcomm reader (msm.cpp), which
|
||||
* looks for its fan controller by that name and halves what it reads - that part reports twice
|
||||
* the real speed - so this one holds twice it.
|
||||
*
|
||||
* Nothing in a phone's own hwmon is read by the overlay, so standing in for it loses nothing.
|
||||
*/
|
||||
class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
private var fanSource: String? = null
|
||||
private val fanFile = File(dir, "hwmon1/fan1_input")
|
||||
private val valveFanFile = File(dir, "hwmon2/fan1_input")
|
||||
private var lastRpm = 0L
|
||||
private var lastRpmAt = 0L
|
||||
|
||||
/** Writes the sensors; true when the directory should be bound over `/sys/class/hwmon`. */
|
||||
fun prepare(): Boolean = try {
|
||||
dir.mkdirs()
|
||||
clear(dir)
|
||||
val cpu = LinuxRuntime.cpuTempSource()
|
||||
if (cpu != null) sensor("hwmon0", "cpu0_thermal").also { link(cpu, File(it, "temp1_input")) }
|
||||
val gpu = LinuxRuntime.gpuTempSource()
|
||||
fanSource = FAN_SOURCES().firstOrNull { readNumber(it) != null }
|
||||
if (gpu != null || fanSource != null) {
|
||||
val sensor = sensor("hwmon1", "gpuss0_thermal")
|
||||
if (gpu != null) link(gpu, File(sensor, "temp1_input"))
|
||||
if (fanSource != null) {
|
||||
sensor("hwmon2", "slg4ax46073v")
|
||||
writeFan(sampleFan())
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "hud: hwmon cpu temp ${cpu ?: "none"}, gpu temp ${gpu ?: "none"}, fan ${fanSource ?: "none"}")
|
||||
cpu != null || gpu != null || fanSource != null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "hud: could not write the session's hwmon: $e")
|
||||
false
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
if (fanSource == null) return
|
||||
running = true
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(FAN_PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
// A tachometer read busy-waits 100 ms in the kernel: only while the overlay shows.
|
||||
if (running && OverlayShown.check(root)) writeFan(sampleFan())
|
||||
}
|
||||
}, "hwmon-fan").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
|
||||
/**
|
||||
* The fan's speed in RPM. An AYN tachometer counts pulses over a short window per read and
|
||||
* often catches none, reading 0 while the fan turns; a reading is held until a newer one
|
||||
* comes or [FAN_HOLD_MS] passes with only zeros, when the fan is taken to have stopped.
|
||||
*/
|
||||
private fun sampleFan(): Long {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val rpm = fanSource?.let { readNumber(it) } ?: 0L
|
||||
if (rpm > 0) {
|
||||
lastRpm = rpm
|
||||
lastRpmAt = now
|
||||
} else if (now - lastRpmAt > FAN_HOLD_MS) {
|
||||
lastRpm = 0
|
||||
}
|
||||
return lastRpm
|
||||
}
|
||||
|
||||
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
|
||||
private fun writeFan(rpm: Long) {
|
||||
for ((file, value) in listOf(fanFile to rpm, valveFanFile to rpm * 2)) {
|
||||
try {
|
||||
RandomAccessFile(file, "rw").use { it.seek(0); it.write(String.format("%6d\n", value).toByteArray()) }
|
||||
} catch (e: Exception) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun sensor(name: String, label: String): File =
|
||||
File(dir, name).apply { mkdirs(); File(this, "name").writeText("$label\n") }
|
||||
|
||||
private fun link(target: String, link: File) {
|
||||
java.nio.file.Files.deleteIfExists(link.toPath())
|
||||
Os.symlink(target, link.path)
|
||||
}
|
||||
|
||||
/** Only files and links are made here; deleting a link must not follow it into sysfs. */
|
||||
private fun clear(root: File) {
|
||||
root.listFiles()?.forEach { f ->
|
||||
if (!java.nio.file.Files.isSymbolicLink(f.toPath()) && f.isDirectory) clear(f)
|
||||
java.nio.file.Files.deleteIfExists(f.toPath())
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
/** The AYN tachometer reads 0 if read again within a couple of seconds. */
|
||||
private const val FAN_PERIOD_MS = 3_000L
|
||||
private const val FAN_HOLD_MS = 10_000L
|
||||
|
||||
private val FAN_SOURCES = {
|
||||
val sources = mutableListOf("/sys/class/gpio5_pwm2/speed", "/sys/class/gpio5_pwm/speed")
|
||||
File("/sys/class/hwmon").listFiles()?.sortedBy { it.name }?.forEach { hwmon ->
|
||||
hwmon.listFiles { f -> f.name.matches(Regex("fan\\d+_input")) }?.sortedBy { it.name }
|
||||
?.forEach { sources.add(it.path) }
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
private fun readNumber(path: String): Long? =
|
||||
runCatching { File(path).readText().trim().toLong() }.getOrNull()?.takeIf { it >= 0 }
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Kills every process of this app's uid other than the app itself.
|
||||
* Kills leftover Linux processes owned by this app while preserving live DroidDeck process trees.
|
||||
*
|
||||
* A session is a tree of processes under proot, and proot dies with the app only when the app's
|
||||
* own teardown runs. When the app is killed or crashes instead, the tree stays: proot holding the
|
||||
* rootfs, gamescope holding the GPU, Steam holding its lock file - and the next session never
|
||||
* comes up, or comes up beside a client that is already running. A user on a Thor Pro had to
|
||||
* force-stop the app before every launch. Everything of ours that should be alive between
|
||||
* sessions is inside the app process, so at session start anything else under our uid is a
|
||||
* leftover, and this sweeps it. Each pid is checked by uid at kill time, never by name.
|
||||
*
|
||||
* The one exception is work the app started outside any session and is still waiting on - a
|
||||
* Flatpak install from the store - registered with [keep]: that process and everything under it
|
||||
* are left to finish.
|
||||
* sessions lives in Android processes, so another active session can own Linux children under
|
||||
* the same uid. Those trees are protected by skipping the sweep while a sibling app process is
|
||||
* active. Work started outside a session and still waiting - such as a Flatpak install - is
|
||||
* registered with [keep] and its process tree is spared. Each pid is checked by uid at kill time,
|
||||
* never by name.
|
||||
*/
|
||||
object OrphanReaper {
|
||||
private const val TAG = "OrphanReaper"
|
||||
@@ -27,7 +27,11 @@ object OrphanReaper {
|
||||
|
||||
fun release(pid: Int) { kept.remove(pid) }
|
||||
|
||||
fun reap(reason: String): Int {
|
||||
fun reap(reason: String, context: Context): Int {
|
||||
if (SessionProcess.hasSiblingProcess(context)) {
|
||||
Log.i(TAG, "skipped process sweep while a sibling app process is active - $reason")
|
||||
return 0
|
||||
}
|
||||
val me = android.os.Process.myPid()
|
||||
val uid = android.os.Process.myUid()
|
||||
val spared = descendants(kept)
|
||||
@@ -78,4 +82,5 @@ object OrphanReaper {
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Whether Deck mode's performance overlay is on screen. The client sets its level by rewriting
|
||||
* mangoapp's config (bannerlator-session makes it, `/tmp/mangohud.*`), and `no_display` is the
|
||||
* level that hides it. The feeds whose reads cost something - the fan's tachometer busy-waits in
|
||||
* the kernel, GPU memory walks every process's mappings - only run while it shows.
|
||||
*/
|
||||
object OverlayShown {
|
||||
fun check(root: File): Boolean {
|
||||
val config = File(root, "tmp").listFiles { f -> f.name.startsWith("mangohud.") }
|
||||
?.maxByOrNull { it.lastModified() } ?: return false
|
||||
return runCatching { !config.readText().contains("no_display") }.getOrDefault(false)
|
||||
}
|
||||
}
|
||||
@@ -21,9 +21,8 @@ import java.util.concurrent.atomic.AtomicInteger
|
||||
* is on, what the screen is actually being shown - "60 → 118 fps" is the proof that the engine
|
||||
* is doing something, and "FG starting" or a reason is the proof that it is not.
|
||||
*
|
||||
* The base rate is the game window's own frames, counted here from the compositor's per-frame
|
||||
* callback with or without an engine - what Steam's overlay counts too. The presented rate comes
|
||||
* from the engine's telemetry while it generates.
|
||||
* The base rate is counted here from the compositor's per-frame callback, so it is right with or
|
||||
* without an engine. The presented rate comes from the engine's own telemetry while it generates.
|
||||
*/
|
||||
class PerfHud(context: Context) {
|
||||
/** Empty when the HUD is off or not yet started. */
|
||||
@@ -100,7 +99,10 @@ class PerfHud(context: Context) {
|
||||
return when {
|
||||
problem == 1 -> context.getString(R.string.hud_fg_unsupported, name)
|
||||
problem == 2 -> context.getString(R.string.hud_fg_failed, name)
|
||||
stats != null && stats[3] > 1f -> String.format(Locale.US, "%s %.0f → %.0f fps", label, base, stats[3])
|
||||
stats != null && stats[3] > 1f -> {
|
||||
val source = if (stats[2] > 1f) stats[2] else base
|
||||
String.format(Locale.US, "%s %.0f → %.0f fps", label, source, stats[3])
|
||||
}
|
||||
else -> context.getString(R.string.hud_fg_starting, label, fps(base))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
||||
import java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
|
||||
import java.security.MessageDigest
|
||||
import java.util.Locale
|
||||
|
||||
/** Android shared storage cannot create the links in Wine prefixes or native Steam depots. */
|
||||
object SecondaryLibrary {
|
||||
private val bootstrapTools = linkedMapOf(
|
||||
"4185400" to "SteamLinuxRuntime_4-arm64",
|
||||
"4427310" to "Proton Experimental (ARM64)",
|
||||
"4628740" to "Proton 11.0 (ARM64)",
|
||||
)
|
||||
|
||||
fun privateRoot(files: File, library: File): File {
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray())
|
||||
.joinToString("") { "%02x".format(it.toInt() and 255) }
|
||||
return File(files, "steam-libraries/$digest")
|
||||
}
|
||||
|
||||
/** Parent binds come first; the more specific private directories override them in PRoot. */
|
||||
fun binds(files: File, library: File): List<String> {
|
||||
val private = privateRoot(files, library)
|
||||
val apps = File(library, "steamapps")
|
||||
val tools = LinkedHashMap(bootstrapTools)
|
||||
// Include other installed Proton/runtime versions, without routing ordinary game depots.
|
||||
apps.listFiles()?.filter { it.name.matches(Regex("appmanifest_\\d+\\.acf")) }?.forEach { manifest ->
|
||||
val text = manifest.readText()
|
||||
val id = Regex("\"appid\"\\s+\"(\\d+)\"").find(text)?.groupValues?.get(1)
|
||||
val dir = Regex("\"installdir\"\\s+\"([^\"]+)\"").find(text)?.groupValues?.get(1)
|
||||
if (id != null && dir != null && File(dir).name == dir &&
|
||||
(dir.startsWith("Proton ") || dir.startsWith("SteamLinuxRuntime"))) tools[id] = dir
|
||||
}
|
||||
val overrides = ArrayList<Pair<File, String>>()
|
||||
for (name in listOf("compatdata", "shadercache")) {
|
||||
val target = File(private, "steamapps/$name")
|
||||
migrate(File(apps, name), target)
|
||||
overrides.add(target to "steamapps/$name")
|
||||
}
|
||||
for ((id, dir) in tools) {
|
||||
for (relative in listOf("steamapps/common/$dir", "steamapps/downloading/$id")) {
|
||||
val target = File(private, relative)
|
||||
migrate(File(library, relative), target)
|
||||
// FUSE discarded the executable bits. Steam will restore the depot's exact modes
|
||||
// on verification; its launchers must already be executable when importing it.
|
||||
target.walkTopDown().filter { it.isFile }.forEach { it.setExecutable(true, true) }
|
||||
overrides.add(target to relative)
|
||||
// Steam normalizes depot install directories to lowercase on Android's
|
||||
// case-insensitive shared storage. PRoot binds are case-sensitive, so both
|
||||
// spellings must reach the same private directory during the commit.
|
||||
val lower = relative.lowercase(Locale.ROOT)
|
||||
if (lower != relative) overrides.add(target to lower)
|
||||
}
|
||||
}
|
||||
return listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd").flatMap { guest ->
|
||||
listOf("${library.path}:$guest") + overrides.map { (host, relative) -> "${host.path}:$guest/$relative" }
|
||||
}
|
||||
}
|
||||
|
||||
/** Copy once into a staging directory; retain the source and never merge over a live prefix. */
|
||||
private fun migrate(source: File, target: File) {
|
||||
val migrated = File(target.parentFile, ".${target.name}.migrated")
|
||||
if (target.isDirectory) {
|
||||
if (!migrated.isFile) migrated.writeText(source.canonicalPath)
|
||||
return
|
||||
}
|
||||
check(target.parentFile!!.isDirectory || target.parentFile!!.mkdirs()) { "cannot create ${target.parent}" }
|
||||
if (!source.isDirectory || migrated.isFile) {
|
||||
check(target.mkdirs()) { "cannot create $target" }
|
||||
if (!migrated.isFile) migrated.writeText(source.canonicalPath)
|
||||
return
|
||||
}
|
||||
val stage = File(target.parentFile, "${target.name}.migrating")
|
||||
check(!stage.exists() || stage.deleteRecursively()) { "cannot clear $stage" }
|
||||
check(stage.mkdirs()) { "cannot create $stage" }
|
||||
try {
|
||||
Files.walk(source.toPath()).use { paths ->
|
||||
paths.forEach { path ->
|
||||
val destination = stage.toPath().resolve(source.toPath().relativize(path))
|
||||
if (Files.isDirectory(path, NOFOLLOW_LINKS)) Files.createDirectories(destination)
|
||||
else Files.copy(path, destination, NOFOLLOW_LINKS, COPY_ATTRIBUTES)
|
||||
}
|
||||
}
|
||||
check(stage.renameTo(target)) { "cannot finish migration to $target" }
|
||||
migrated.writeText(source.canonicalPath)
|
||||
} catch (e: Exception) {
|
||||
stage.deleteRecursively()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ object SessionArtifacts {
|
||||
fun scrubOlder(context: Context) {
|
||||
val current = SessionPaths.current()
|
||||
val dirs = LinuxRuntime.debugLogDir().listFiles { f ->
|
||||
SessionPaths.isSessionFolder(f) && f != current && !File(f, SCRUBBED_MARKER).exists()
|
||||
f.isDirectory && f.name.startsWith("session-") && f != current && !File(f, SCRUBBED_MARKER).exists()
|
||||
} ?: return
|
||||
if (dirs.isEmpty()) return
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
@@ -124,8 +124,8 @@ object SessionArtifacts {
|
||||
fun finishAbandoned(context: Context) {
|
||||
val parent = LinuxRuntime.debugLogDir()
|
||||
val abandoned = parent.listFiles { f ->
|
||||
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists()
|
||||
}?.sortedWith(SessionPaths.chronological) ?: return
|
||||
f.isDirectory && f.name.startsWith("session-") && !File(f, COMPLETE_MARKER).exists()
|
||||
}?.sortedBy { it.name } ?: return
|
||||
if (abandoned.isEmpty()) return
|
||||
val current = SessionPaths.current()
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
@@ -157,37 +157,5 @@ object SessionArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the newest [SessionPaths.KEEP_SESSIONS] session folders and deletes the rest: a few
|
||||
* days of testing left hundreds, and the one a report needed was lost among them. Only folders
|
||||
* that are finished; the session in progress is never touched. Runs at app start after
|
||||
* [finishAbandoned], on its worker thread.
|
||||
*/
|
||||
@Synchronized
|
||||
fun prune(context: Context) {
|
||||
val current = SessionPaths.current()
|
||||
val finished = SessionPaths.sessionFolders(context).filter { it != current && File(it, COMPLETE_MARKER).exists() }
|
||||
val old = finished.dropLast(SessionPaths.KEEP_SESSIONS)
|
||||
old.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
|
||||
if (old.isNotEmpty()) Log.i(TAG, "deleted ${old.size} session folder(s) past the newest ${SessionPaths.KEEP_SESSIONS}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Every session folder but the one in progress, and the one-off command logs (tools/, or loose
|
||||
* beside the folders from before it): the Setup page's Clear logs. Returns how many session
|
||||
* folders went.
|
||||
*/
|
||||
@Synchronized
|
||||
fun clearAll(context: Context): Int {
|
||||
val current = SessionPaths.current()
|
||||
val gone = SessionPaths.sessionFolders(context).filter { it != current }
|
||||
gone.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
|
||||
com.droiddeck.launcher.core.FileUtils.delete(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR))
|
||||
// Before tools/, those logs sat loose beside the session folders.
|
||||
LinuxRuntime.debugLogDir().listFiles { f -> f.isFile && f.name.endsWith(".log") }?.forEach { it.delete() }
|
||||
Log.i(TAG, "cleared ${gone.size} session folder(s)")
|
||||
return gone.size
|
||||
}
|
||||
|
||||
private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
}
|
||||
@@ -11,12 +11,11 @@ object SessionEvents {
|
||||
private const val TAG = "SessionEvents"
|
||||
private val lock = Any()
|
||||
|
||||
/** [label] names the session's folder for what is being run (SessionPaths.label). */
|
||||
fun begin(context: Context, mode: String, label: String? = null) {
|
||||
fun begin(context: Context, mode: String) {
|
||||
// A runtime-install failure can leave the folder claimed before the service ever starts.
|
||||
// Keep that folder, but give the next attempt its own session directory.
|
||||
SessionPaths.take()
|
||||
val dir = SessionPaths.beginOrCurrent(context, label ?: SessionPaths.label(mode, null))
|
||||
val dir = SessionPaths.beginOrCurrent(context)
|
||||
synchronized(SessionState) {
|
||||
SessionState.phase = SessionPhase.PREPARING
|
||||
SessionState.mode = mode
|
||||
|
||||
@@ -5,7 +5,6 @@ import android.os.Environment
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import java.io.File
|
||||
|
||||
/** Everything the session needs written into the runtime before it starts. */
|
||||
@@ -30,7 +29,6 @@ object SessionFiles {
|
||||
"usr/local/bin/bannerlator-game-env" to "usr/local/bin/bannerlator-game-env",
|
||||
"libblsession.so" to "usr/local/lib/libblsession.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
|
||||
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
|
||||
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
|
||||
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
|
||||
@@ -44,8 +42,6 @@ object SessionFiles {
|
||||
"usr/local/bin/bannerlator-steam-shortcuts" to "usr/local/bin/bannerlator-steam-shortcuts",
|
||||
"usr/local/bin/bannerlator-steam-games" to "usr/local/bin/bannerlator-steam-games",
|
||||
"usr/local/bin/bannerlator-pad-defaults" to "usr/local/bin/bannerlator-pad-defaults",
|
||||
// GOG: the store's wrapper around Heroic's gogdl (which the app downloads itself).
|
||||
"usr/local/bin/bannerlator-gog" to "usr/local/bin/bannerlator-gog",
|
||||
// Flatpak: the bwrap stand-in, the store's helper and setup, and the front end's launcher.
|
||||
"usr/local/bin/bannerlator-bwrap" to "usr/local/bin/bannerlator-bwrap",
|
||||
"usr/local/bin/bannerlator-flatpak" to "usr/local/bin/bannerlator-flatpak",
|
||||
@@ -73,6 +69,13 @@ object SessionFiles {
|
||||
// staging them into a runtime without it would make the desktop look present when it is not.
|
||||
val desktop = arrayOf(
|
||||
"usr/local/bin/droiddeck-desktop" to "usr/local/bin/droiddeck-desktop",
|
||||
"usr/local/bin/droiddeck-plasma-mobile" to "usr/local/bin/droiddeck-plasma-mobile",
|
||||
// Plasma Mobile 6.7.5 backports: populate the Folio app catalog without a Wayland
|
||||
// connection handle and reset the native mobile task switcher's gesture state.
|
||||
"usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so" to "usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so",
|
||||
"usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so" to "usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so",
|
||||
"usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml" to "usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml",
|
||||
"usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml" to "usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml",
|
||||
// Games and emulators from the menu, full screen in a gamescope of their own.
|
||||
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
|
||||
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
|
||||
@@ -155,9 +158,6 @@ object SessionFiles {
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
// Last, so the others' opens and stats reach it through RTLD_NEXT. It stays idle in any
|
||||
// process its proot did not describe to it (ProotFastPath).
|
||||
if (ProotFastPath.enabled(context)) preload.append(ProotFastPath.LIBRARY + "\n")
|
||||
val etc = File(root, "etc").apply { mkdirs() }
|
||||
val staged = File(etc, "ld.so.preload.staged")
|
||||
if (!FileUtils.writeString(staged, preload.toString())
|
||||
|
||||
@@ -17,7 +17,10 @@ import java.util.zip.ZipOutputStream
|
||||
*/
|
||||
object SessionLogShare {
|
||||
/** The newest session folder in either place logs are written, or null if there is none. */
|
||||
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
|
||||
fun latest(context: Context): File? =
|
||||
listOf(LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
|
||||
.flatMap { dir -> dir.listFiles { f -> f.isDirectory && f.name.startsWith("session-") }?.toList() ?: emptyList() }
|
||||
.maxByOrNull { it.name }
|
||||
|
||||
/** Builds the zip (blocking). Returns null when there is no session to share. */
|
||||
fun zipLatest(context: Context): File? = latest(context)?.let { zipFolder(context, it) }
|
||||
@@ -33,40 +36,21 @@ object SessionLogShare {
|
||||
// session pass yet, and the redactor changes nothing in a line that is already clean.
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { z ->
|
||||
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f) }
|
||||
liveSteamLogs(context, folder).forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f) }
|
||||
files.forEach { f ->
|
||||
z.putNextEntry(ZipEntry(folder.name + "/" + f.relativeTo(folder).path))
|
||||
if (LogRedactor.isText(f)) {
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubTo(f, w)
|
||||
w.flush()
|
||||
} else {
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
}
|
||||
z.closeEntry()
|
||||
}
|
||||
}
|
||||
return zip
|
||||
}
|
||||
|
||||
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
|
||||
z.putNextEntry(ZipEntry(name))
|
||||
if (LogRedactor.isText(f)) {
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubTo(f, w)
|
||||
w.flush()
|
||||
} else {
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
}
|
||||
z.closeEntry()
|
||||
}
|
||||
|
||||
/**
|
||||
* The client's own logs as they stand, for a session shared while it runs. The session script
|
||||
* copies them into steam/ only as it exits, so a zip made from the drawer had none - and
|
||||
* controller.txt (which pad the client opened, the touch mode it set) is what a controller or
|
||||
* touch report needs most. Only for the running session: an older folder would get this
|
||||
* session's logs. The same files the script copies; nothing holding credentials is in logs/.
|
||||
*/
|
||||
private fun liveSteamLogs(context: Context, folder: File): List<File> {
|
||||
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
|
||||
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
|
||||
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
|
||||
}
|
||||
|
||||
/** The client's content and bootstrap logs grow large over months and say nothing about a session. */
|
||||
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
|
||||
|
||||
fun shareIntent(context: Context, zip: File): Intent {
|
||||
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", zip)
|
||||
val send = Intent(Intent.ACTION_SEND)
|
||||
|
||||
@@ -8,24 +8,18 @@ import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded,
|
||||
* named for the day, that day's session number and what was run, so the one a report is about can
|
||||
* be picked out without opening any:
|
||||
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded:
|
||||
*
|
||||
* ```
|
||||
* Download/DroidDeck/2026-09-30-03-steam/
|
||||
* Download/DroidDeck/session-20260921-161256/
|
||||
* device.txt what this device is, and every setting the session ran with
|
||||
* session.log the guest session: proot, gamescope, the client's stdout
|
||||
* wayland.log the app's compositor
|
||||
* steam.log the Steam client's own log, scrubbed (Steam mode)
|
||||
* steam/ the rest of the client's logs, scrubbed (Steam mode)
|
||||
* desktop.log labwc, the panel and the programs on it (desktop mode)
|
||||
* Download/DroidDeck/tools/ one-off commands: Flatpak installs, AppImage imports
|
||||
* ```
|
||||
*
|
||||
* Folders from before this naming (`session-20260930-180642`) are still recognised, shared and
|
||||
* pruned with the rest.
|
||||
*
|
||||
* The folder is claimed by whoever starts first - the activity starts the compositor before the
|
||||
* service starts the session - so both write into the same one, and a recreated activity (a
|
||||
* foldable opening mid-session) joins the folder in progress instead of opening another.
|
||||
@@ -33,44 +27,25 @@ 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 scope = if (SessionProcess.isExternalDisplay(context)) "external-" else ""
|
||||
val baseName = "session-$scope$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 +54,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 +61,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 +79,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
|
||||
@@ -302,17 +296,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the session's path lookups take proot's fast path (ProotFastPath): answered inside
|
||||
* each process instead of a round trip through the tracer. On by default; it needs proot's
|
||||
* seccomp filter, so it is off whenever proot runs without one.
|
||||
*/
|
||||
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
|
||||
|
||||
fun setProotFastPath(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("prootFastPath", on).apply()
|
||||
}
|
||||
|
||||
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
|
||||
|
||||
@JvmStatic
|
||||
@@ -569,6 +552,25 @@ object SessionPrefs {
|
||||
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-renderer-failed").delete()
|
||||
}
|
||||
|
||||
const val DESKTOP_ENV_LXQT = "lxqt"
|
||||
const val DESKTOP_ENV_PLASMA_MOBILE = "plasma-mobile"
|
||||
val desktopEnvironmentChoices = listOf(
|
||||
DESKTOP_ENV_LXQT to "LXQt",
|
||||
DESKTOP_ENV_PLASMA_MOBILE to "KDE Plasma Mobile",
|
||||
)
|
||||
|
||||
/** Shell used when the user opens the primary Desktop button. LXQt remains the default. */
|
||||
fun desktopEnvironment(context: Context): String =
|
||||
prefs(context).getString("desktopEnvironment", DESKTOP_ENV_LXQT)
|
||||
?.takeIf { value -> desktopEnvironmentChoices.any { it.first == value } }
|
||||
?: DESKTOP_ENV_LXQT
|
||||
|
||||
fun setDesktopEnvironment(context: Context, environment: String) {
|
||||
val value = environment.takeIf { candidate -> desktopEnvironmentChoices.any { it.first == candidate } }
|
||||
?: DESKTOP_ENV_LXQT
|
||||
prefs(context).edit().putString("desktopEnvironment", value).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* HDR10 output for MODE_STEAM / MODE_DESKTOP. Off by default. Honoured only when the panel
|
||||
* lists HDR10 (HdrSupport), and decided when the compositor starts, which is once per app
|
||||
@@ -600,7 +602,11 @@ object SessionPrefs {
|
||||
* The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a
|
||||
* fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices.
|
||||
*/
|
||||
fun prefMode(mode: String): String = if (mode == SessionService.MODE_RUN) SessionService.MODE_STEAM else mode
|
||||
fun prefMode(mode: String): String = when (mode) {
|
||||
SessionService.MODE_RUN -> SessionService.MODE_STEAM
|
||||
SessionService.MODE_PLASMA_MOBILE -> SessionService.MODE_DESKTOP
|
||||
else -> mode
|
||||
}
|
||||
|
||||
fun suspendPolicy(context: Context, mode: String): String =
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.channels.FileLock
|
||||
import java.nio.channels.OverlappingFileLockException
|
||||
|
||||
/** Identifies the dedicated Android process used to host a second-display Linux session. */
|
||||
object SessionProcess {
|
||||
private const val TAG = "SessionProcess"
|
||||
private const val SECONDARY_SUFFIX = ":externalDisplay"
|
||||
private const val MAIN_SESSION_LOCK = ".droiddeck-main-session.lock"
|
||||
private const val EXTERNAL_SESSION_LOCK = ".droiddeck-external-session.lock"
|
||||
|
||||
@Volatile private var heldLock: FileLock? = null
|
||||
@Volatile private var heldLockFile: RandomAccessFile? = null
|
||||
|
||||
fun isExternalDisplay(context: Context): Boolean = processName(context) == context.packageName + SECONDARY_SUFFIX
|
||||
|
||||
/**
|
||||
* Keeps the sibling session discoverable even when Android restricts cross-process /proc
|
||||
* reads. The service holds this process-specific file lock for the whole Linux session.
|
||||
*/
|
||||
@Synchronized
|
||||
fun acquireSessionLock(context: Context): Boolean {
|
||||
if (heldLock?.isValid == true) return true
|
||||
val path = File(context.filesDir, ownLockName(context))
|
||||
val file = RandomAccessFile(path, "rw")
|
||||
val lock = try {
|
||||
file.channel.tryLock()
|
||||
} catch (e: OverlappingFileLockException) {
|
||||
Log.w(TAG, "another session process already owns ${path.path}", e)
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not lock ${path.path}", e)
|
||||
null
|
||||
}
|
||||
if (lock == null) {
|
||||
file.close()
|
||||
return false
|
||||
}
|
||||
heldLockFile = file
|
||||
heldLock = lock
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun releaseSessionLock() {
|
||||
try {
|
||||
heldLock?.release()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not release the session lock", e)
|
||||
}
|
||||
try {
|
||||
heldLockFile?.close()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not close the session lock file", e)
|
||||
}
|
||||
heldLock = null
|
||||
heldLockFile = null
|
||||
}
|
||||
|
||||
/** A sibling lock means its guest process tree must not be swept as an orphan. */
|
||||
fun hasSiblingSession(context: Context): Boolean = isLocked(File(context.filesDir, siblingLockName(context)))
|
||||
|
||||
/** Includes an idle app process during display handoff, so legacy name-based sweeps stay safe. */
|
||||
fun hasSiblingProcess(context: Context): Boolean {
|
||||
if (hasSiblingSession(context)) return true
|
||||
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager ?: return true
|
||||
val processes = try {
|
||||
manager.runningAppProcesses ?: return true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not inspect sibling app processes; skipping cleanup", e)
|
||||
return true
|
||||
}
|
||||
return processes.any { process ->
|
||||
process.pid != android.os.Process.myPid() &&
|
||||
(process.processName == context.packageName || process.processName.startsWith(context.packageName + ":"))
|
||||
}
|
||||
}
|
||||
|
||||
private fun isLocked(file: File): Boolean {
|
||||
val probe = try {
|
||||
RandomAccessFile(file, "rw")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not inspect sibling session lock ${file.path}; skipping cleanup", e)
|
||||
return true
|
||||
}
|
||||
return try {
|
||||
val lock = probe.channel.tryLock()
|
||||
if (lock == null) true else {
|
||||
lock.release()
|
||||
false
|
||||
}
|
||||
} catch (_: OverlappingFileLockException) {
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not inspect sibling session lock ${file.path}; skipping cleanup", e)
|
||||
true
|
||||
} finally {
|
||||
try { probe.close() } catch (_: Exception) { }
|
||||
}
|
||||
}
|
||||
|
||||
private fun ownLockName(context: Context): String =
|
||||
if (isExternalDisplay(context)) EXTERNAL_SESSION_LOCK else MAIN_SESSION_LOCK
|
||||
|
||||
private fun siblingLockName(context: Context): String =
|
||||
if (isExternalDisplay(context)) MAIN_SESSION_LOCK else EXTERNAL_SESSION_LOCK
|
||||
|
||||
private fun processName(context: Context): String =
|
||||
if (Build.VERSION.SDK_INT >= 28) Application.getProcessName() else readCommandLine(android.os.Process.myPid())
|
||||
|
||||
private fun readCommandLine(pid: Int): String = try {
|
||||
File("/proc/$pid/cmdline").readText().substringBefore('\u0000')
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import android.os.PowerManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.SessionActivity
|
||||
import com.droiddeck.launcher.ExternalSessionActivity
|
||||
import com.droiddeck.launcher.audio.DirectAudioRelayComponent
|
||||
import com.droiddeck.launcher.audio.PulseAudioComponent
|
||||
import com.droiddeck.launcher.core.CpuCores
|
||||
@@ -36,7 +37,6 @@ import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.input.FakeInputWriter
|
||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
@@ -57,7 +57,7 @@ import java.util.Locale
|
||||
*
|
||||
* The activity comes and goes on top of this; see [com.droiddeck.launcher.wayland.CompositorHost].
|
||||
*/
|
||||
class SessionService : Service() {
|
||||
open class SessionService : Service() {
|
||||
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
|
||||
/** The Steam Deck controller's sysfs binds (SteamDeckPad), when this session has one. */
|
||||
private var deckBinds: List<String> = emptyList()
|
||||
@@ -165,14 +165,14 @@ class SessionService : Service() {
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
}
|
||||
startForeground(NOTIFICATION_ID, buildNotification())
|
||||
if (!SessionState.running) SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
|
||||
startForeground(notificationId(), buildNotification())
|
||||
if (SessionState.running) return START_NOT_STICKY
|
||||
if (SessionState.stopRequested) {
|
||||
SessionState.running = true
|
||||
stopSession(0)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
activityVisible = true
|
||||
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true
|
||||
@@ -201,12 +201,21 @@ class SessionService : Service() {
|
||||
// replaces can report its own exit in the gap between the two, and that exit must not
|
||||
// be taken as this one's.
|
||||
val gen = ++sessionGen
|
||||
if (!SessionProcess.acquireSessionLock(this)) {
|
||||
SessionState.running = false
|
||||
Log.e(TAG, "another ${if (SessionProcess.isExternalDisplay(this)) "external" else "handheld"} session already owns its process lock")
|
||||
SessionEvents.fail("SESSION_ALREADY_RUNNING", "Another DroidDeck session is already running", -1)
|
||||
SessionState.notifyEnded(-1)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
acquireLocks()
|
||||
Thread({
|
||||
// A tree the last session left behind (the app was killed or crashed, so its teardown
|
||||
// never ran) would hold the rootfs, the GPU and Steam's lock: nothing of ours should
|
||||
// be alive between sessions outside this process.
|
||||
OrphanReaper.reap("session starting")
|
||||
OrphanReaper.reap("session starting", this)
|
||||
runSession(gen)
|
||||
}, "session-start").start()
|
||||
// The activity or the notification stops us; the system must not resurrect a session whose
|
||||
@@ -231,6 +240,26 @@ class SessionService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun readPlasmaShellPid(directory: File?): Int {
|
||||
val pidFile = directory?.let { File(it, "plasma-shell.pid") } ?: return -1
|
||||
return runCatching { pidFile.readText().trim().toInt() }.getOrDefault(-1)
|
||||
}
|
||||
|
||||
/** Plasma can outlive KWin when PRoot tears down, so stop this session's recorded shell. */
|
||||
private fun stopPlasmaShell(pid: Int, directory: File?) {
|
||||
if (pid < 2 || directory == null) return
|
||||
val proc = File("/proc/$pid")
|
||||
val command = runCatching {
|
||||
File(proc, "cmdline").readBytes().toString(Charsets.UTF_8).replace('\u0000', ' ')
|
||||
}.getOrDefault("")
|
||||
val environment = runCatching {
|
||||
File(proc, "environ").readBytes().toString(Charsets.UTF_8)
|
||||
}.getOrDefault("")
|
||||
if (!command.contains("plasmashell") || !environment.contains(directory.name)) return
|
||||
android.os.Process.killProcess(pid)
|
||||
Log.i(TAG, "stopped Plasma Mobile shell process $pid")
|
||||
}
|
||||
|
||||
private fun extraEnv(): List<String> {
|
||||
val file = File(Environment.getExternalStorageDirectory(), ENV_SWITCH).takeIf { it.isFile } ?: return emptyList()
|
||||
val lines = FileUtils.readString(file)?.lines().orEmpty()
|
||||
@@ -254,18 +283,27 @@ class SessionService : Service() {
|
||||
|
||||
private fun runSession(gen: Int) {
|
||||
SessionTerminal.clear()
|
||||
val externalDisplay = SessionProcess.isExternalDisplay(this)
|
||||
val plasmaDesktop = externalDisplay || SessionState.mode == MODE_PLASMA_MOBILE ||
|
||||
(SessionState.mode == MODE_DESKTOP &&
|
||||
SessionPrefs.desktopEnvironment(this) == SessionPrefs.DESKTOP_ENV_PLASMA_MOBILE)
|
||||
val root = if (plasmaDesktop) LinuxRuntime.plasmaRootDir(this) else LinuxRuntime.rootDir(this)
|
||||
if (plasmaDesktop && !com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this)) {
|
||||
Log.e(TAG, "Plasma Mobile's isolated runtime is not installed or is out of date")
|
||||
stopSession(-1)
|
||||
return
|
||||
}
|
||||
try {
|
||||
LinuxRuntime.writeAccounts(this)
|
||||
LinuxRuntime.writeAccounts(this, root)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not write the guest's passwd/group", e)
|
||||
stopSession(-1)
|
||||
return
|
||||
}
|
||||
|
||||
val root = LinuxRuntime.rootDir(this)
|
||||
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
val sessionRoot = LinuxRuntime.sessionRoot(this, externalDisplay).apply { mkdirs() }
|
||||
val runtimeDir = File(filesDir, if (externalDisplay) ".wayland-rt-external-display" else ".wayland-rt").apply { mkdirs() }
|
||||
if (!SessionProcess.hasSiblingProcess(this)) killStragglers()
|
||||
SessionFiles.stage(this, root)
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
@@ -278,14 +316,17 @@ class SessionService : Service() {
|
||||
// The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the
|
||||
// same set-up as a Steam session: it gets what the client and its games are started with.
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
addClientEnvironment(guest, steamHere)
|
||||
// Where the fast path's description of proot's view goes, once the binds are known.
|
||||
val fastPathAt = guest.size
|
||||
addClientEnvironment(guest, runtimeDir, steamHere, root)
|
||||
|
||||
val pulse = startAudio(guest, sessionDir)
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
guest.add("BL_DESKTOP_ENV=" + SessionPrefs.desktopEnvironment(this))
|
||||
} else if (SessionState.mode == MODE_PLASMA_MOBILE) {
|
||||
guest.add("BL_DESKTOP_ENV=" + SessionPrefs.DESKTOP_ENV_PLASMA_MOBILE)
|
||||
}
|
||||
if (SessionState.hdr) {
|
||||
// The activity opened the compositor's HDR gate: gamescope offers HDR to its clients
|
||||
// and DXVK takes the HDR10 swapchain when a game asks for one.
|
||||
@@ -302,7 +343,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
|
||||
@@ -363,25 +404,12 @@ class SessionService : Service() {
|
||||
|
||||
// Android has no /dev/shm; the cache stands in for it and, unlike the real thing, keeps
|
||||
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
|
||||
FileUtils.clear(File(cacheDir, "shm"))
|
||||
FileUtils.clear(File(cacheDir, if (externalDisplay) "shm-external-display" else "shm"))
|
||||
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir)
|
||||
// The fast path is told exactly the rootfs and binds proot is given (ProotFastPath).
|
||||
val fastPathKey = if (ProotFastPath.enabled(this)) {
|
||||
val prootBinds = LinuxRuntime.binds(
|
||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds,
|
||||
)
|
||||
val root = LinuxRuntime.rootDir(this)
|
||||
ProotFastPath.key(root, prootBinds)?.also { key ->
|
||||
val env = ProotFastPath.guestEnv(root, prootBinds, key)
|
||||
guest.addAll(fastPathAt, env)
|
||||
shellGuest.addAll(fastPathAt, env)
|
||||
Log.i(TAG, "proot: fast path on (${prootBinds.size} binds)")
|
||||
}
|
||||
} else null
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir, root, externalDisplay)
|
||||
|
||||
val command = LinuxRuntime.command(
|
||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
|
||||
val command = LinuxRuntime.commandForRoot(
|
||||
this, root, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
|
||||
)
|
||||
|
||||
val hostEnv = HostEnvironment()
|
||||
@@ -395,12 +423,11 @@ class SessionService : Service() {
|
||||
hostEnv["PROOT_NO_SECCOMP"] = "1"
|
||||
Log.i(TAG, "proot: seccomp acceleration off by request")
|
||||
}
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } }
|
||||
val prootLibs = LinuxRuntime.prootLibraryPath(this)
|
||||
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
|
||||
|
||||
val terminalCommand = LinuxRuntime.command(
|
||||
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
|
||||
val terminalCommand = LinuxRuntime.commandForRoot(
|
||||
this, root, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
|
||||
)
|
||||
val terminalHostEnvironment = LinkedHashMap(System.getenv())
|
||||
hostEnv.asArray().forEach { entry ->
|
||||
@@ -500,7 +527,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
/** The guest's base environment: paths, the display, the GL/Vulkan stack and the client's switches. */
|
||||
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean) {
|
||||
private fun addClientEnvironment(guest: MutableList<String>, runtimeDir: File, steamHere: Boolean, root: File) {
|
||||
guest.add("/usr/bin/env")
|
||||
guest.add("-i")
|
||||
guest.add("HOME=/root")
|
||||
@@ -511,7 +538,7 @@ class SessionService : Service() {
|
||||
// Without this the session is UTC: the client's clock, its logs and every timestamp in a
|
||||
// session bundle sit hours off the device's. Bannerlator carries the same line.
|
||||
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
|
||||
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
|
||||
guest.add("XDG_RUNTIME_DIR=" + runtimeDir.path)
|
||||
guest.add("XDG_SESSION_TYPE=wayland")
|
||||
guest.add("WAYLAND_DISPLAY=wayland-0")
|
||||
guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1")
|
||||
@@ -519,7 +546,7 @@ class SessionService : Service() {
|
||||
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
|
||||
guest.add("GALLIUM_DRIVER=zink")
|
||||
guest.add("LIBGL_KOPPER_DRI2=true")
|
||||
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
LinuxRuntime.vulkanIcd(root)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
// An imported glibc Turnip, when one is set (by the user, or by Auto): the session script
|
||||
// checks the manifest and its library from inside and points the loader at it with
|
||||
// VK_DRIVER_FILES, so the runtime's own driver above stays untouched and is what a bad
|
||||
@@ -552,16 +579,11 @@ class SessionService : Service() {
|
||||
// opened once and read and written with pread/pwrite, which proot never sees. Mesa removes
|
||||
// the old folder itself once it has gone a week untouched.
|
||||
guest.add("MESA_DISK_CACHE_DATABASE=1")
|
||||
// glibc's per-thread rseq registration is refused by Android's app seccomp policy, so
|
||||
// every thread start paid a SIGSYS that proot answers; the malloc top pad grows the heap
|
||||
// 16 MB at a time instead of 128 KB, and every brk(2) is a proot stop too.
|
||||
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
||||
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
|
||||
if (SessionState.mode == MODE_STEAM) {
|
||||
guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0"))
|
||||
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
|
||||
SessionPrefs.writeForceFullscreenFlag(this)
|
||||
}
|
||||
// Proton's own gate for its xalia helper (its `proton` script reads this, and sets
|
||||
@@ -598,7 +620,7 @@ class SessionService : Service() {
|
||||
// top, and the helper only opens an input stream when asked - so a user who wants game
|
||||
// sound but no recording gets exactly that, and Android's recording indicator stays off.
|
||||
val wantsDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.directAudio(this)
|
||||
val wantsMic = SessionPrefs.micEnabled(this) &&
|
||||
val wantsMic = SessionState.mode == MODE_STEAM && SessionPrefs.micEnabled(this) &&
|
||||
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
// Both paths sit under the app's files directory, which the session binds at its own path,
|
||||
// so the same string is valid on both sides and nothing has to be translated.
|
||||
@@ -638,7 +660,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
/** The fake evdev pads: the ring files the app writes and the identity SDL and Steam see. */
|
||||
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File, sessionDir: File) {
|
||||
private fun addControllerEnvironment(guest: MutableList<String>, fakeInputDir: File) {
|
||||
FakeInputWriter.prepareRingSlots(fakeInputDir, 4)
|
||||
// Virtual pads a client made last session (event16 and up, and their hidden rings) are
|
||||
// not there any more; a client that crashed never took its own down.
|
||||
@@ -664,15 +686,11 @@ class SessionService : Service() {
|
||||
deckBinds = if (wantsDeck) SteamDeckPad.prepare(this, fakeInputDir.parentFile!!.parentFile!!) else emptyList()
|
||||
SessionState.deckPad = deckBinds.isNotEmpty()
|
||||
if (wantsDeck && !SessionState.deckPad) Log.w(TAG, "deck pad: not available this session; the pad stays an Xbox 360 controller")
|
||||
logControllersAtStart()
|
||||
if (uinput) {
|
||||
// /dev/uinput, stood in for by libfakeinput: the virtual pad Steam Input makes for a
|
||||
// game becomes a node the game reads, carrying the player's layout, as on a Deck.
|
||||
guest.add("FAKE_EVDEV_UINPUT=1")
|
||||
if (SessionState.deckPad) {
|
||||
guest.add("FAKE_EVDEV_DECK=1")
|
||||
guest.add("FAKE_DECK_SYSFS_LISTING=" + SteamDeckPad.listingDir(fakeInputDir.parentFile!!.parentFile!!).path)
|
||||
}
|
||||
if (SessionState.deckPad) guest.add("FAKE_EVDEV_DECK=1")
|
||||
} else if (SessionState.mode == MODE_STEAM) {
|
||||
// Without it, games see the pad itself wearing Steam Input's virtual-gamepad identity -
|
||||
// for games the client starts only. Everywhere else (the desktop, a program from the
|
||||
@@ -685,16 +703,14 @@ 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
|
||||
}
|
||||
|
||||
/** What proot binds into the guest: the pads, the battery, storage, the game library, added games and ROMs. */
|
||||
private fun sessionBinds(controllersOn: Boolean, fakeInputDir: File): ArrayList<String> {
|
||||
private fun sessionBinds(controllersOn: Boolean, fakeInputDir: File, root: File, externalDisplay: Boolean): ArrayList<String> {
|
||||
val binds = ArrayList<String>()
|
||||
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
||||
if (controllersOn) binds.addAll(deckBinds)
|
||||
@@ -702,41 +718,10 @@ class SessionService : Service() {
|
||||
// /sys/class/power_supply/BAT<n>/..., a laptop's or a Deck's naming; Android's supply is
|
||||
// called "battery" and its files differ, so the client sees no battery at all. A directory
|
||||
// of our own, written from Android's battery API every few seconds, is bound over it.
|
||||
// Steam's time estimates come from /run/vpower instead, written straight into the rootfs.
|
||||
val battery = BatteryComponent(
|
||||
File(filesDir, "session/sys/power_supply"),
|
||||
File(LinuxRuntime.rootDir(this), "run/vpower"),
|
||||
)
|
||||
val battery = BatteryComponent(File(filesDir, "session/sys/power_supply"))
|
||||
battery.attach(this)
|
||||
components.add(battery)
|
||||
binds.add(battery.dir.path + ":/sys/class/power_supply")
|
||||
// The overlay's CPU and GPU temperatures and the fan, as hwmon sensors it knows by name.
|
||||
val hwmon = HwmonComponent(File(filesDir, "session/sys/hwmon"), LinuxRuntime.rootDir(this))
|
||||
if (hwmon.prepare()) {
|
||||
hwmon.attach(this)
|
||||
components.add(hwmon)
|
||||
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
|
||||
}
|
||||
// CPU load for everything in the session that reads /proc/stat, the overlay among them.
|
||||
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
|
||||
if (cpuStat.prepare()) {
|
||||
cpuStat.attach(this)
|
||||
components.add(cpuStat)
|
||||
binds.add(cpuStat.file.path + ":/proc/stat")
|
||||
}
|
||||
// The GPU memory in use for the overlay's VRAM lines, which it would read from tracefs.
|
||||
val gpuMem = GpuMemComponent(File(LinuxRuntime.rootDir(this), "run/droiddeck-hud/gpu-mem"), LinuxRuntime.rootDir(this))
|
||||
if (gpuMem.prepare()) {
|
||||
gpuMem.attach(this)
|
||||
components.add(gpuMem)
|
||||
}
|
||||
// The GPU's load and temperature for the performance overlay, where KGSL's sysfs is refused.
|
||||
val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"))
|
||||
if (gpuStats.prepare()) {
|
||||
gpuStats.attach(this)
|
||||
components.add(gpuStats)
|
||||
binds.addAll(gpuStats.binds())
|
||||
}
|
||||
// Rumble for the on-screen pad: the fake evdev layer sends force-feedback effects to this
|
||||
// listener, which drives the phone's vibrator (see RumbleComponent).
|
||||
if (controllersOn) components.add(RumbleComponent().also { it.attach(this) })
|
||||
@@ -746,8 +731,10 @@ class SessionService : Service() {
|
||||
// tree and could not find the phone at all. The same storage is placed under home as
|
||||
// well, and the ROMs folder chosen on the main screen beside it; a bind rather than a
|
||||
// link, so a folder on an SD card works the same.
|
||||
val home = File(LinuxRuntime.rootDir(this), "root")
|
||||
val home = if (externalDisplay) File(filesDir, "plasma-mobile-home") else File(root, "root")
|
||||
home.mkdirs()
|
||||
File(home, "Storage").mkdirs()
|
||||
if (externalDisplay) binds.add("${home.path}:/root")
|
||||
binds.add(Environment.getExternalStorageDirectory().path + ":/root/Storage")
|
||||
// A second Steam library: the storage chosen in the Steam cog, at the path the runtime's
|
||||
// bannerlator-steam-library registers with the client. Nothing bound = the script removes
|
||||
@@ -756,15 +743,12 @@ class SessionService : Service() {
|
||||
if (library != null) {
|
||||
val problem = GameStorage.prepare(library.path)
|
||||
if (problem == null) {
|
||||
File(LinuxRuntime.rootDir(this), "mnt/droiddeck-sd").mkdirs()
|
||||
File(root, "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()
|
||||
try {
|
||||
binds.addAll(SecondaryLibrary.binds(filesDir, File(library.path)))
|
||||
Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\"); prefixes and native tools private")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "game storage: private directories could not be prepared; internal only this session", e)
|
||||
}
|
||||
File(root, "mnt/bannerlator-sd").mkdirs()
|
||||
binds.add("${library.path}:/mnt/bannerlator-sd")
|
||||
Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\")")
|
||||
} else {
|
||||
Log.w(TAG, "game storage: $problem; internal only this session")
|
||||
}
|
||||
@@ -773,13 +757,13 @@ class SessionService : Service() {
|
||||
}
|
||||
// The user's own games folder (the Steam cog's "Added games"), bound at a fixed place so
|
||||
// the shortcuts the app writes point somewhere whatever storage the folder is on.
|
||||
for (root in com.droiddeck.launcher.frontend.AddedGames.roots(this)) {
|
||||
if (root.host.isDirectory && root.host.canRead()) {
|
||||
File(LinuxRuntime.rootDir(this), root.guest.removePrefix("/")).mkdirs()
|
||||
binds.add(root.host.path + ":" + root.guest)
|
||||
Log.i(TAG, "added games: ${root.host} -> ${root.guest}")
|
||||
for (addedRoot in com.droiddeck.launcher.frontend.AddedGames.roots(this)) {
|
||||
if (addedRoot.host.isDirectory && addedRoot.host.canRead()) {
|
||||
File(root, addedRoot.guest.removePrefix("/")).mkdirs()
|
||||
binds.add(addedRoot.host.path + ":" + addedRoot.guest)
|
||||
Log.i(TAG, "added games: ${addedRoot.host} -> ${addedRoot.guest}")
|
||||
} else {
|
||||
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
|
||||
Log.w(TAG, "added games: ${addedRoot.host} is not a readable folder this session")
|
||||
}
|
||||
}
|
||||
val roms = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }?.let { File(it) }
|
||||
@@ -1035,6 +1019,7 @@ class SessionService : Service() {
|
||||
SessionEvents.fail(code, message, failureStatus)
|
||||
}
|
||||
SessionState.notifyEnded(status)
|
||||
SessionProcess.releaseSessionLock()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
@@ -1066,6 +1051,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun stopSession(status: Int) {
|
||||
if (!SessionProcess.isExternalDisplay(this)) stopExternalDisplaySession(this)
|
||||
synchronized(stopLock) {
|
||||
if (!SessionState.running) return
|
||||
SessionState.running = false
|
||||
@@ -1099,6 +1085,7 @@ class SessionService : Service() {
|
||||
// dump the crash buffer. That was about four and a half seconds of blocked main thread,
|
||||
// and Android ANR'd the app for it: the desktop session that would not let go.
|
||||
val ended = SessionPaths.take()
|
||||
val plasmaShellPid = readPlasmaShellPid(ended)
|
||||
if (ended != null) Thread({ collectSessionArtifacts(ended) }, "session-collect").start()
|
||||
components.reversed().forEach {
|
||||
try {
|
||||
@@ -1116,10 +1103,12 @@ class SessionService : Service() {
|
||||
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
stopPlasmaShell(plasmaShellPid, ended)
|
||||
killGuestLeftovers()
|
||||
finishSessionStop(status, stoppedGen)
|
||||
}, "session-teardown").start()
|
||||
} else {
|
||||
stopPlasmaShell(plasmaShellPid, ended)
|
||||
finishSessionStop(status, stoppedGen)
|
||||
}
|
||||
}
|
||||
@@ -1139,6 +1128,7 @@ class SessionService : Service() {
|
||||
|
||||
override fun onDestroy() {
|
||||
stopSession(0)
|
||||
if (!SessionState.running) SessionProcess.releaseSessionLock()
|
||||
if (screenReceiverRegistered) {
|
||||
unregisterReceiver(screenReceiver)
|
||||
screenReceiverRegistered = false
|
||||
@@ -1200,8 +1190,9 @@ class SessionService : Service() {
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
val channelId = notificationChannelId()
|
||||
// IMPORTANCE_LOW: it must never make a sound or push a heads-up over a game.
|
||||
val channel = NotificationChannel(CHANNEL_ID, getString(R.string.session_channel),
|
||||
val channel = NotificationChannel(channelId, getString(R.string.session_channel),
|
||||
NotificationManager.IMPORTANCE_LOW).apply {
|
||||
description = getString(R.string.session_channel_description)
|
||||
setShowBadge(false)
|
||||
@@ -1211,23 +1202,23 @@ class SessionService : Service() {
|
||||
manager?.createNotificationChannel(channel)
|
||||
|
||||
val open = PendingIntent.getActivity(
|
||||
this, 0,
|
||||
Intent(this, SessionActivity::class.java)
|
||||
this, notificationId(),
|
||||
Intent(this, sessionActivityClass())
|
||||
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val stop = PendingIntent.getService(
|
||||
this, 1, Intent(this, SessionService::class.java).setAction(ACTION_STOP),
|
||||
this, notificationId() + 1, Intent(this, sessionServiceClass()).setAction(ACTION_STOP),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val resume = PendingIntent.getActivity(
|
||||
this, 2,
|
||||
Intent(this, SessionActivity::class.java)
|
||||
this, notificationId() + 2,
|
||||
Intent(this, sessionActivityClass())
|
||||
.setAction(ACTION_RESUME)
|
||||
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
return Notification.Builder(this, CHANNEL_ID)
|
||||
return Notification.Builder(this, channelId)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(getString(R.string.app_name))
|
||||
.setContentText(getString(if (SessionState.suspended) R.string.session_notification_paused else R.string.session_notification))
|
||||
@@ -1245,20 +1236,19 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun refreshNotification() {
|
||||
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification())
|
||||
getSystemService(NotificationManager::class.java)?.notify(notificationId(), 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")
|
||||
}
|
||||
private fun notificationId(): Int = if (SessionProcess.isExternalDisplay(this)) EXTERNAL_NOTIFICATION_ID else NOTIFICATION_ID
|
||||
|
||||
private fun notificationChannelId(): String =
|
||||
if (SessionProcess.isExternalDisplay(this)) EXTERNAL_CHANNEL_ID else CHANNEL_ID
|
||||
|
||||
private fun sessionActivityClass(): Class<*> =
|
||||
if (SessionProcess.isExternalDisplay(this)) ExternalSessionActivity::class.java else SessionActivity::class.java
|
||||
|
||||
private fun sessionServiceClass(): Class<*> =
|
||||
if (SessionProcess.isExternalDisplay(this)) ExternalSessionService::class.java else SessionService::class.java
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
@@ -1270,6 +1260,8 @@ class SessionService : Service() {
|
||||
private const val ENV_SWITCH = "Download/droiddeck-env"
|
||||
private const val CHANNEL_ID = "session"
|
||||
private const val NOTIFICATION_ID = 1001
|
||||
private const val EXTERNAL_CHANNEL_ID = "session-external-display"
|
||||
private const val EXTERNAL_NOTIFICATION_ID = 1002
|
||||
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
|
||||
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
|
||||
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
|
||||
@@ -1282,13 +1274,14 @@ class SessionService : Service() {
|
||||
private const val ACTION_AUXILIARY_EXITED = "com.droiddeck.launcher.AUXILIARY_EXITED"
|
||||
private const val EXTRA_AUXILIARY_PID = "auxiliaryPid"
|
||||
/** Command lines that can only belong to a session of ours. */
|
||||
private val STRAGGLERS = listOf("bannerlator-session", "gamescope", "Xwayland", "steamrtarm64",
|
||||
private val STRAGGLERS = listOf("bannerlator-session", "gamescope", "Xwayland", "kwin_wayland", "kwin_x11", "plasmashell", "steamrtarm64",
|
||||
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
|
||||
/** How long proot gets to run its own cleanup before it is killed outright. */
|
||||
private const val GRACE_MS = 1200L
|
||||
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. */
|
||||
@@ -1297,6 +1290,7 @@ class SessionService : Service() {
|
||||
const val EXTRA_MODE = "mode"
|
||||
const val MODE_STEAM = "steam"
|
||||
const val MODE_DESKTOP = "lxqt"
|
||||
const val MODE_PLASMA_MOBILE = "plasma-mobile"
|
||||
/** A program inside the runtime, fullscreen under gamescope (EXTRA_PROGRAM = its path). */
|
||||
const val MODE_RUN = "run"
|
||||
const val EXTRA_PROGRAM = "program"
|
||||
@@ -1307,11 +1301,16 @@ class SessionService : Service() {
|
||||
const val EXTRA_STEAM_UI = "steamUi"
|
||||
const val EXTRA_STEAM_URL = "steamUrl"
|
||||
|
||||
private fun serviceClass(mode: String): Class<*> =
|
||||
if (mode == MODE_PLASMA_MOBILE) ExternalSessionService::class.java else SessionService::class.java
|
||||
|
||||
private fun currentServiceClass(): Class<*> = serviceClass(SessionState.mode)
|
||||
|
||||
fun start(
|
||||
context: Context, mode: String = MODE_STEAM, program: String? = null,
|
||||
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
|
||||
) {
|
||||
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
|
||||
val intent = Intent(context, serviceClass(mode)).putExtra(EXTRA_MODE, mode)
|
||||
if (program != null) intent.putExtra(EXTRA_PROGRAM, program)
|
||||
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
|
||||
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
|
||||
@@ -1325,29 +1324,33 @@ class SessionService : Service() {
|
||||
SessionState.stopRequested = true
|
||||
return
|
||||
}
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
|
||||
context.startService(Intent(context, currentServiceClass()).setAction(ACTION_STOP))
|
||||
}
|
||||
|
||||
/** Stops the independent Linux desktop hosted on the other Android display, if running. */
|
||||
fun stopExternalDisplaySession(context: Context): Boolean =
|
||||
context.stopService(Intent(context, ExternalSessionService::class.java))
|
||||
|
||||
fun setActivityVisible(context: Context, visible: Boolean) {
|
||||
if (!SessionState.running) return
|
||||
val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(action))
|
||||
context.startService(Intent(context, currentServiceClass()).setAction(action))
|
||||
}
|
||||
|
||||
fun resume(context: Context) {
|
||||
if (!SessionState.running) return
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
|
||||
context.startService(Intent(context, currentServiceClass()).setAction(ACTION_RESUME))
|
||||
}
|
||||
|
||||
fun suspendPolicyChanged(context: Context) {
|
||||
if (!SessionState.running) return
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
|
||||
context.startService(Intent(context, currentServiceClass()).setAction(ACTION_SUSPEND_POLICY_CHANGED))
|
||||
}
|
||||
|
||||
/** Let the session service clean up the PTY's proot tree if the control screen closes. */
|
||||
fun stopTerminalProcess(context: Context, pid: Int) {
|
||||
if (pid > 1) context.startService(
|
||||
Intent(context, SessionService::class.java)
|
||||
Intent(context, currentServiceClass())
|
||||
.setAction(ACTION_STOP_AUXILIARY)
|
||||
.putExtra(EXTRA_AUXILIARY_PID, pid),
|
||||
)
|
||||
@@ -1355,7 +1358,7 @@ class SessionService : Service() {
|
||||
|
||||
fun registerTerminalProcess(context: Context, pid: Int) {
|
||||
if (pid > 1) context.startService(
|
||||
Intent(context, SessionService::class.java)
|
||||
Intent(context, currentServiceClass())
|
||||
.setAction(ACTION_TRACK_AUXILIARY)
|
||||
.putExtra(EXTRA_AUXILIARY_PID, pid),
|
||||
)
|
||||
@@ -1363,7 +1366,7 @@ class SessionService : Service() {
|
||||
|
||||
fun terminalProcessExited(context: Context, pid: Int) {
|
||||
if (pid > 1) context.startService(
|
||||
Intent(context, SessionService::class.java)
|
||||
Intent(context, currentServiceClass())
|
||||
.setAction(ACTION_AUXILIARY_EXITED)
|
||||
.putExtra(EXTRA_AUXILIARY_PID, pid),
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
package com.droiddeck.launcher.store.gog
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* GOG's web APIs, as Heroic uses them: the signed-in account's games (embed.gog.com, with the
|
||||
* token gogdl keeps) and a game's art (gamesdb.gog.com, public). Downloads are gogdl's.
|
||||
*/
|
||||
object GogApi {
|
||||
private const val TAG = "GogApi"
|
||||
private const val TIMEOUT_MS = 20_000
|
||||
private const val LIBRARY = "https://embed.gog.com/account/getFilteredProducts?mediaType=1&sortBy=title&page="
|
||||
private const val GAMESDB = "https://gamesdb.gog.com/platforms/gog/external_releases/"
|
||||
|
||||
/** An owned game; [image] is the store's wide tile. Only games with a Windows build are listed. */
|
||||
class Game(val id: String, val title: String, val image: String?)
|
||||
|
||||
class Art(val cover: String?, val header: String?, val hero: String?, val logo: String?)
|
||||
|
||||
/** Every game the account owns that runs on Windows, by title; null when GOG could not be asked. */
|
||||
fun library(token: String): List<Game>? {
|
||||
val games = ArrayList<Game>()
|
||||
var page = 1
|
||||
var pages = 1
|
||||
while (page <= pages) {
|
||||
val body = get(LIBRARY + page, token) ?: return null
|
||||
val (items, total) = parseLibraryPage(body) ?: return null
|
||||
games += items
|
||||
pages = total.coerceAtMost(100)
|
||||
page++
|
||||
}
|
||||
return games.distinctBy { it.id }.sortedBy { it.title.lowercase() }
|
||||
}
|
||||
|
||||
/** One page: its games and how many pages there are. */
|
||||
internal fun parseLibraryPage(body: String): Pair<List<Game>, Int>? = runCatching {
|
||||
val o = JSONObject(body)
|
||||
val products = o.optJSONArray("products")
|
||||
val games = (0 until (products?.length() ?: 0)).mapNotNull { i ->
|
||||
val p = products!!.optJSONObject(i) ?: return@mapNotNull null
|
||||
val windows = p.optJSONObject("worksOn")?.optBoolean("Windows") ?: false
|
||||
val id = p.opt("id")?.toString()?.takeIf { it.isNotEmpty() && it != "null" } ?: return@mapNotNull null
|
||||
if (!windows) return@mapNotNull null
|
||||
Game(id, p.optString("title").ifEmpty { id }, image(p.optString("image")))
|
||||
}
|
||||
games to o.optInt("totalPages", 1).coerceAtLeast(1)
|
||||
}.getOrNull()
|
||||
|
||||
/** The store's image ids come protocol-relative and without a size; 392 is its wide tile. */
|
||||
internal fun image(raw: String): String? {
|
||||
if (raw.isBlank()) return null
|
||||
val url = if (raw.startsWith("//")) "https:$raw" else raw
|
||||
return if (url.endsWith(".jpg") || url.endsWith(".png")) url else "${url}_392.jpg"
|
||||
}
|
||||
|
||||
/** The game's art from GOG's games database, or null when it has none. */
|
||||
fun art(id: String): Art? = get(GAMESDB + id, null)?.let(::parseArt)
|
||||
|
||||
internal fun parseArt(body: String): Art? = runCatching {
|
||||
val game = JSONObject(body).optJSONObject("game") ?: return@runCatching null
|
||||
fun url(key: String, ext: String) = game.optJSONObject(key)?.optString("url_format")
|
||||
?.takeIf { it.isNotEmpty() }?.replace("{formatter}", "")?.replace("{ext}", ext)
|
||||
Art(url("vertical_cover", "jpg"), url("horizontal_artwork", "jpg"), url("background", "jpg"), url("logo", "png"))
|
||||
}.getOrNull()
|
||||
|
||||
/**
|
||||
* Puts the game's art into its folder's .art/ under the names the Added Games art reader looks
|
||||
* for first (cover, header, hero, logo), so Steam shows GOG's own art for it. Best effort.
|
||||
*/
|
||||
fun saveArt(id: String, dir: File) {
|
||||
val art = art(id) ?: return
|
||||
val target = File(dir, ".art").apply { mkdirs() }
|
||||
listOf("cover.jpg" to art.cover, "header.jpg" to art.header, "hero.jpg" to art.hero, "logo.png" to art.logo)
|
||||
.forEach { (name, url) ->
|
||||
val file = File(target, name)
|
||||
if (url != null && !file.isFile) download(url, file)
|
||||
}
|
||||
}
|
||||
|
||||
private fun download(url: String, file: File) {
|
||||
var c: HttpURLConnection? = null
|
||||
try {
|
||||
c = (URL(url).openConnection() as HttpURLConnection).apply { connectTimeout = TIMEOUT_MS; readTimeout = TIMEOUT_MS }
|
||||
if (c.responseCode / 100 != 2) return
|
||||
val part = File(file.path + ".part")
|
||||
c.inputStream.use { input -> part.outputStream().use { input.copyTo(it) } }
|
||||
part.renameTo(file)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "$url: $e")
|
||||
} finally {
|
||||
c?.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun get(url: String, token: String?): String? {
|
||||
var c: HttpURLConnection? = null
|
||||
return try {
|
||||
c = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
connectTimeout = TIMEOUT_MS
|
||||
readTimeout = TIMEOUT_MS
|
||||
setRequestProperty("Accept", "application/json")
|
||||
if (token != null) setRequestProperty("Authorization", "Bearer $token")
|
||||
}
|
||||
// The URL is logged; the token never is.
|
||||
if (c.responseCode / 100 != 2) { Log.w(TAG, "${url.substringBefore('?')} -> HTTP ${c.responseCode}"); null }
|
||||
else c.inputStream.bufferedReader().use { it.readText() }
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "${url.substringBefore('?')}: ${e.javaClass.simpleName}"); null
|
||||
} finally {
|
||||
c?.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package com.droiddeck.launcher.store.gog
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* What an installed GOG game says about itself: goggame-<id>.info in its folder, the file GOG Galaxy
|
||||
* and Heroic launch from. Its primary play task names the exe, the folder to start in and the
|
||||
* arguments, so a store-installed game needs no guessing at which .exe is the game.
|
||||
*/
|
||||
object GogGameInfo {
|
||||
class Task(val exe: File, val workingDir: File, val arguments: String)
|
||||
class Info(val id: String, val name: String, val task: Task?)
|
||||
|
||||
/** The root game's info in [folder] (DLCs add their own files beside it), or null. */
|
||||
fun read(folder: File): Info? {
|
||||
val files = folder.listFiles { f -> f.isFile && f.name.startsWith("goggame-") && f.name.endsWith(".info") } ?: return null
|
||||
val parsed = files.sortedBy { it.name }.mapNotNull { f -> runCatching { JSONObject(f.readText()) }.getOrNull() }
|
||||
val root = parsed.firstOrNull { it.optString("gameId").let { id -> id.isNotEmpty() && id == it.optString("rootGameId") } }
|
||||
?: parsed.singleOrNull() ?: return null
|
||||
return parse(folder, root)
|
||||
}
|
||||
|
||||
internal fun parse(folder: File, json: JSONObject): Info? {
|
||||
val id = json.optString("gameId").ifEmpty { return null }
|
||||
val name = json.optString("name").ifEmpty { folder.name }
|
||||
val tasks = json.optJSONArray("playTasks")
|
||||
val files = (0 until (tasks?.length() ?: 0)).mapNotNull { tasks!!.optJSONObject(it) }
|
||||
.filter { it.optString("type") == "FileTask" && it.optString("path").isNotEmpty() }
|
||||
// Galaxy's own choice: the primary game task; else the first game task; else the first at all.
|
||||
val chosen = files.firstOrNull { it.optBoolean("isPrimary") && it.optString("category", "game") == "game" }
|
||||
?: files.firstOrNull { it.optString("category", "game") == "game" }
|
||||
?: files.firstOrNull()
|
||||
val task = chosen?.let { t ->
|
||||
val exe = resolve(folder, t.optString("path")) ?: return@let null
|
||||
val dir = t.optString("workingDir").takeIf { it.isNotBlank() }?.let { resolve(folder, it) } ?: folder
|
||||
Task(exe, dir, t.optString("arguments").trim())
|
||||
}
|
||||
return Info(id, name, task)
|
||||
}
|
||||
|
||||
/**
|
||||
* [relative] (a Windows path, backslashes and all) under [base], matched case-insensitively as
|
||||
* Windows would; null when no such file or folder exists.
|
||||
*/
|
||||
internal fun resolve(base: File, relative: String): File? {
|
||||
var at = base
|
||||
for (part in relative.replace('\\', '/').split('/').filter { it.isNotEmpty() && it != "." }) {
|
||||
// The name as the folder lists it: a caseless filesystem (an SD card) would accept any
|
||||
// spelling, but the session sees the game through proot, where only the real one works.
|
||||
val names = at.listFiles().orEmpty()
|
||||
at = names.firstOrNull { it.name == part } ?: names.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return null
|
||||
}
|
||||
return at
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.droiddeck.launcher.store.gog
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import com.droiddeck.launcher.MainActivity
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
/**
|
||||
* Keeps the process in the foreground while a GOG game downloads: games run to tens of gigabytes,
|
||||
* and without a foreground service Android may kill the app (and the download's proot with it) the
|
||||
* moment the user switches away. A killed or stopped download resumes when installed again.
|
||||
*/
|
||||
class GogInstallService : Service() {
|
||||
/** One download: [kind] is "install" or "update"; [base] a [GogManager.Base] id; [dir] the game's folder for an update. */
|
||||
class Job(val kind: String, val id: String, val title: String, val base: String, val dir: String?)
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == ACTION_CANCEL) {
|
||||
GogState.cancel()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val job = intent?.let(::jobFrom)
|
||||
startForeground(NOTIFICATION_ID, notification(job?.title ?: "GOG", "Starting…", -1))
|
||||
if (job == null) {
|
||||
stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
Thread({
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
var shown = Int.MIN_VALUE
|
||||
GogState.run(applicationContext, job) { stage, percent ->
|
||||
// Every percent at most once: a notification per line would flood the system.
|
||||
if (percent != shown) {
|
||||
shown = percent
|
||||
manager?.notify(NOTIFICATION_ID, notification(job.title, stage, percent))
|
||||
}
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
stopForeground(true)
|
||||
stopSelf(startId)
|
||||
}, "gog-${job.kind}").start()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun notification(title: String, stage: String, percent: Int): Notification {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "GOG downloads",
|
||||
NotificationManager.IMPORTANCE_LOW).apply {
|
||||
description = "Shows while a GOG game downloads"
|
||||
setShowBadge(false)
|
||||
setSound(null, null)
|
||||
enableVibration(false)
|
||||
})
|
||||
val open = PendingIntent.getActivity(this, 0,
|
||||
Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||
PendingIntent.FLAG_IMMUTABLE)
|
||||
val cancel = PendingIntent.getService(this, 1,
|
||||
Intent(this, GogInstallService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
|
||||
return Notification.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(title)
|
||||
.setContentText(stage)
|
||||
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
|
||||
.setContentIntent(open)
|
||||
.addAction(Notification.Action.Builder(null, "Stop", cancel).build())
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setShowWhen(false)
|
||||
.build()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "gog-download"
|
||||
private const val NOTIFICATION_ID = 4
|
||||
private const val ACTION_CANCEL = "com.droiddeck.launcher.gog.CANCEL"
|
||||
|
||||
fun start(context: Context, job: Job) {
|
||||
val intent = Intent(context, GogInstallService::class.java)
|
||||
.putExtra("kind", job.kind).putExtra("id", job.id).putExtra("title", job.title)
|
||||
.putExtra("base", job.base).putExtra("dir", job.dir)
|
||||
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
|
||||
}
|
||||
|
||||
private fun jobFrom(intent: Intent): Job? {
|
||||
val kind = intent.getStringExtra("kind") ?: return null
|
||||
val id = intent.getStringExtra("id") ?: return null
|
||||
return Job(kind, id, intent.getStringExtra("title") ?: id, intent.getStringExtra("base") ?: "internal", intent.getStringExtra("dir"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
package com.droiddeck.launcher.store.gog
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* GOG in the Linux runtime, through Heroic's gogdl (GOG's own download protocol, sign-in tokens,
|
||||
* resumable installs): putting gogdl there, signing in, and installing, updating and removing
|
||||
* games. A game lands in a GOG folder the Added Games scan reads, so the session puts it in Steam
|
||||
* as a shortcut like any other added game - the store only fetches; Steam still launches.
|
||||
*
|
||||
* Each command runs in a proot of its own (GuestCommand), so a download carries on whether or
|
||||
* not a session is up.
|
||||
*/
|
||||
object GogManager {
|
||||
private const val TAG = "GogManager"
|
||||
/** Heroic's gogdl release the app puts in the runtime: a Python zipapp, so any architecture. */
|
||||
const val GOGDL_VERSION = "1.3.0"
|
||||
private const val GOGDL_URL = "https://github.com/Heroic-Games-Launcher/heroic-gogdl/releases/download/v$GOGDL_VERSION/gogdl_linux_arm64"
|
||||
private const val GOGDL_SHA256 = "c49e1519146523ec94f33e2d21eedcc9a167004d7da218621e6d5fb84a7a0f4c"
|
||||
/** Where gogdl lives in the runtime (bannerlator-gog runs it from there). */
|
||||
private const val GOGDL = "opt/droiddeck/gogdl/gogdl"
|
||||
private const val HELPER = "/usr/local/bin/bannerlator-gog"
|
||||
/** The folder, in each place games can go, that store installs live under. */
|
||||
const val FOLDER = "GOG"
|
||||
/** Written by the helper into a game's folder before its download starts. */
|
||||
const val MARKER = ".droiddeck-gog.json"
|
||||
private const val RESUME = ".gogdl-resume"
|
||||
|
||||
/** One store operation at a time. */
|
||||
@Volatile var busy: String? = null
|
||||
private set
|
||||
|
||||
/** One place games can go: internal (the runtime's own disk) or the SD card's game library. */
|
||||
class Base(val id: String, val label: String, val host: File, val guest: String, val binds: List<String>)
|
||||
|
||||
/** A GOG game in one of the [bases]; [complete] is false for a download that stopped partway. */
|
||||
class Installed(val id: String, val name: String, val dir: File, val base: Base, val complete: Boolean)
|
||||
|
||||
/** The sign-in gogdl keeps (tokens), in the app's private files - never on shared storage. */
|
||||
fun authFile(context: Context) = File(context.filesDir, "gog/auth.json")
|
||||
|
||||
private fun gogdl(context: Context) = File(LinuxRuntime.rootDir(context), GOGDL)
|
||||
private fun stamp(context: Context) = File(LinuxRuntime.rootDir(context), "$GOGDL.version")
|
||||
|
||||
fun ready(context: Context): Boolean =
|
||||
gogdl(context).isFile && runCatching { stamp(context).readText().trim() }.getOrNull() == GOGDL_VERSION
|
||||
|
||||
fun signedIn(context: Context): Boolean = authFile(context).isFile
|
||||
|
||||
fun bases(context: Context): List<Base> {
|
||||
val internal = Base("internal", "Internal storage", File(LinuxRuntime.rootDir(context), "root/$FOLDER"), "/root/$FOLDER", emptyList())
|
||||
val sd = GameStorage.effective(context)?.let { lib ->
|
||||
Base("sd", lib.label, File(lib.path, FOLDER), "/mnt/droiddeck-sd/$FOLDER", listOf("${lib.path}:/mnt/droiddeck-sd"))
|
||||
}
|
||||
return listOfNotNull(internal, sd)
|
||||
}
|
||||
|
||||
fun installed(context: Context): List<Installed> = bases(context).flatMap { base ->
|
||||
base.host.listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { dir -> installedAt(dir, base) }
|
||||
}.sortedBy { it.name.lowercase() }
|
||||
|
||||
private fun installedAt(dir: File, base: Base): Installed? {
|
||||
val marker = runCatching { JSONObject(File(dir, MARKER).readText()) }.getOrNull()
|
||||
val info = GogGameInfo.read(dir)
|
||||
val id = marker?.optString("id")?.ifEmpty { null } ?: info?.id ?: return null
|
||||
val complete = info?.task != null && !File(dir, RESUME).exists()
|
||||
return Installed(id, info?.name ?: dir.name, dir, base, complete)
|
||||
}
|
||||
|
||||
/** True for a folder the store put there and whose download has not finished: not a game yet. */
|
||||
fun incomplete(dir: File): Boolean =
|
||||
File(dir, MARKER).isFile && (File(dir, RESUME).exists() || GogGameInfo.read(dir)?.task == null)
|
||||
|
||||
private inline fun <T> exclusive(what: String, block: () -> T): T? {
|
||||
synchronized(this) {
|
||||
if (busy != null) return null
|
||||
busy = what
|
||||
}
|
||||
try { return block() } finally { busy = null }
|
||||
}
|
||||
|
||||
/** Downloads the pinned gogdl into the runtime and checks it. Null on success, else why not. */
|
||||
fun setup(context: Context, onProgress: (String, Int) -> Unit): String? {
|
||||
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
|
||||
return exclusive("setup") {
|
||||
val target = gogdl(context)
|
||||
val part = File(target.path + ".part")
|
||||
target.parentFile?.mkdirs()
|
||||
onProgress("Downloading gogdl $GOGDL_VERSION", -1)
|
||||
if (!Downloader.downloadFile(GOGDL_URL, part, true) { f -> if (f >= 0) onProgress("Downloading gogdl $GOGDL_VERSION", (f * 100).toInt()) }) {
|
||||
return@exclusive "Could not download gogdl"
|
||||
}
|
||||
if (!Hashes.sha256(part).equals(GOGDL_SHA256, ignoreCase = true)) {
|
||||
part.delete()
|
||||
return@exclusive "gogdl did not match its checksum"
|
||||
}
|
||||
if (!part.renameTo(target)) return@exclusive "Could not put gogdl in place"
|
||||
target.setExecutable(true, false)
|
||||
stamp(context).writeText(GOGDL_VERSION)
|
||||
null
|
||||
} ?: "Another GOG task is running"
|
||||
}
|
||||
|
||||
/** Runs the helper. Commands that touch tokens pass no [logName]: their output stays off shared storage. */
|
||||
private fun helper(context: Context, args: List<String>, logName: String?, binds: List<String> = emptyList(),
|
||||
onProcess: ((Process) -> Unit)? = null, onEvent: (JSONObject) -> Unit): Int {
|
||||
val argv = listOf("/usr/bin/python3", HELPER, args[0], authFile(context).path) + args.drop(1)
|
||||
return GuestCommand.run(context, argv, logName = logName, extraBinds = binds, onProcess = onProcess) { line ->
|
||||
val o = runCatching { JSONObject(line) }.getOrNull()
|
||||
if (o != null && o.has("e")) onEvent(o) else if (logName != null) Log.i(TAG, line)
|
||||
}
|
||||
}
|
||||
|
||||
/** Trades the sign-in page's code for gogdl's tokens. Null on success, else why not. */
|
||||
fun login(context: Context, code: String): String? {
|
||||
if (!ready(context)) return "Set up GOG first"
|
||||
authFile(context).parentFile?.mkdirs()
|
||||
var error: String? = null
|
||||
var done = false
|
||||
val status = exclusive("login") {
|
||||
helper(context, listOf("login", code), logName = null) { o ->
|
||||
when (o.optString("e")) {
|
||||
"done" -> done = true
|
||||
"error" -> error = o.optString("message")
|
||||
}
|
||||
}
|
||||
} ?: return "Another GOG task is running"
|
||||
return when {
|
||||
done -> null
|
||||
error != null -> error
|
||||
else -> "Signing in failed (exit $status)"
|
||||
}
|
||||
}
|
||||
|
||||
fun signOut(context: Context) {
|
||||
authFile(context).delete()
|
||||
token = null
|
||||
}
|
||||
|
||||
private class Token(val value: String, val userId: String, val expires: Long)
|
||||
@Volatile private var token: Token? = null
|
||||
|
||||
/** A current access token for GOG's APIs, refreshed by gogdl when due; null when signed out. */
|
||||
fun accessToken(context: Context): String? {
|
||||
token?.takeIf { it.expires * 1000 > System.currentTimeMillis() + 60_000 }?.let { return it.value }
|
||||
if (!ready(context) || !signedIn(context)) return null
|
||||
var fresh: Token? = null
|
||||
// Not exclusive: a token is wanted while a download runs, and gogdl only rewrites the
|
||||
// file when it refreshes.
|
||||
helper(context, listOf("token"), logName = null) { o ->
|
||||
if (o.optString("e") == "token") fresh = Token(o.optString("access_token"), o.optString("user_id"), o.optLong("expires"))
|
||||
}
|
||||
token = fresh
|
||||
return fresh?.value
|
||||
}
|
||||
|
||||
class Sizes(val download: Long, val disk: Long)
|
||||
|
||||
/** The Windows build's download and installed sizes, or null when it cannot be read. */
|
||||
fun sizes(context: Context, id: String): Sizes? {
|
||||
if (!ready(context)) return null
|
||||
var sizes: Sizes? = null
|
||||
helper(context, listOf("info", id), logName = null) { o ->
|
||||
if (o.optString("e") == "info") sizes = Sizes(o.optLong("download_size"), o.optLong("disk_size"))
|
||||
}
|
||||
return sizes
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads [id] into [base]; a stopped download picks up where it left off. [onProcess] gets
|
||||
* the running command so the caller can stop it. Null on success, else why not.
|
||||
*/
|
||||
fun install(context: Context, id: String, base: Base, onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? =
|
||||
transfer(context, "install", listOf("install", id, base.guest), base, onProcess, onProgress)
|
||||
|
||||
fun update(context: Context, game: Installed, onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? {
|
||||
val guest = game.base.guest + "/" + game.dir.name
|
||||
return transfer(context, "update", listOf("update", game.id, guest), game.base, onProcess, onProgress)
|
||||
}
|
||||
|
||||
private fun transfer(context: Context, verb: String, args: List<String>, base: Base,
|
||||
onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? {
|
||||
if (!ready(context)) return "Set up GOG first"
|
||||
if (!signedIn(context)) return "Sign in to GOG first"
|
||||
return exclusive("$verb:${args[1]}") {
|
||||
base.host.mkdirs()
|
||||
// proot binds the SD library onto this folder, as a session does.
|
||||
if (base.binds.isNotEmpty()) File(LinuxRuntime.rootDir(context), "mnt/droiddeck-sd").mkdirs()
|
||||
var error: String? = null
|
||||
var done = false
|
||||
var stage = if (verb == "update") "Updating" else "Downloading"
|
||||
onProgress("Preparing", -1)
|
||||
val status = helper(context, args, logName = "gog-$verb", binds = base.binds, onProcess = onProcess) { o ->
|
||||
when (o.optString("e")) {
|
||||
"info" -> {
|
||||
stage = "${if (verb == "update") "Updating" else "Downloading"} ${formatSize(o.optLong("download_size"))}"
|
||||
onProgress(stage, 0)
|
||||
}
|
||||
"progress" -> onProgress(stage, o.optInt("percent"))
|
||||
"error" -> error = o.optString("message")
|
||||
"done" -> done = true
|
||||
}
|
||||
}
|
||||
when {
|
||||
done -> null
|
||||
error != null -> error
|
||||
else -> "Stopped (exit $status)"
|
||||
}
|
||||
} ?: "Another GOG task is running"
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the game's files and gogdl's record of them. The game's Proton prefix (its saves and
|
||||
* settings) stays where Steam keeps it, as for any added game taken out of the library.
|
||||
*/
|
||||
fun uninstall(context: Context, game: Installed): String? = exclusive("uninstall:${game.id}") {
|
||||
if (!game.dir.deleteRecursively() && game.dir.exists()) return@exclusive "Could not remove ${game.dir.name}"
|
||||
File(LinuxRuntime.rootDir(context), "root/.config/heroic_gogdl/manifests/${game.id}").delete()
|
||||
null
|
||||
} ?: "Another GOG task is running"
|
||||
|
||||
fun formatSize(bytes: Long): String = when {
|
||||
bytes >= 1L shl 30 -> "%.1f GB".format(bytes / (1L shl 30).toDouble())
|
||||
bytes >= 1L shl 20 -> "%.0f MB".format(bytes / (1L shl 20).toDouble())
|
||||
else -> "%.0f KB".format(bytes / 1024.0)
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
package com.droiddeck.launcher.store.gog
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.Toast
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
/**
|
||||
* The GOG store's state for the life of the process, so a download carries on - and its progress
|
||||
* shows - while the user moves around the launcher or plays something meanwhile. Downloads run in
|
||||
* [GogInstallService], which keeps the process in the foreground for as long as they take.
|
||||
*/
|
||||
object GogState {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
var ready by mutableStateOf(false)
|
||||
private set
|
||||
var signedIn by mutableStateOf(false)
|
||||
private set
|
||||
/** The account's Windows games; null until loaded. */
|
||||
var library by mutableStateOf<List<GogApi.Game>?>(null)
|
||||
private set
|
||||
var libraryFailed by mutableStateOf(false)
|
||||
private set
|
||||
var loadingLibrary by mutableStateOf(false)
|
||||
private set
|
||||
var installed by mutableStateOf<List<GogManager.Installed>>(emptyList())
|
||||
private set
|
||||
/** What is running: "setup", "login", or a game id; null when idle. */
|
||||
var busy by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var stage by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var percent by mutableStateOf(-1)
|
||||
private set
|
||||
/** Download and installed sizes by game id; absent until asked, null while being read. */
|
||||
val sizes = mutableStateMapOf<String, GogManager.Sizes?>()
|
||||
|
||||
@Volatile private var process: Process? = null
|
||||
@Volatile private var cancelled = false
|
||||
|
||||
fun refresh(context: Context) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val r = GogManager.ready(app)
|
||||
val s = GogManager.signedIn(app)
|
||||
val list = GogManager.installed(app)
|
||||
main.post { ready = r; signedIn = s; installed = list }
|
||||
}, "gog-refresh").start()
|
||||
}
|
||||
|
||||
fun loadLibrary(context: Context, force: Boolean = false) {
|
||||
if (loadingLibrary || (!force && library != null)) return
|
||||
val app = context.applicationContext
|
||||
loadingLibrary = true
|
||||
libraryFailed = false
|
||||
Thread({
|
||||
val token = GogManager.accessToken(app)
|
||||
val games = token?.let { GogApi.library(it) }
|
||||
main.post {
|
||||
loadingLibrary = false
|
||||
if (games != null) library = games else libraryFailed = true
|
||||
}
|
||||
}, "gog-library").start()
|
||||
}
|
||||
|
||||
fun loadSizes(context: Context, id: String) {
|
||||
if (sizes.containsKey(id)) return
|
||||
val app = context.applicationContext
|
||||
sizes[id] = null
|
||||
Thread({
|
||||
val s = GogManager.sizes(app, id)
|
||||
main.post { sizes[id] = s; if (s == null) sizes.remove(id) }
|
||||
}, "gog-sizes").start()
|
||||
}
|
||||
|
||||
private fun background(context: Context, what: String, label: String, work: (Context, (String, Int) -> Unit) -> String?) {
|
||||
if (busy != null) return
|
||||
val app = context.applicationContext
|
||||
busy = what; stage = "Starting…"; percent = -1
|
||||
Thread({
|
||||
val problem = try {
|
||||
work(app) { s, p -> main.post { stage = s; percent = p } }
|
||||
} catch (e: Exception) {
|
||||
e.message ?: e.toString()
|
||||
}
|
||||
val r = GogManager.ready(app)
|
||||
val s = GogManager.signedIn(app)
|
||||
val list = GogManager.installed(app)
|
||||
main.post {
|
||||
busy = null; stage = null; percent = -1
|
||||
ready = r; signedIn = s; installed = list
|
||||
if (problem != null) Toast.makeText(app, "$label: $problem", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "gog-$what").start()
|
||||
}
|
||||
|
||||
fun setup(context: Context) = background(context, "setup", "GOG setup") { c, p -> GogManager.setup(c, p) }
|
||||
|
||||
fun login(context: Context, code: String) = background(context, "login", "GOG sign-in") { c, p ->
|
||||
p("Signing in…", -1)
|
||||
GogManager.login(c, code).also { if (it == null) main.post { library = null; loadLibrary(c, force = true) } }
|
||||
}
|
||||
|
||||
fun signOut(context: Context) {
|
||||
GogManager.signOut(context)
|
||||
library = null
|
||||
signedIn = false
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, game: GogManager.Installed) =
|
||||
background(context, game.id, game.name) { c, p -> p("Removing…", -1); GogManager.uninstall(c, game) }
|
||||
|
||||
fun install(context: Context, game: GogApi.Game, base: GogManager.Base) {
|
||||
if (busy != null) return
|
||||
busy = game.id; stage = "Starting…"; percent = -1
|
||||
GogInstallService.start(context, GogInstallService.Job("install", game.id, game.title, base.id, null))
|
||||
}
|
||||
|
||||
fun update(context: Context, game: GogManager.Installed) {
|
||||
if (busy != null) return
|
||||
busy = game.id; stage = "Starting…"; percent = -1
|
||||
GogInstallService.start(context, GogInstallService.Job("update", game.id, game.name, game.base.id, game.dir.path))
|
||||
}
|
||||
|
||||
/** Stops the running download; installing again resumes it. */
|
||||
fun cancel() {
|
||||
cancelled = true
|
||||
process?.destroy()
|
||||
}
|
||||
|
||||
/** The service's half of [install] and [update]; runs on the service's thread. */
|
||||
internal fun run(context: Context, job: GogInstallService.Job, notify: (String, Int) -> Unit) {
|
||||
val app = context.applicationContext
|
||||
cancelled = false
|
||||
main.post { busy = job.id }
|
||||
val base = GogManager.bases(app).firstOrNull { it.id == job.base }
|
||||
val problem = try {
|
||||
when {
|
||||
base == null -> "That storage is not available"
|
||||
job.kind == "update" -> {
|
||||
val game = GogManager.installed(app).firstOrNull { it.dir.path == job.dir }
|
||||
if (game == null) "The game is no longer installed"
|
||||
else GogManager.update(app, game, { process = it }) { s, p -> main.post { stage = s; percent = p }; notify(s, p) }
|
||||
}
|
||||
else -> GogManager.install(app, job.id, base, { process = it }) { s, p -> main.post { stage = s; percent = p }; notify(s, p) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.message ?: e.toString()
|
||||
} finally {
|
||||
process = null
|
||||
}
|
||||
val list = GogManager.installed(app)
|
||||
// GOG's own art for Steam to show; the Steam store's is the fallback if this finds none.
|
||||
if (problem == null) list.firstOrNull { it.id == job.id }?.let { runCatching { GogApi.saveArt(job.id, it.dir) } }
|
||||
main.post {
|
||||
busy = null; stage = null; percent = -1
|
||||
installed = list
|
||||
val message = when {
|
||||
cancelled -> "${job.title}: stopped. Install again to pick up where it left off."
|
||||
problem != null -> "${job.title}: $problem"
|
||||
job.kind == "update" -> "${job.title} is up to date."
|
||||
else -> "${job.title} is installed. It shows in Steam the next time Steam starts."
|
||||
}
|
||||
Toast.makeText(app, message, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -1,328 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import android.view.ViewGroup
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebStorage
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.store.gog.GogApi
|
||||
import com.droiddeck.launcher.store.gog.GogManager
|
||||
import com.droiddeck.launcher.store.gog.GogState
|
||||
|
||||
// The Store's GOG side: sign in, the account's Windows games, and installing them into a GOG
|
||||
// folder the Added Games scan reads - so each shows in Steam as a non-Steam game, launched by
|
||||
// Steam through Proton like any other added game. gogdl (Heroic's) does the downloading.
|
||||
|
||||
/** GOG's own sign-in page; it hands back a code on embed.gog.com, which gogdl trades for tokens. */
|
||||
private const val GOG_LOGIN = "https://auth.gog.com/auth?client_id=46899977096215655" +
|
||||
"&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&response_type=code&layout=galaxy"
|
||||
|
||||
@Composable
|
||||
internal fun GogStore(s: FrontEndState) {
|
||||
val ctx = LocalContext.current
|
||||
var open by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var signingIn by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(s.ready) { GogState.refresh(ctx) }
|
||||
BackHandler(enabled = open != null) { open = null }
|
||||
if (signingIn) GogLoginDialog(onCode = { signingIn = false; GogState.login(ctx, it) }, onDismiss = { signingIn = false })
|
||||
if (!s.ready) {
|
||||
Rise(1) { Note("Install the Linux runtime from Setup first; GOG games install into it.") }
|
||||
return
|
||||
}
|
||||
val id = open
|
||||
if (id != null) {
|
||||
GogDetail(id) { open = null }
|
||||
return
|
||||
}
|
||||
GogBusyBar()
|
||||
when {
|
||||
!GogState.ready -> Rise(1) {
|
||||
GogCard(
|
||||
"Set up GOG",
|
||||
"Adds gogdl, the GOG downloader Heroic Games Launcher uses (about 2 MB), to the Linux runtime. " +
|
||||
"Games you own on GOG then install from here and show in Steam's library as non-Steam games.",
|
||||
) {
|
||||
PrimaryButton(if (GogState.busy == "setup") "Setting up…" else "Set up GOG", enabled = GogState.busy == null, main = true) { GogState.setup(ctx) }
|
||||
}
|
||||
}
|
||||
!GogState.signedIn -> Rise(1) {
|
||||
GogCard("Sign in to GOG", "Sign in with your GOG account to list and install the games you own. The sign-in stays in the app's private storage.") {
|
||||
PrimaryButton(if (GogState.busy == "login") "Signing in…" else "Sign in", enabled = GogState.busy == null, main = true) { signingIn = true }
|
||||
}
|
||||
}
|
||||
else -> GogLibrary(onOpen = { open = it }, onSignOut = {
|
||||
GogState.signOut(ctx)
|
||||
CookieManager.getInstance().removeAllCookies(null)
|
||||
WebStorage.getInstance().deleteAllData()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GogCard(title: String, body: String, actions: @Composable () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 12.dp).clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(16.dp),
|
||||
) {
|
||||
Text(title, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text(body, fontSize = 14.sp, color = colors.onSurfaceVariant)
|
||||
Actions { actions() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The running setup, sign-in or download, whichever page it was started from. */
|
||||
@Composable
|
||||
private fun GogBusyBar() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val busy = GogState.busy ?: return
|
||||
val name = GogState.library?.firstOrNull { it.id == busy }?.title ?: GogState.installed.firstOrNull { it.id == busy }?.name
|
||||
?: when (busy) { "setup" -> "GOG"; "login" -> "GOG"; else -> busy }
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 4.dp)) {
|
||||
val stage = GogState.stage
|
||||
Text(
|
||||
"$name · " + (if (stage != null && GogState.percent >= 0) "$stage · ${GogState.percent}%" else stage ?: "Starting…"),
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(bottom = 6.dp),
|
||||
)
|
||||
if (GogState.percent >= 0) LinearProgressIndicator(progress = { GogState.percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
|
||||
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GogLibrary(onOpen: (String) -> Unit, onSignOut: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
LaunchedEffect(Unit) { GogState.loadLibrary(ctx) }
|
||||
val library = GogState.library
|
||||
val installed = GogState.installed
|
||||
Rise(2) {
|
||||
Actions {
|
||||
SecondaryButton(if (GogState.loadingLibrary) "Refreshing…" else "Refresh", enabled = !GogState.loadingLibrary) { GogState.loadLibrary(ctx, force = true) }
|
||||
SecondaryButton("Sign out", enabled = GogState.busy == null, onClick = onSignOut)
|
||||
}
|
||||
}
|
||||
if (installed.isNotEmpty()) {
|
||||
Rise(3) { SectionTitle("Installed", installed.size.toString()) }
|
||||
Rise(3) {
|
||||
GogGrid(installed.map { i ->
|
||||
Triple(i.id, i.name, library?.firstOrNull { it.id == i.id }?.image)
|
||||
}, first = true, status = { gid -> installed.firstOrNull { it.id == gid }?.let { if (it.complete) "Installed · ${it.base.label}" else "Download stopped" } }, onOpen = onOpen)
|
||||
}
|
||||
Rise(3) { Note("Installed games show in Steam's library as non-Steam games the next time Steam starts.") }
|
||||
}
|
||||
when {
|
||||
library == null && GogState.libraryFailed -> Rise(4) { Note("GOG could not be reached, or the sign-in has expired. Refresh, or sign out and in again.") }
|
||||
library == null -> Rise(4) { SectionTitle("Your games", "loading…") }
|
||||
library.isEmpty() -> Rise(4) { Note("No Windows games on this GOG account yet.") }
|
||||
else -> {
|
||||
Rise(4) { SectionTitle("Your games", library.size.toString()) }
|
||||
Rise(5) {
|
||||
GogGrid(library.map { Triple(it.id, it.title, it.image) }, first = installed.isEmpty(),
|
||||
status = { gid -> installed.firstOrNull { it.id == gid }?.let { if (it.complete) "Installed" else "Download stopped" } }, onOpen = onOpen)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Games as tiles with GOG's wide art: three across, or one on a narrow page. */
|
||||
@Composable
|
||||
private fun GogGrid(games: List<Triple<String, String, String?>>, first: Boolean, status: (String) -> String?, onOpen: (String) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val columns = if (LocalNarrowPane.current) 1 else 3
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) {
|
||||
games.chunked(columns).forEachIndexed { r, row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
row.forEachIndexed { i, (id, title, image) ->
|
||||
key(id) {
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
Column(
|
||||
modifier = Modifier.weight(1f).paneItem("tile:gog:$id").then(if (first && r == 0 && i == 0) Modifier.firstTile() else Modifier)
|
||||
.clip(Shape14).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
|
||||
.glideBorder(hot, Shape14, pal.signal, pal.line)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onOpen(id) },
|
||||
) {
|
||||
AsyncImage(
|
||||
model = image, contentDescription = null, contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).background(colors.surfaceVariant),
|
||||
)
|
||||
Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {
|
||||
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val st = status(id)
|
||||
Text(st ?: "GOG", fontSize = 13.sp, color = if (st != null) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GogDetail(id: String, onBack: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
val game = GogState.library?.firstOrNull { it.id == id }
|
||||
val local = GogState.installed.firstOrNull { it.id == id }
|
||||
val title = game?.title ?: local?.name ?: id
|
||||
val bases = remember { GogManager.bases(ctx) }
|
||||
var baseId by rememberSaveable(id) { mutableStateOf(bases.first().id) }
|
||||
LaunchedEffect(id) { GogState.loadSizes(ctx, id) }
|
||||
val sizes = GogState.sizes[id]
|
||||
val busyHere = GogState.busy == id
|
||||
// Uninstall asks twice: one stray press of A should not cost a download.
|
||||
var confirmRemove by remember(id) { mutableStateOf(false) }
|
||||
LaunchedEffect(confirmRemove) { if (confirmRemove) { kotlinx.coroutines.delay(4000); confirmRemove = false } }
|
||||
Rise(0) { BackLink("GOG", onClick = onBack) }
|
||||
Rise(1) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.padding(top = 12.dp, bottom = 8.dp)) {
|
||||
AsyncImage(
|
||||
model = game?.image, contentDescription = null, contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.width(if (narrow) 140.dp else 220.dp).aspectRatio(16f / 9f).clip(Shape12).background(colors.surfaceVariant),
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(title, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
when {
|
||||
local?.complete == true -> "Installed on ${local.base.label}"
|
||||
local != null -> "Download stopped on ${local.base.label}"
|
||||
else -> "Windows · runs through Proton in Steam"
|
||||
},
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (local == null && bases.size > 1) {
|
||||
Rise(2) { SectionTitle("Install to", null) }
|
||||
Rise(2) {
|
||||
Actions {
|
||||
bases.forEach { b ->
|
||||
val label = "${b.label} · ${GameStorage.free(b.host.parentFile ?: b.host)} free"
|
||||
if (b.id == baseId) PrimaryButton(label, compact = true) {} else SecondaryButton(label, compact = true) { baseId = b.id }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Rise(3) {
|
||||
Actions {
|
||||
when {
|
||||
busyHere -> SecondaryButton("Stop") { GogState.cancel() }
|
||||
local == null || !local.complete -> PrimaryButton(if (local == null) "Install" else "Resume download", main = true, enabled = GogState.busy == null && game != null) {
|
||||
val base = local?.base ?: bases.first { it.id == baseId }
|
||||
game?.let { GogState.install(ctx, it, base) }
|
||||
}
|
||||
else -> SecondaryButton("Check for update", enabled = GogState.busy == null) { GogState.update(ctx, local) }
|
||||
}
|
||||
if (local != null && !busyHere) {
|
||||
SecondaryButton(if (confirmRemove) "Press again to uninstall" else "Uninstall", enabled = GogState.busy == null) {
|
||||
if (confirmRemove) { confirmRemove = false; GogState.uninstall(ctx, local) } else confirmRemove = true
|
||||
}
|
||||
}
|
||||
sizes?.let {
|
||||
ActionChip("${GogManager.formatSize(it.download)} download", ok = false)
|
||||
ActionChip("${GogManager.formatSize(it.disk)} installed", ok = false)
|
||||
}
|
||||
if (local?.complete == true) ActionChip("● Installed", ok = true)
|
||||
}
|
||||
}
|
||||
if (busyHere) GogBusyBar()
|
||||
Rise(4) {
|
||||
Box(Modifier.padding(top = 12.dp)) {
|
||||
Note(
|
||||
if (local?.complete == true) "It is in Steam's library as a non-Steam game (after Steam next starts). Uninstalling removes the game's files; " +
|
||||
"its saves and settings stay in its Proton prefix."
|
||||
else "Installs the Windows build. Once it finishes, the game shows in Steam's library as a non-Steam game the next time Steam starts, " +
|
||||
"and runs through Proton like the rest of your added games.",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A sign-in that ends on GOG's success page hands its code to [onCode]; GOG's page does the rest. */
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
private fun GogLoginDialog(onCode: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
var done by remember { mutableStateOf(false) }
|
||||
fun check(url: String?): Boolean {
|
||||
val uri = url?.let(Uri::parse) ?: return false
|
||||
if (uri.host != "embed.gog.com" || uri.path?.startsWith("/on_login_success") != true) return false
|
||||
val code = uri.getQueryParameter("code") ?: return false
|
||||
if (!done) { done = true; onCode(code) }
|
||||
return true
|
||||
}
|
||||
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { c ->
|
||||
WebView(c).apply {
|
||||
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = check(request.url.toString())
|
||||
override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
|
||||
if (check(url)) view.stopLoading()
|
||||
}
|
||||
}
|
||||
loadUrl(GOG_LOGIN)
|
||||
}
|
||||
},
|
||||
onRelease = { it.destroy() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -63,12 +63,13 @@ class ModeSettings(
|
||||
val clientDirectAudio: Boolean = false,
|
||||
val mic: Boolean?,
|
||||
val renderer: String?,
|
||||
val desktopEnvironment: String? = null,
|
||||
val plasmaMobileInstalled: Boolean = false,
|
||||
val gameStorage: String? = null,
|
||||
val storageOptions: List<Pair<String, String>> = emptyList(),
|
||||
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. */
|
||||
@@ -114,11 +115,11 @@ class ModeSettingsActions(
|
||||
val onClientDirectAudio: (Boolean) -> Unit = {},
|
||||
val onMic: (Boolean) -> Unit,
|
||||
val onRenderer: (String) -> Unit,
|
||||
val onDesktopEnvironment: (String) -> Unit = {},
|
||||
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
|
||||
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 = {},
|
||||
@@ -193,6 +194,19 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr,
|
||||
)
|
||||
}
|
||||
if (s.desktopEnvironment != null) SettingsGroup("Desktop environment") {
|
||||
ChoiceRow(
|
||||
host, "desktop-environment", "Desktop", null,
|
||||
SessionPrefs.desktopEnvironmentChoices, s.desktopEnvironment,
|
||||
note = "KDE Plasma Mobile installs on first launch and can also run on a second screen.",
|
||||
onPick = a.onDesktopEnvironment,
|
||||
)
|
||||
SettingsRow(
|
||||
"KDE Plasma Mobile",
|
||||
if (s.plasmaMobileInstalled) "Installed and ready."
|
||||
else "Downloads packages from Arch Linux ARM the first time you open Desktop.",
|
||||
) { }
|
||||
}
|
||||
SettingsGroup("Drivers") {
|
||||
SettingsRow("GPU drivers", "Shared by Steam and the desktop, on the Components page.") {
|
||||
ValueChip(s.gpuDrivers, open = false) { a.onGpuDrivers() }
|
||||
@@ -363,11 +377,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)
|
||||
|
||||
@@ -40,7 +40,6 @@ fun PerformancePage(
|
||||
gamescopeRealtime: Boolean,
|
||||
gpuClockPin: Boolean,
|
||||
prootNoSeccomp: Boolean,
|
||||
prootFastPath: Boolean,
|
||||
guestHostname: String,
|
||||
phantomWarning: String?,
|
||||
onClientOverride: (Boolean) -> Unit,
|
||||
@@ -52,7 +51,6 @@ fun PerformancePage(
|
||||
onGamescopeRealtime: (Boolean) -> Unit,
|
||||
onGpuClockPin: (Boolean) -> Unit,
|
||||
onProotNoSeccomp: (Boolean) -> Unit,
|
||||
onProotFastPath: (Boolean) -> Unit,
|
||||
onGuestHostname: (String) -> Unit,
|
||||
onClientCore: (Int, Boolean) -> Unit,
|
||||
onGameCore: (Int, Boolean) -> Unit,
|
||||
@@ -129,12 +127,6 @@ fun PerformancePage(
|
||||
"May fix missing syscall errors on some kernels, but can reduce performance.",
|
||||
prootNoSeccomp, onChange = onProotNoSeccomp,
|
||||
)
|
||||
ToggleRow(
|
||||
host, "fastpath", "proot fast path",
|
||||
if (prootNoSeccomp) "Needs proot's seccomp filter: off while proot runs without seccomp."
|
||||
else "Answers file lookups inside each program instead of through proot. Faster loading and less stutter; turn off if a program cannot find its files.",
|
||||
prootFastPath && !prootNoSeccomp, enabled = !prootNoSeccomp, onChange = onProotFastPath,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Session identity") {
|
||||
var draft by remember(guestHostname) { mutableStateOf(guestHostname) }
|
||||
|
||||
@@ -114,6 +114,7 @@ class SecondScreenPresentation(
|
||||
SecondScreenMode.TERMINAL -> renderTerminal()
|
||||
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam), weightParams())
|
||||
SecondScreenMode.NONE -> Unit
|
||||
SecondScreenMode.PLASMA_MOBILE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -166,6 +166,7 @@ class DrawerActions(
|
||||
val backActionsInverted: Boolean,
|
||||
val touchMode: String,
|
||||
val touchAuto: String,
|
||||
val directTouchOnly: Boolean,
|
||||
val shapeMode: String,
|
||||
val fexPreset: String,
|
||||
/** Steam only: games stretched to the screen's size, changed live (null = not Steam). */
|
||||
@@ -173,6 +174,7 @@ class DrawerActions(
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val plasmaMobileInstalled: Boolean = false,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
val onFrameGenPick: (FrameGen.Mode) -> Unit,
|
||||
val onImportLossless: () -> Unit,
|
||||
@@ -358,7 +360,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
DRAWER_PAGE_COMPONENTS -> ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
|
||||
1 -> {
|
||||
SettingsGroup("Controls") {
|
||||
ChoiceRow(host, "touch", "Touch", null,
|
||||
if (a.directTouchOnly) {
|
||||
SettingsRow("Touch", "Direct input to the screen") {
|
||||
Text("Direct", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
}
|
||||
} else ChoiceRow(host, "touch", "Touch", null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"),
|
||||
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
|
||||
ChoiceRow(host, "osc", "On-screen controls", null,
|
||||
@@ -380,10 +386,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
}
|
||||
}
|
||||
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
||||
val secondScreenModes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
|
||||
(if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) +
|
||||
(if (a.plasmaMobileInstalled) listOf(SecondScreenMode.PLASMA_MOBILE) else emptyList())
|
||||
ChoiceRow(host, "second-screen-mode", "Shows", null,
|
||||
(listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
|
||||
(if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()))
|
||||
.map { it to it.label },
|
||||
secondScreenModes.map { it to it.label },
|
||||
a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
|
||||
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", "Display", null,
|
||||
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
|
||||
|
||||
@@ -76,8 +76,6 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
var openApp by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var category by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
// Which store the page shows: Flathub's apps, or the user's GOG games.
|
||||
var store by rememberSaveable { mutableStateOf("flathub") }
|
||||
LaunchedEffect(s.ready) { StoreState.refresh(ctx) }
|
||||
LaunchedEffect(Unit) { StoreState.loadSections() }
|
||||
// A pad's focus sits on something the page is about to replace - the tile that opens an app,
|
||||
@@ -105,8 +103,8 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
}
|
||||
Column(
|
||||
modifier = modifier.verticalScroll(scroll).padding(horizontal = padH, vertical = padV)
|
||||
.bumpers(onPrevious = { if (openApp == null && store == "flathub") switchTab((tab + TABS.size - 1) % TABS.size) },
|
||||
onNext = { if (openApp == null && store == "flathub") switchTab((tab + 1) % TABS.size) }),
|
||||
.bumpers(onPrevious = { if (openApp == null) switchTab((tab + TABS.size - 1) % TABS.size) },
|
||||
onNext = { if (openApp == null) switchTab((tab + 1) % TABS.size) }),
|
||||
) {
|
||||
val id = openApp
|
||||
if (id != null) {
|
||||
@@ -115,25 +113,10 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
}
|
||||
Rise(0) {
|
||||
PageHeader("Store") {
|
||||
if (store == "gog") {
|
||||
Chip("GOG · Windows games", ok = false)
|
||||
if (com.droiddeck.launcher.store.gog.GogState.signedIn) Chip("● Signed in", ok = true)
|
||||
} else {
|
||||
Chip("Flathub · ARM64", ok = false)
|
||||
if (StoreState.ready) Chip("● Flatpak ready", ok = true)
|
||||
}
|
||||
Chip("Flathub · ARM64", ok = false)
|
||||
if (StoreState.ready) Chip("● Flatpak ready", ok = true)
|
||||
}
|
||||
}
|
||||
Rise(0) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 10.dp)) {
|
||||
PillButton("Flathub", selected = store == "flathub") { store = "flathub" }
|
||||
PillButton("GOG", selected = store == "gog") { store = "gog" }
|
||||
}
|
||||
}
|
||||
if (store == "gog") {
|
||||
GogStore(s)
|
||||
return@Column
|
||||
}
|
||||
if (!s.ready) {
|
||||
Rise(1) { Note("Install the Linux runtime from Setup first; the store installs apps into it.") }
|
||||
return@Column
|
||||
|
||||
@@ -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,76 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class SecondaryLibraryTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun gamesStaySharedButPrefixesAndNativeDownloadsArePrivate() {
|
||||
val files = tmp.newFolder("files")
|
||||
val library = tmp.newFolder("card")
|
||||
File(library, "steamapps/common/Game").mkdirs()
|
||||
val binds = SecondaryLibrary.binds(files, library)
|
||||
val private = SecondaryLibrary.privateRoot(files, library)
|
||||
for (guest in listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd")) {
|
||||
assertTrue(binds.contains("${library.path}:$guest"))
|
||||
assertTrue(binds.contains("$private/steamapps/compatdata:$guest/steamapps/compatdata"))
|
||||
assertTrue(binds.contains("$private/steamapps/downloading/4185400:$guest/steamapps/downloading/4185400"))
|
||||
assertTrue(binds.contains("$private/steamapps/common/SteamLinuxRuntime_4-arm64:$guest/steamapps/common/steamlinuxruntime_4-arm64"))
|
||||
assertFalse(binds.any { it.endsWith(":$guest/steamapps/common/Game") })
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun migrationPreservesSavesLinksAndOriginalAndNeverOverwritesNewSaves() {
|
||||
val files = tmp.newFolder("files")
|
||||
val library = tmp.newFolder("card")
|
||||
val save = File(library, "steamapps/compatdata/42/pfx/save.dat")
|
||||
save.parentFile!!.mkdirs()
|
||||
save.writeText("original")
|
||||
Files.createSymbolicLink(File(save.parentFile, "link").toPath(), File("save.dat").toPath())
|
||||
SecondaryLibrary.binds(files, library)
|
||||
val copied = File(SecondaryLibrary.privateRoot(files, library), "steamapps/compatdata/42/pfx/save.dat")
|
||||
assertEquals("original", copied.readText())
|
||||
assertTrue(Files.isSymbolicLink(File(copied.parentFile, "link").toPath()))
|
||||
copied.writeText("new save")
|
||||
SecondaryLibrary.binds(files, library)
|
||||
assertEquals("new save", copied.readText())
|
||||
assertEquals("original", save.readText())
|
||||
}
|
||||
|
||||
@Test fun changingLibraryUsesADifferentPrivatePrefixDirectory() {
|
||||
val files = tmp.newFolder("files")
|
||||
assertNotEquals(SecondaryLibrary.privateRoot(files, tmp.newFolder("one")),
|
||||
SecondaryLibrary.privateRoot(files, tmp.newFolder("two")))
|
||||
}
|
||||
|
||||
@Test fun installedNativeToolVersionsAlsoGetPrivateStaging() {
|
||||
val files = tmp.newFolder("files")
|
||||
val library = tmp.newFolder("card")
|
||||
val manifest = File(library, "steamapps/appmanifest_123.acf")
|
||||
manifest.parentFile!!.mkdirs()
|
||||
manifest.writeText("\"AppState\" { \"appid\" \"123\" \"installdir\" \"Proton 99.0 (ARM64)\" }")
|
||||
assertTrue(SecondaryLibrary.binds(files, library).any {
|
||||
it.endsWith(":/mnt/droiddeck-sd/steamapps/downloading/123")
|
||||
})
|
||||
}
|
||||
|
||||
@Test fun deletingAStagedDepotDoesNotRestoreTheOldSharedDownload() {
|
||||
val files = tmp.newFolder("files")
|
||||
val library = tmp.newFolder("card")
|
||||
val stale = File(library, "steamapps/downloading/4185400/stale")
|
||||
stale.parentFile!!.mkdirs()
|
||||
stale.writeText("old download")
|
||||
SecondaryLibrary.binds(files, library)
|
||||
val target = File(SecondaryLibrary.privateRoot(files, library), "steamapps/downloading/4185400")
|
||||
assertTrue(File(target, "stale").isFile)
|
||||
target.deleteRecursively()
|
||||
SecondaryLibrary.binds(files, library)
|
||||
assertFalse(File(target, "stale").exists())
|
||||
assertTrue(stale.isFile)
|
||||
}
|
||||
}
|
||||
@@ -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,91 +0,0 @@
|
||||
package com.droiddeck.launcher.store.gog
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class GogTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
private fun game(): File = tmp.newFolder("Example Game").apply {
|
||||
File(this, "Bin").mkdirs()
|
||||
File(this, "Bin/Game.EXE").writeText("x")
|
||||
File(this, "Launcher.exe").writeText("x")
|
||||
File(this, "Data").mkdirs()
|
||||
}
|
||||
|
||||
private fun info(vararg tasks: String) =
|
||||
JSONObject("""{"gameId":"42","rootGameId":"42","name":"Example: The Game","playTasks":[${tasks.joinToString(",")}]}""")
|
||||
|
||||
@Test fun primaryGameTaskWinsWithWindowsPathsMatchedCaselessly() {
|
||||
val dir = game()
|
||||
val parsed = GogGameInfo.parse(dir, info(
|
||||
"""{"type":"FileTask","category":"launcher","isPrimary":true,"path":"Launcher.exe"}""",
|
||||
"""{"type":"URLTask","category":"document","link":"https://example.com"}""",
|
||||
"""{"type":"FileTask","category":"game","isPrimary":true,"path":"bin\\game.exe","workingDir":"data","arguments":"-windowed -lang \"en\""}""",
|
||||
))!!
|
||||
assertEquals("42", parsed.id)
|
||||
assertEquals("Example: The Game", parsed.name)
|
||||
assertEquals(File(dir, "Bin/Game.EXE"), parsed.task!!.exe)
|
||||
assertEquals(File(dir, "Data"), parsed.task!!.workingDir)
|
||||
assertEquals("-windowed -lang \"en\"", parsed.task!!.arguments)
|
||||
}
|
||||
|
||||
@Test fun noWorkingDirStartsInTheGameFolder() {
|
||||
val dir = game()
|
||||
val parsed = GogGameInfo.parse(dir, info("""{"type":"FileTask","category":"game","path":"Bin\\Game.exe"}"""))!!
|
||||
assertEquals(dir, parsed.task!!.workingDir)
|
||||
assertEquals("", parsed.task!!.arguments)
|
||||
}
|
||||
|
||||
@Test fun missingExeMeansNoTask() {
|
||||
val dir = game()
|
||||
assertNull(GogGameInfo.parse(dir, info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Missing.exe"}"""))!!.task)
|
||||
}
|
||||
|
||||
@Test fun readPicksTheRootGameOverDlcInfoFiles() {
|
||||
val dir = game()
|
||||
File(dir, "goggame-7.info").writeText("""{"gameId":"7","rootGameId":"42","name":"DLC","playTasks":[]}""")
|
||||
File(dir, "goggame-42.info").writeText(info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Bin\\Game.exe"}""").toString())
|
||||
assertEquals("42", GogGameInfo.read(dir)!!.id)
|
||||
}
|
||||
|
||||
@Test fun incompleteUntilTheDownloadFinishes() {
|
||||
val dir = game()
|
||||
File(dir, GogManager.MARKER).writeText("""{"id":"42"}""")
|
||||
assertTrue(GogManager.incomplete(dir))
|
||||
File(dir, "goggame-42.info").writeText(info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Bin\\Game.exe"}""").toString())
|
||||
File(dir, ".gogdl-resume").writeText("")
|
||||
assertTrue(GogManager.incomplete(dir))
|
||||
File(dir, ".gogdl-resume").delete()
|
||||
assertEquals(false, GogManager.incomplete(dir))
|
||||
}
|
||||
|
||||
@Test fun libraryKeepsWindowsGamesAndPageCount() {
|
||||
val (games, pages) = GogApi.parseLibraryPage("""{"totalPages":3,"products":[
|
||||
{"id":1207658924,"title":"Unreal Tournament","image":"//images-1.gog-statics.com/abc","worksOn":{"Windows":true,"Mac":false,"Linux":false}},
|
||||
{"id":2,"title":"Mac Only","image":"//images-1.gog-statics.com/def","worksOn":{"Windows":false,"Mac":true}}
|
||||
]}""")!!
|
||||
assertEquals(3, pages)
|
||||
assertEquals(listOf("1207658924"), games.map { it.id })
|
||||
assertEquals("https://images-1.gog-statics.com/abc_392.jpg", games[0].image)
|
||||
}
|
||||
|
||||
@Test fun artFillsGamesDbUrlTemplates() {
|
||||
val art = GogApi.parseArt("""{"game":{"vertical_cover":{"url_format":"https://images.gog.com/v{formatter}.{ext}"},
|
||||
"logo":{"url_format":"https://images.gog.com/l{formatter}.{ext}"}}}""")!!
|
||||
assertEquals("https://images.gog.com/v.jpg", art.cover)
|
||||
assertEquals("https://images.gog.com/l.png", art.logo)
|
||||
assertNull(art.hero)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -1,310 +0,0 @@
|
||||
# proot, glibc and where the time goes
|
||||
|
||||
Research notes for `feat/performance-fixes-2` (2026-09-30). The question was whether Steam and the
|
||||
games should keep running under proot, run directly on glibc, or a mix of the two, and what the
|
||||
fastest correct setup is. Everything below was measured on a Snapdragon 8 Elite Gen 5 (SM8850, kernel
|
||||
6.12.38-android16, Android 16) over adb, unless it says otherwise.
|
||||
|
||||
## Short answer
|
||||
|
||||
- **Don't drop proot.** On Android it does two jobs. It translates paths. It also answers every
|
||||
syscall that Android's app seccomp policy blocks (`rseq`, `set_robust_list`, `faccessat2`,
|
||||
`fchmodat2`, `openat2`, the `set*id` family, `futex_waitv`, ...).
|
||||
- Stock Arch glibc without a tracer is killed by `SIGSYS` on its first `pthread_create`. That
|
||||
stays true even with an in-process `SIGSYS` handler, because glibc makes those calls with every
|
||||
signal blocked.
|
||||
- Going "pure glibc" means building Termux-style glibc (relocated prefix, blocked syscalls
|
||||
rewritten), an exec shim for every ELF Steam self-updates, a `/proc/self/exe` emulator for
|
||||
Chromium, path redirects for `/tmp`, `/dev/shm`, `/mnt/*` and the fake `/proc` and `/sys`
|
||||
files, and Wine's hard-coded `/tmp/.wine-<uid>`.
|
||||
- That is a project of its own, and its failure mode is a crash instead of a slow call.
|
||||
- **During gameplay, proot already costs almost nothing**, thanks to patches 0004–0013. GPU submits
|
||||
(`ioctl`), `futex`, `read`/`write`, `mmap`, `ppoll`/`epoll`, `sendmsg`/`recvmsg` and
|
||||
`clock_gettime` (via the vDSO) all run at native speed under the filter.
|
||||
- **What proot still costs** is every *path* syscall, `execve`, `brk`, thread and process creation,
|
||||
and every Android-blocked syscall: **15–60 µs each**, against ~0.5 µs natively. All of it goes
|
||||
through **one tracer thread**, which tops out around 75–95k traps/s. Steam start-up, game loading
|
||||
and asset streaming, Proton's Python, and any burst on several threads at once all hit this.
|
||||
- **Most of that cost is not proot's code but the two cross-core wake-ups per trap.** Any
|
||||
out-of-process mechanism pays them: ptrace, and seccomp user-notification too (measured the same).
|
||||
The only real fix is to not leave the process.
|
||||
- **Recommendation: proot plus an in-process fast path.** A preloaded library answers the common
|
||||
path calls inside the process. It sends them through a trampoline page that proot's filter lets
|
||||
through, and it falls back to proot for anything it can't prove proot would answer the same way.
|
||||
- The prototype is in this branch: `tools/proot/fastpath/` and `patches/0014`.
|
||||
- Speed: `stat` 25 µs → 0.6 µs, `open` 25 µs → 0.9 µs, missing-file lookups 23 µs → 1.6 µs.
|
||||
Eight threads doing `stat` went from 89k/s to 3.6M/s.
|
||||
- Correctness: an equivalence suite of awkward paths produced byte-identical results.
|
||||
- It only uses syscalls the app policy allows.
|
||||
|
||||
## How a session runs today
|
||||
|
||||
```
|
||||
SessionService ─HostProcess─▶ libproot.so (ONE tracer process, nice -6 after 2 s)
|
||||
└─ /usr/bin/env -i … bannerlator-session steam
|
||||
└─ gamescope ─▶ bannerlator-session (BL_INSIDE) ─▶ steamrtarm64/steam (+ steamwebhelper/CEF tree)
|
||||
└─ reaper ─▶ bannerlator-game-env ─▶ bannerlator-proton ─▶ Valve ARM64 Proton (python)
|
||||
└─ wine (arm64ec, FEX loaded in-process as a DLL) ─▶ wineserver, game.exe, …
|
||||
```
|
||||
|
||||
- Every process in the tree, from the session script to the game, is a tracee of the same proot.
|
||||
- The options are `--kill-on-exit`, `--kernel-release=…` (kompat, for the hostname), `-i uid:uid`
|
||||
(fake_id0, for Xwayland's `setgid`/`setuid`), and about 25 binds: `/dev`, `/proc`, `/sys`, fake
|
||||
`/proc` and `/sys` files, the GPU node, `/dev/shm`, storage and the game libraries.
|
||||
- `/etc/ld.so.preload` loads `libblsession.so` (the `tools/linuxfs/preload/*.c` shims) into every
|
||||
guest process.
|
||||
- The Flatpak sandboxes (`BwrapSpawner`) already run in **separate** proot instances, started from
|
||||
the Android side.
|
||||
|
||||
### What proot does per traced syscall
|
||||
|
||||
The tracee runs into proot's seccomp filter, which returns `SECCOMP_RET_TRACE`. Then:
|
||||
|
||||
1. The kernel stops the tracee and wakes the tracer: a cross-core IPI, and possibly an exit from a
|
||||
deep idle state.
|
||||
2. The tracer reads the registers (`PTRACE_GETREGSET`) and reads the path (`process_vm_readv`).
|
||||
3. It canonicalises the path against the rootfs and bindings: an `lstat` per component, or one
|
||||
`O_PATH` open plus a `/proc/self/fd` readlink with patch 0002.
|
||||
4. It writes the host path into a scratch area in the tracee (`process_vm_writev`) and updates the
|
||||
registers.
|
||||
5. It resumes the tracee, which is another cross-core wake-up.
|
||||
|
||||
Calls flagged `FILTER_SYSEXIT` stop a second time on the way out, for example to translate the
|
||||
result of `readlink` or `getcwd`. Android-blocked syscalls arrive as a `SIGSYS` signal stop instead,
|
||||
and proot emulates them (`src/tracee/seccomp.c`). Fork, clone, exec and thread exit each add
|
||||
`PTRACE_EVENT_*` stops.
|
||||
|
||||
## Measurements
|
||||
|
||||
The tools are in `tools/proot/bench/`; `run-device.sh` explains the device layout.
|
||||
|
||||
**Caveat:** `adb shell` is *not* under the app seccomp filter. Mechanism costs are the same, but
|
||||
syscalls that Android blocks only for apps (see below) can't be reproduced there.
|
||||
|
||||
**Caveat:** the phone in Doze (screen off) runs everything about 7× slower. All numbers below were
|
||||
taken with the screen awake.
|
||||
|
||||
### Per call, as a session runs proot today
|
||||
|
||||
`sysbench` in the patched (`patched`) and unpatched (`vanilla`) columns, using the session's own
|
||||
proot options and a similar set of binds.
|
||||
|
||||
| call | direct glibc | termux proot (vanilla) | this repo's proot (0001–0013) | + fast path (0014) |
|
||||
|---|---|---|---|---|
|
||||
| getppid / futex / ioctl / pread (untraced) | 0.1–0.4 µs | futex **16.6**, fstat **32.8**, ioctl **30.5** µs | 0.2–0.4 µs | 0.2–0.4 µs |
|
||||
| stat, deep absolute path | 0.8 µs | 41.7 | 25.3 | **0.6** |
|
||||
| open + close | 1.7 µs | 40.4 | 25.3 | **0.9** |
|
||||
| access | | 27.2 | 26.2 | **1.0** |
|
||||
| fstatat relative to a dirfd | | 45.5 | 26.8 | **1.9** |
|
||||
| stat of a missing file | | 38.9 | 22.9 | **1.6** |
|
||||
| readlink /proc/self/exe | | 42.8 | 38–43 | (proot) |
|
||||
| getcwd / uname / brk | | 31–35 | 30–33 | (proot) |
|
||||
| memfd_create | | 20.4 | 18.6 | (proot) |
|
||||
| pthread create+join | | 58 | 48 | 48 |
|
||||
| fork + exec + wait | ~1.1 ms | 1.16 ms | 0.70–0.78 ms | +0.2–0.4 ms (see open items) |
|
||||
|
||||
The patches already in the repo pay off: kompat (0011) and fake_id0 (0012) took `futex`, `fstat` and
|
||||
`sendmsg` off the trap list, and 0013 did the same for `ioctl`.
|
||||
|
||||
### What one trap costs, by mechanism (`mechbench`; the handler does nothing)
|
||||
|
||||
| mechanism | cost |
|
||||
|---|---|
|
||||
| native syscall | 0.1 µs |
|
||||
| seccomp filter of 0 / 50 / 150 / 300 compares, allowed syscall | **no difference** (kernel ≥5.11 caches constant decisions per syscall number) |
|
||||
| ptrace + seccomp, tracer and tracee on the **same core** | 6.2 µs (6.7 µs with register get/set) |
|
||||
| ptrace + seccomp, **unpinned** (as the app runs it) | 15.5 µs |
|
||||
| ptrace + seccomp, different cores (same cluster / across clusters) | 34–36 / 42–61 µs |
|
||||
| ptrace with a spinning tracer, different cores | 20 µs (the tracee's side still has to wake) |
|
||||
| seccomp user-notification (the "modern proot" design) | 5.7 µs same core, 34–58 µs across, 43 µs unpinned; `SYNC_WAKE_UP` doesn't help |
|
||||
| **in-process SIGSYS** (`SECCOMP_RET_TRAP`) | **0.83 µs** |
|
||||
| openat2 `RESOLVE_IN_ROOT` (kernel-side chroot lookup) | 1.0 µs, but **blocked in apps** |
|
||||
|
||||
Takeaways:
|
||||
- The tracer's own work is about 8 µs of the ~14 µs same-core trap. Everything above that is
|
||||
scheduling.
|
||||
- Moving to seccomp user-notification would be a rewrite for no gain.
|
||||
- The filter's length doesn't matter. What matters is not breaking the kernel's cache:
|
||||
- **Any check on an argument or the instruction pointer must come after the syscall-number
|
||||
dispatch.** The first version of 0014 checked the address first. That made every syscall in
|
||||
the session run the whole filter, and cost +0.5 ms per exec.
|
||||
- Patches 0004 and 0013 already follow this rule.
|
||||
|
||||
### One tracer for everything (`parstat`: N threads doing `stat`)
|
||||
|
||||
| | 1 thread | 4 threads | 8 threads |
|
||||
|---|---|---|---|
|
||||
| one proot | 37k/s, 27 µs | 74–95k/s, 42–54 µs | 68–89k/s, **90–118 µs** each |
|
||||
| two proots, 2 threads each | | 187k/s total, 21 µs | |
|
||||
| proot + fast path | 1.64M/s, 0.6 µs | 2.76M/s | **3.60M/s, 2.2 µs** |
|
||||
|
||||
A burst of path calls on several threads therefore queues behind the single tracer. CEF loading
|
||||
assets, Proton's Python, a game streaming files on worker threads and the shader-cache threads all
|
||||
produce such bursts.
|
||||
|
||||
### CPU placement
|
||||
|
||||
The workload ran with `taskset`; no fast path. Times are per traced call, and the last column is one
|
||||
fork + exec.
|
||||
|
||||
| affinity | stat | exec |
|
||||
|---|---|---|
|
||||
| default | 25.8 µs | 750 µs |
|
||||
| one core | 14.0 µs | 370 µs |
|
||||
| the two prime cores | 14.6 µs | |
|
||||
| the six-core cluster | 25.9 µs | |
|
||||
|
||||
The scheduler's wake-affine placement helps when it can put the tracer and the tracee together, and
|
||||
spreading them apart hurts. **Never pin the tracer away from its tracees.** Today `raiseTracer`
|
||||
only renices it, which is correct.
|
||||
|
||||
### Whole programs
|
||||
|
||||
Times are in ms, each with proot's ~40 ms start-up already subtracted.
|
||||
|
||||
| | direct glibc | vanilla proot | this repo's proot | + fast path |
|
||||
|---|---|---|---|---|
|
||||
| python3: 10 stdlib imports | 75–89 | ~130 | ~110 | ~90 (878 of 879 path calls answered in-process) |
|
||||
| tar of 2.7k files | 10–40 | ~180 | ~80 | ~20 |
|
||||
| 200 × fork+exec of `true` | 230 | ~600 | ~500 | ~500 |
|
||||
| find over 2.7k files | 16–23 | noisy | noisy | unchanged: glibc's fts calls internal entry points |
|
||||
|
||||
## Android's app seccomp policy decides more than proot does
|
||||
|
||||
The app filter is generated from bionic's `SYSCALLS.TXT`, minus the blocklists, plus the
|
||||
allowlists. It is the same for every app whatever its `targetSdk`, and anything not listed gets
|
||||
`SECCOMP_RET_TRAP`, a `SIGSYS`. Filters stack, and the strictest one wins: a blocked call never
|
||||
reaches proot's `RET_TRACE`. It arrives as a `SIGSYS` stop, and proot answers it (usually `ENOSYS`).
|
||||
|
||||
Checked against bionic `android16-release`:
|
||||
|
||||
| syscall | app policy | who calls it |
|
||||
|---|---|---|
|
||||
| `rseq`, `set_robust_list` | **blocked** | glibc, at the start of every thread, while all signals are blocked |
|
||||
| `faccessat2` | **blocked** | glibc's `faccessat()`, which tries it on **every** call before falling back, so 2 round trips (`access()` calls the plain `faccessat` syscall directly) |
|
||||
| `fchmodat2`, `openat2` | **blocked** | newer glibc, Flatpak/libglnx |
|
||||
| `setuid`, `setgid` and the rest of the family | **blocked** | Xwayland (hence `-i`) |
|
||||
| `futex_waitv`, `io_uring_*`, `landlock_*` | **blocked** | Proton's fsync, some engines |
|
||||
| `clone3` | blocked before Android 15 | glibc `pthread_create` |
|
||||
| `close_range` | blocked on Android 12 | |
|
||||
| `statx`, `process_vm_readv`/`writev`, `memfd_create`, `pidfd_*`, `seccomp` | allowed | |
|
||||
|
||||
On top of the ptrace round trips, every one of these costs a signal round trip through proot.
|
||||
|
||||
## Every traced syscall: what it needs and whether it can bypass proot
|
||||
|
||||
This is the filter of termux proot at `source.env` plus patches 0001–0013. "Fast path" means the
|
||||
call can be answered in-process with the 0014 design.
|
||||
|
||||
| syscalls | why proot traps them | can it bypass proot? |
|
||||
|---|---|---|
|
||||
| `openat`/`open`/`creat`, `newfstatat`/`stat`/`lstat`, `statx`, `faccessat`/`access`, `readlinkat` (exit), `mkdirat`, `unlinkat`, `renameat(2)`, `symlinkat`, `linkat`, `fchmodat`, `fchownat`, `utimensat`, `truncate`, `*xattr`, `inotify_add_watch`, `name_to_handle_at` | path translation (guest → host), plus exit fixups for `readlink` and `rename` | **Yes, through libc wrappers.** The prototype covers open, stat, statx, access, readlink, opendir and fopen; the write family is next. Raw `svc` and glibc's internal callers (ld.so, fts, realpath, nss) still go to proot. |
|
||||
| `chdir`/`fchdir`, `getcwd` (exit) | proot emulates the cwd; until 0014 the kernel's cwd never moved | With 0014 the kernel's cwd follows the guest's. `getcwd` stays in proot (cheap, rare). |
|
||||
| `execve`/`execveat` | runs the loader, maps `PT_INTERP` inside the rootfs, shebangs, tracks `/proc/self/exe` | **No.** This is the core of what proot is for. Costs 0.4–0.8 ms per exec; the session scripts already avoid exec-heavy loops (`nap`). |
|
||||
| `brk` (entry and exit) | heap emulation: programs are mapped by proot's loader, so the kernel's brk area is the loader's | No (`PR_SET_MM` needs `CAP_SYS_RESOURCE`). **Fewer calls:** `GLIBC_TUNABLES=glibc.malloc.top_pad=…` grows the heap in larger steps. |
|
||||
| `bind`, `connect`, `accept(4)`, `getsockname`, `getpeername` | `sun_path` of Unix sockets | Same-path binds (runtime dir, files dir) need no translation, but the filter can't see the address. Possible fast-path candidate. |
|
||||
| `wait4`/`waitpid`, `ptrace` | ptrace emulation inside the guest (breakpad, gdb) | Could become opt-in; then `wait4` is free (one stop per wait today). |
|
||||
| `prctl(PR_SET_DUMPABLE)`, `setrlimit`/`prlimit64(RLIMIT_STACK)` | loader and stack fixups | Already narrowed to these arguments (0004). |
|
||||
| `ioctl(TCSETSF, termios2, FICLONE)` | Android pty policy, FICLONE `EACCES` | Already narrowed to these requests; GPU ioctls are free (0013). |
|
||||
| `uname`, `sethostname`, `setdomainname` | the `DroidDeck` hostname (kompat) | Rare. Keep. |
|
||||
| `set*id`, `*setxattr` | fake_id0 identity mode (0012) | Rare. Keep. |
|
||||
| `memfd_create` | Qt JIT and php workarounds (string argument) | Every Wayland `wl_shm` buffer and Chromium shared memory pays one stop. Could be dropped if the DroidDeck runtime doesn't need those workarounds. |
|
||||
| `statfs` (exit) | fakes tmpfs for `/dev/shm` | Rare. |
|
||||
| `open_tree`, `move_mount`, `fspick`, `mount_setattr`, `openat2` | answered `ENOSYS` (0008, 0010) | Fine. |
|
||||
| Android-blocked calls (previous table) | `SIGSYS` emulation | **Avoidable at the source:** `GLIBC_TUNABLES=glibc.pthread.rseq=0` removes one stop per thread. The rest need a patched glibc. |
|
||||
| clone/fork/vfork/exec/exit events | tracking tracees | Needed while proot traces. |
|
||||
|
||||
## Options weighed
|
||||
|
||||
1. **Pure glibc, no proot.** Rejected as the main path, for the reasons in the short answer.
|
||||
- Closest prior art: huntergdavis/steamclienttermux, which runs `steamrtarm64` on a patched
|
||||
Termux glibc 2.44 with an exec shim and a `/tmp` and `/dev/shm` redirect preload.
|
||||
- They report Steam's first window 7× faster and about 5% more FPS, with proot having used 60–65%
|
||||
of a core.
|
||||
- **They still run Proton and the games under proot.**
|
||||
- DroidDeck also has four package names (`tools/release/variants.txt`), so a relocated prefix
|
||||
would need four builds or Winlator-style padded path rewriting.
|
||||
2. **Hybrid by process (Steam in proot, game on glibc, or the reverse).** The game side is the
|
||||
*harder* half. Wine re-execs itself and `wineserver`, which hits `PT_INTERP`. Its server
|
||||
directory is hard-coded under `/tmp`, and Proton's esync and fsync use `shm_open` (`/dev/shm`)
|
||||
and `futex_waitv`, which is blocked. A game's steady state is already mostly untraced, so the
|
||||
gain is in loading. Not worth it before the fast path.
|
||||
3. **Seccomp user-notification instead of ptrace.** It measures the same as ptrace, and it can't
|
||||
rewrite arguments, so every call would have to be emulated. No.
|
||||
4. **In-process `SIGSYS` for everything** (0.8 µs). The kernel resets a blocked `SIGSYS` to the
|
||||
default action and kills the process (`force_sig_seccomp`, `HANDLER_CURRENT`). glibc and Wine
|
||||
block all signals around exactly these calls. Unsafe without also trapping `rt_sigprocmask`. No.
|
||||
5. **proot plus an in-process fast path (this branch).** Recommended. Details below.
|
||||
6. **A proot-aware glibc**, the follow-up to 5. Rebuild the rootfs's own glibc (same version, same
|
||||
Arch package) with two changes:
|
||||
- its internal path entry points (`__open_nocancel`, `__fstatat64`, ld.so's opens) go through the
|
||||
fast path, which covers ld.so, fts, realpath and nss;
|
||||
- it never makes the Android-blocked calls, as Termux's `fakesyscall.json` does.
|
||||
|
||||
This removes the remaining library-loading traps and all the `SIGSYS` round trips. The rootfs is
|
||||
versioned (`linuxfs-rN`), so glibc rebuilds stay under control.
|
||||
7. **On the tracer side, with no in-process changes:**
|
||||
- **A second proot for the game tree.** Measured 2.5× trap throughput, and Steam/CEF bursts no
|
||||
longer stall the game. `BwrapSpawner` already shows the pattern: a stand-in process in the
|
||||
session relays stdio, the exit status and signals to a proot started from the app.
|
||||
- Leave the tracer unpinned (above).
|
||||
- Set `GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216` in the session
|
||||
environment.
|
||||
|
||||
## The fast path (prototype)
|
||||
|
||||
The code is `tools/proot/fastpath/fastpath.c`, preloaded into every guest process. On the proot side
|
||||
it needs `patches/0014`, enabled with `PROOT_FASTPATH=1`.
|
||||
|
||||
- **Trampoline.** The library maps a 4 KiB executable page at the fixed address `0xffff00000`. It
|
||||
holds `mov x8,x0 … svc #0; ret`. With `PROOT_FASTPATH`, proot's filter checks the caller's address
|
||||
just before each `RET_TRACE` and allows syscalls coming from that page.
|
||||
- **Mapping a path.** The library takes the literal guest path and finds the longest binding whose
|
||||
guest path is a prefix of it; otherwise the path is under the rootfs.
|
||||
- It opens the *parent* host directory `O_PATH` and requires `/proc/self/fd` to name exactly that
|
||||
path. That proves no component on the way was a symlink, so proot would have walked the same
|
||||
directories.
|
||||
- The last component is never followed: a symlink there goes to proot.
|
||||
- **Missing files.** For a missing file, the deepest existing ancestor is verified the same way, and
|
||||
the next component must not exist even as a symlink. Then `ENOENT` is exact.
|
||||
- **What always goes to proot:**
|
||||
- `..`, a trailing `/`, `/proc`, `/dev/fd` and `/dev/std*`;
|
||||
- `O_TMPFILE`, `AT_EACCESS`, and any flag not handled;
|
||||
- any doubt at all. "Go to proot" means calling the real libc function, so proot decides.
|
||||
- **Relative paths.** Patch 0014 keeps the kernel's cwd at the guest cwd's host directory. Relative
|
||||
and dirfd lookups are mapped through `/proc/self/{cwd,fd/N}`.
|
||||
- **Verified-parent cache.** Verified parents are cached for 2 s (`PROOT_FP_TTL_MS`). That is the
|
||||
same trade-off `preload/pathcache.c` already makes for the Steam client. A parent directory turned
|
||||
into a symlink inside that window would be missed; `PROOT_FP_TTL_MS=0` verifies every call, at
|
||||
2.0 µs instead of 0.6 µs.
|
||||
- **Allowed syscalls only.** It uses only `openat`, `newfstatat`, `statx`, `faccessat`, `readlinkat`
|
||||
and `close`, all allowed for apps. A first version used `openat2 RESOLVE_IN_ROOT`, which the app
|
||||
policy blocks.
|
||||
- **Equivalence check.** `bench/equiv.py` runs stat, lstat, readlink, read, listdir and access over
|
||||
awkward paths, from several working directories and through a dirfd. Its output is byte-identical
|
||||
with and without the fast path, at TTL 0 and at TTL 2000. The paths include:
|
||||
- absolute and relative symlinks into binds, `..` symlinks, dangling links and loops;
|
||||
- files inside binds, nested binds (`/dev/shm` inside `/dev`) and `/proc`;
|
||||
- missing paths behind symlinks.
|
||||
|
||||
### Open items before shipping it
|
||||
|
||||
- **Validate inside the app**, not just from adb. Three things to check:
|
||||
- The app domain allows an anonymous `PROT_EXEC` page (`execmem`). If not, map a page of the
|
||||
library file itself at the fixed address instead, as proot's loader does for every program.
|
||||
- Nothing claims `0xffff00000` first.
|
||||
- The stub's syscalls pass Android's filter. They should: all are allowed.
|
||||
- **Integrate into `libblsession.so`** rather than a second preload. `opens.c` and `pathcache.c`
|
||||
already define `open` and `access`, so their "real" call should become the fast path. That also
|
||||
removes the second library's load cost, about 0.2–0.4 ms per exec that is still unexplained (see
|
||||
the exec row above).
|
||||
- **Wire the launcher.** The app already knows the binds (`LinuxRuntime.binds`):
|
||||
- set `PROOT_FASTPATH=1` in proot's environment;
|
||||
- pass `PROOT_FP_ROOT` and `PROOT_FP_BINDS` to the guest;
|
||||
- add a Performance toggle next to "Run proot without seccomp", with the fast path off whenever
|
||||
seccomp is off.
|
||||
- **Cover the write family** (mkdir, unlink, rename, symlink, chmod, utimens) and Unix-socket
|
||||
`connect`/`bind` for same-path binds. Then measure a real Steam start in the app, a game load,
|
||||
and `PROOT_FP_STATS` hit rates for steam, steamwebhelper, wine and wineserver.
|
||||
- **FEX**, inside Proton as a DLL, translates x86 path syscalls through glibc's `syscall()`, not the
|
||||
wrappers, so they still trap. A `syscall()` hook could route `openat` and `newfstatat` there too.
|
||||
@@ -117,9 +117,6 @@ docker run --rm --platform linux/amd64 \
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libblsession.so" tools/linuxfs/preload/*.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libblsession.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$d/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$d/libblfastpath.so"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$d/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
@@ -127,6 +124,7 @@ docker run --rm --platform linux/amd64 \
|
||||
[ -f "$f" ] && install -Dm644 "$f" "$d/${f#tools/linuxfs/overlay/}"
|
||||
done
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-plasma-mobile "$d/usr/local/bin/droiddeck-plasma-mobile"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/autostart "$d/etc/xdg/labwc/autostart"
|
||||
@@ -161,6 +159,8 @@ docker run --rm --platform linux/amd64 \
|
||||
test -f "$d/usr/local/bin/bannerlator-proton-extra"
|
||||
'
|
||||
|
||||
"${repo_root}/tools/plasma-mobile/build.sh"
|
||||
|
||||
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
|
||||
if [[ -z "${github_repo}" ]]; then
|
||||
origin_url=$(git -C "${repo_root}" remote get-url origin)
|
||||
@@ -224,13 +224,9 @@ while read -r package_sha256 package_url; do
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
|
||||
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
|
||||
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
|
||||
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1 libtracefs.so.1; do
|
||||
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
|
||||
done
|
||||
# Ours, not the package's: GPU memory without tracefs (tools/mangoapp/libtracefs-shim.c).
|
||||
docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
|
||||
-o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c
|
||||
mkdir -p "${linuxfs_dir}/usr/local/bin"
|
||||
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
|
||||
|
||||
|
||||
@@ -39,13 +39,5 @@ library list, before anything is published.
|
||||
then focus is handed over again. `GAMESCOPE_RESTORE_FOCUS_WINDOW` on the root window asks for the
|
||||
same restore from outside (the session script's resume watcher).
|
||||
|
||||
- `0113-steam-overlay-keeps-game-keyboard-focus.patch` - this app: the Steam client opens the Quick
|
||||
Access Menu and Steam menu over a game with `STEAM_INPUT_FOCUS` 1, which moves X keyboard focus to
|
||||
its overlay; wine then deactivates the game and a fullscreen game minimizes itself, freezing
|
||||
behind the menu instead of running on as on a Steam Deck. Steam's own overlay taking input now
|
||||
keeps keyboard focus on the game, as mode 2 does; its input comes from the controller through
|
||||
Steam Input, not the X keyboard. The pointer warps gamescope makes as input moves to Steam and
|
||||
back are skipped around it, since the game - still taking input - saw them as a mouse jump.
|
||||
|
||||
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
|
||||
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
|
||||
@@ -1,104 +0,0 @@
|
||||
From: DroidDeck
|
||||
Subject: [PATCH] steamcompmgr: keep the game's keyboard focus under Steam's overlay
|
||||
|
||||
The Steam client opens its Quick Access Menu and Steam menu over a game by setting
|
||||
STEAM_OVERLAY 1 and STEAM_INPUT_FOCUS 1 on its window. Mode 1 moves X keyboard focus to the
|
||||
overlay, so the game's window gets FocusOut: wine moves the foreground to the desktop, a fullscreen
|
||||
game deactivates and minimizes itself (WM_CHANGE_STATE IconicState), and it stops rendering behind
|
||||
the menu - frozen, all threads asleep, until the menu closes (Alan Wake's American Nightmare,
|
||||
Proton Experimental ARM64). On a Steam Deck the game runs on behind the menu.
|
||||
|
||||
Mode 2 already means "input to the overlay, keyboard focus stays on the focus window". Treat
|
||||
Steam's own overlay taking input in mode 1 the same way at the three places mode 2 is honoured.
|
||||
The overlay's input does not need X keyboard focus: the controller drives it through Steam Input.
|
||||
Measured by rewriting the property to 2 by hand: the game kept running behind the menu and the
|
||||
controller still moved only the menu.
|
||||
|
||||
With the game keeping focus, the pointer resets gamescope makes when input moves to Steam (warp
|
||||
to the centre, park in the corner) and back (warp to the centre) reached it as a sudden mouse
|
||||
move: a mouse-look camera spun every time the menu opened and closed. Skip them while Steam's
|
||||
overlay opens over a game that keeps focus, and as it closes - by then the overlay has dropped its
|
||||
STEAM_INPUT_FOCUS, so whether the opening kept focus is remembered.
|
||||
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index 372a82c..3fab3c6 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -1321,6 +1321,22 @@ window_is_steam( steamcompmgr_win_t *w )
|
||||
return w && ( w->isSteamLegacyBigPicture || w->appID == 769 );
|
||||
}
|
||||
|
||||
+// Whether keyboard focus stays on the focus window while this window has input focus.
|
||||
+// STEAM_INPUT_FOCUS 2 asks for that. The Steam client also opens its Quick Access Menu and Steam
|
||||
+// menu over a game with 1, which moves X keyboard focus to the overlay: wine then deactivates the
|
||||
+// game, a fullscreen game minimizes itself, and it froze behind the menu instead of running on as
|
||||
+// on a Steam Deck. The overlay's own input does not need X keyboard focus (the controller drives
|
||||
+// it through Steam Input), so Steam's overlay keeps the game's keyboard focus too.
|
||||
+static bool
|
||||
+window_keeps_game_keyboard_focus( steamcompmgr_win_t *w )
|
||||
+{
|
||||
+ if ( !w )
|
||||
+ return false;
|
||||
+ if ( w->inputFocusMode == 2 )
|
||||
+ return true;
|
||||
+ return w->inputFocusMode == 1 && w->isOverlay && window_is_steam( w );
|
||||
+}
|
||||
+
|
||||
static bool
|
||||
window_is_vr_scene_app( steamcompmgr_win_t *w )
|
||||
{
|
||||
@@ -4728,7 +4744,7 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
|
||||
|
||||
if ( gamescope::VirtualConnectorIsSingleOutput() )
|
||||
{
|
||||
- if ( inputFocus && inputFocus->inputFocusMode == 2 )
|
||||
+ if ( window_keeps_game_keyboard_focus( inputFocus ) )
|
||||
keyboardFocusWin = ctx->focus.focusWindow;
|
||||
}
|
||||
else
|
||||
@@ -4834,12 +4850,26 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
|
||||
if ( ctx->focus.inputFocusWindow != inputFocus ||
|
||||
ctx->focus.inputFocusMode != inputFocus->inputFocusMode )
|
||||
{
|
||||
+ // Steam's overlay opening over a game, or closing again, while the game keeps keyboard focus
|
||||
+ // (window_keeps_game_keyboard_focus): the game is still taking input, so a pointer warp
|
||||
+ // reaches it as a sudden mouse move - the camera of a mouse-look game spun as the Quick
|
||||
+ // Access Menu opened and as it closed. The overlay is driven by the controller and the
|
||||
+ // cursor is hidden, so leave the pointer where it is. Closing, the overlay has already
|
||||
+ // dropped its STEAM_INPUT_FOCUS, so whether the opening kept focus is remembered.
|
||||
+ static bool s_bOverlayKeptGameFocus = false;
|
||||
+ bool bOverlayKeepsGameFocus = window_keeps_game_keyboard_focus( inputFocus ) &&
|
||||
+ ctx->focus.focusWindow && !window_is_steam( ctx->focus.focusWindow );
|
||||
+ bool bSkipPointerReset = bOverlayKeepsGameFocus || s_bOverlayKeptGameFocus;
|
||||
+ s_bOverlayKeptGameFocus = bOverlayKeepsGameFocus;
|
||||
+
|
||||
// If the window doesn't want focus when hidden, move it away
|
||||
// as we are going to hide it straight after.
|
||||
// otherwise, if we switch from wanting it to not
|
||||
// (steam -> game)
|
||||
// put us back in the centre of the screen.
|
||||
- if (window_wants_no_focus_when_mouse_hidden(inputFocus))
|
||||
+ if ( bSkipPointerReset )
|
||||
+ ;
|
||||
+ else if (window_wants_no_focus_when_mouse_hidden(inputFocus))
|
||||
ctx->focus.bResetToCorner = true;
|
||||
else if ( window_wants_no_focus_when_mouse_hidden(inputFocus) != window_wants_no_focus_when_mouse_hidden(ctx->focus.inputFocusWindow) )
|
||||
ctx->focus.bResetToCenter = true;
|
||||
@@ -5340,7 +5370,7 @@ determine_and_apply_focus( global_focus_t *pFocus )
|
||||
pFocus->inputFocusMode = pFocus->inputFocusWindow->inputFocusMode;
|
||||
|
||||
if ( gamescope::VirtualConnectorIsSingleOutput() &&
|
||||
- pFocus->inputFocusMode == 2 )
|
||||
+ window_keeps_game_keyboard_focus( pFocus->inputFocusWindow ) )
|
||||
{
|
||||
pFocus->keyboardFocusWindow = pFocus->overrideWindow
|
||||
? pFocus->overrideWindow
|
||||
@@ -6485,7 +6515,7 @@ handle_wl_surface_id(xwayland_ctx_t *ctx, steamcompmgr_win_t *w, uint32_t surfac
|
||||
steamcompmgr_win_t *keyboardFocusWindow = pCurrentFocus->inputFocusWindow;
|
||||
|
||||
if ( gamescope::VirtualConnectorIsSingleOutput() &&
|
||||
- keyboardFocusWindow && keyboardFocusWindow->inputFocusMode == 2 )
|
||||
+ window_keeps_game_keyboard_focus( keyboardFocusWindow ) )
|
||||
keyboardFocusWindow = pCurrentFocus->focusWindow;
|
||||
|
||||
if ( w == keyboardFocusWindow )
|
||||
@@ -1,2 +1,2 @@
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p5
|
||||
GAMESCOPE_SHA256=188144e5564e020d0bc485a1f4f90e1c5fd61d0d1d6dd29db21e8b019036a5c6
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p4
|
||||
GAMESCOPE_SHA256=e750fb34864bc2eb1160aeed29593e402bf9c8153fafd9fd18c77450bdd50574
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/bin/bash
|
||||
# Run Plasma Mobile inside a nested KWin Wayland session.
|
||||
set -u
|
||||
|
||||
export XDG_SESSION_TYPE=wayland
|
||||
export XDG_SESSION_DESKTOP=KDE
|
||||
export XDG_CURRENT_DESKTOP=KDE
|
||||
export QT_QPA_PLATFORM=wayland
|
||||
export QT_QPA_PLATFORMTHEME=KDE
|
||||
export QT_WAYLAND_DISABLE_WINDOWDECORATION=1
|
||||
export EGL_PLATFORM=wayland
|
||||
export QT_QUICK_CONTROLS_STYLE=org.kde.breeze
|
||||
export QT_ENABLE_GLYPH_CACHE_WORKAROUND=1
|
||||
export QT_QUICK_CONTROLS_MOBILE=1
|
||||
export KSCREEN_BACKEND=QScreen
|
||||
export KDE_FULL_SESSION=1
|
||||
export KDE_SESSION_VERSION=6
|
||||
export XDG_MENU_PREFIX=plasma-
|
||||
export PLASMA_INTEGRATION_USE_PORTAL=1
|
||||
export PLASMA_PLATFORM=phone:handset
|
||||
export PLASMA_DEFAULT_SHELL=org.kde.plasma.mobileshell
|
||||
export XDG_CONFIG_DIRS="$HOME/.config/plasma-mobile:/etc/xdg:${XDG_CONFIG_DIRS:-}"
|
||||
export GDK_BACKEND=wayland,x11
|
||||
export SDL_VIDEODRIVER=wayland,x11
|
||||
|
||||
if [ -n "${BL_DEBUG_DIR:-}" ]; then
|
||||
mkdir -p "$BL_DEBUG_DIR" 2>/dev/null || true
|
||||
exec >>"$BL_DEBUG_DIR/desktop.log" 2>&1
|
||||
echo "== droiddeck-plasma-mobile $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${BL_WIDTH:-1280}x${BL_HEIGHT:-720}"
|
||||
fi
|
||||
|
||||
if ! command -v plasmashell >/dev/null 2>&1 || ! command -v dbus-run-session >/dev/null 2>&1; then
|
||||
echo "== Plasma Mobile packages are missing; choose KDE Plasma Mobile in Desktop settings and start Desktop once"
|
||||
exit 66
|
||||
fi
|
||||
|
||||
plasma_log="${BL_DEBUG_DIR:-/tmp}/plasma.log"
|
||||
echo "== Plasma $(plasmashell --version 2>&1)"
|
||||
echo "== Wayland display ${WAYLAND_DISPLAY:-wayland-0}; XDG runtime $XDG_RUNTIME_DIR"
|
||||
mkdir -p /tmp || exit 73
|
||||
chmod 1777 /tmp || echo "== could not set standard temporary-directory permissions"
|
||||
export TMPDIR=/tmp
|
||||
echo "== temporary directories: $(ls -ld /tmp /dev/shm 2>&1)"
|
||||
echo "== preparing the KDE Plasma Mobile Wayland session"
|
||||
: >"$plasma_log"
|
||||
|
||||
# Gamescope's Zink override is for game clients. KWin owns the Plasma Mobile session and presents
|
||||
# one nested Wayland window through Bannerlator's host compositor.
|
||||
export QT_QUICK_BACKEND=software
|
||||
unset MESA_LOADER_DRIVER_OVERRIDE GALLIUM_DRIVER LIBGL_KOPPER_DRI2 ZINK_DESCRIPTORS mesa_glthread MESA_NO_ERROR
|
||||
|
||||
# The PRoot guest has no systemd user manager. Hide only its session-bus activation entry while
|
||||
# KDE starts, and restore it on every exit.
|
||||
systemd_dbus_service=/usr/share/dbus-1/services/org.freedesktop.systemd1.service
|
||||
systemd_dbus_service_disabled="$systemd_dbus_service.droiddeck-disabled"
|
||||
restore_systemd_dbus_service() {
|
||||
if [ -e "$systemd_dbus_service_disabled" ] && [ ! -e "$systemd_dbus_service" ]; then
|
||||
mv "$systemd_dbus_service_disabled" "$systemd_dbus_service" || echo "== could not restore systemd D-Bus service file"
|
||||
fi
|
||||
}
|
||||
restore_systemd_dbus_service
|
||||
if [ -f "$systemd_dbus_service" ]; then
|
||||
mv "$systemd_dbus_service" "$systemd_dbus_service_disabled" || echo "== could not disable session-bus activation for systemd1"
|
||||
fi
|
||||
trap restore_systemd_dbus_service EXIT
|
||||
dbus-run-session -- env XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" plasma_log="$plasma_log" sh -c '
|
||||
export WAYLAND_DISPLAY=wayland-0
|
||||
width=${BL_WIDTH:-1280}
|
||||
height=${BL_HEIGHT:-720}
|
||||
rm -f "$XDG_RUNTIME_DIR/wayland-1" "$XDG_RUNTIME_DIR/wayland-1.lock"
|
||||
# D-Bus activation inherited the outer compositor socket. KDE services activated later must
|
||||
# connect to the nested socket, while KWin itself continues to connect to the outer one.
|
||||
if command -v dbus-update-activation-environment >/dev/null 2>&1; then
|
||||
WAYLAND_DISPLAY=wayland-1 dbus-update-activation-environment WAYLAND_DISPLAY >>"$plasma_log" 2>&1
|
||||
echo "== D-Bus activation Wayland display update status $?"
|
||||
fi
|
||||
if command -v plasma-mobile-envmanager >/dev/null 2>&1; then
|
||||
echo "== applying Plasma Mobile device settings"
|
||||
QT_QPA_PLATFORM=offscreen plasma-mobile-envmanager --apply-settings >>"$plasma_log" 2>&1
|
||||
echo "== Plasma Mobile environment setup status $?"
|
||||
else
|
||||
echo "== plasma-mobile-envmanager is missing"
|
||||
fi
|
||||
# This guest has no interactive login from which the user can set a Linux password. The Plasma
|
||||
# Mobile PIN keypad authenticates that account password, so an idle/lock event can strand a
|
||||
# device user at a screen they cannot unlock. Keep session locking disabled for this embedded
|
||||
# desktop and let Android own the device lock instead.
|
||||
lock_config="${XDG_CONFIG_HOME:-$HOME/.config}/kscreenlockerrc"
|
||||
mkdir -p "$(dirname "$lock_config")"
|
||||
if command -v kwriteconfig6 >/dev/null 2>&1; then
|
||||
kwriteconfig6 --file "$lock_config" --group Daemon --key Autolock false
|
||||
kwriteconfig6 --file "$lock_config" --group Daemon --key LockOnResume false
|
||||
kwriteconfig6 --file "$lock_config" --group Daemon --key RequirePassword false
|
||||
kwriteconfig6 --file "$lock_config" --group Daemon --key Timeout 0
|
||||
echo "== disabled Plasma screen locking in $lock_config"
|
||||
else
|
||||
echo "== kwriteconfig6 is missing; could not disable Plasma screen locking"
|
||||
fi
|
||||
if command -v kbuildsycoca6 >/dev/null 2>&1; then
|
||||
echo "== building KDE service cache"
|
||||
QT_QPA_PLATFORM=offscreen kbuildsycoca6 --noincremental >>"$plasma_log" 2>&1
|
||||
cache_status=$?
|
||||
echo "== KDE service cache status $cache_status"
|
||||
cache_dir=${XDG_CACHE_HOME:-$HOME/.cache}
|
||||
for cache_file in "$cache_dir"/ksycoca6_*; do
|
||||
[ -f "$cache_file" ] || continue
|
||||
# KDE cache files land write-only under this PRoot user and cannot be reopened by service lookups.
|
||||
chmod u+rw "$cache_file" || echo "== could not make KDE cache readable: $cache_file"
|
||||
done
|
||||
else
|
||||
echo "== kbuildsycoca6 is missing"
|
||||
fi
|
||||
effect_config="${XDG_CONFIG_HOME:-$HOME/.config}/kwinrc"
|
||||
if command -v kwriteconfig6 >/dev/null 2>&1; then
|
||||
# The overview control in Plasma Mobile invokes this KWin effect. Keep it explicitly enabled
|
||||
# so the patched state/gesture initialization is active in the embedded session.
|
||||
kwriteconfig6 --file "$effect_config" --group Plugins --key mobiletaskswitcherEnabled true
|
||||
fi
|
||||
if command -v kreadconfig6 >/dev/null 2>&1; then
|
||||
effect_setting=$(kreadconfig6 --file "$effect_config" \
|
||||
--group Plugins --key mobiletaskswitcherEnabled 2>&1 || true)
|
||||
echo "== mobile task-switcher setting in $effect_config: ${effect_setting:-unset}"
|
||||
else
|
||||
echo "== kreadconfig6 is missing; cannot inspect the mobile task-switcher setting"
|
||||
fi
|
||||
echo "== starting nested KWin and Plasma Mobile on wayland-0 (${width}x${height}), socket wayland-1"
|
||||
# The mobile task switcher queries Workspace::activities() while filtering tasks.
|
||||
# Keep KActivities initialized; --no-kactivities makes the overview crash on activation.
|
||||
KWIN_WAYLAND_NO_PERMISSION_CHECKS=1 kwin_wayland \
|
||||
--xwayland \
|
||||
--wayland-display=wayland-0 \
|
||||
--socket=wayland-1 \
|
||||
--width="$width" --height="$height" --fullscreen \
|
||||
--no-lockscreen \
|
||||
--exit-with-session "plasmashell -p org.kde.plasma.mobileshell --replace" \
|
||||
>>"$plasma_log" 2>&1 &
|
||||
kwin_pid=$!
|
||||
cleanup() {
|
||||
if [ -n "$kwin_pid" ]; then kill "$kwin_pid" 2>/dev/null || true; wait "$kwin_pid" 2>/dev/null || true; fi
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
wait "$kwin_pid"
|
||||
' >>"$plasma_log" 2>&1
|
||||
result=$?
|
||||
restore_systemd_dbus_service
|
||||
trap - EXIT
|
||||
echo "== Plasma Mobile session exited (status $result)"
|
||||
exit "$result"
|
||||
@@ -1,195 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""The app's GOG store talks to Heroic's gogdl through this: one JSON object per line on stdout,
|
||||
so progress reaches the front end as numbers rather than log lines. The app puts gogdl in the
|
||||
runtime (GOGDL below) and keeps the sign-in in its own files (the auth path every command takes).
|
||||
Tokens never leave on stdout except from "token", whose output the app does not log.
|
||||
|
||||
bannerlator-gog login <auth> <code> trades the sign-in page's code for tokens
|
||||
bannerlator-gog token <auth> a current access token (refreshed when due)
|
||||
bannerlator-gog info <auth> <id> folder name and sizes of the Windows build
|
||||
bannerlator-gog install <auth> <id> <base> downloads into <base>/<folder name>
|
||||
bannerlator-gog update <auth> <id> <dir> brings an installed game to the latest build
|
||||
|
||||
Lines: {"e":"info",...}, {"e":"progress","percent":45,"written":..,"total":..},
|
||||
{"e":"error","message":"..."} and {"e":"done",...} at the end. Exit status 0 on success.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
GOGDL = "/opt/droiddeck/gogdl/gogdl"
|
||||
PLATFORM = "windows"
|
||||
MARKER = ".droiddeck-gog.json"
|
||||
PROGRESS = re.compile(r"= Progress: ([\d.]+) (\d+)/(\d+)")
|
||||
# gogdl's own log lines: "[NAME] LEVEL: message".
|
||||
LOG = re.compile(r"^\[([^\]]+)\] (\w+): (.*)$")
|
||||
|
||||
|
||||
def emit(**kw):
|
||||
sys.stdout.write(json.dumps(kw) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def gogdl(auth, *args):
|
||||
return [sys.executable or "/usr/bin/python3", GOGDL, "--auth-config-path", auth] + list(args)
|
||||
|
||||
|
||||
def last_json(text):
|
||||
"""gogdl prints its answer as the last JSON line of stdout, after anything else it says."""
|
||||
for line in reversed(text.splitlines()):
|
||||
line = line.strip()
|
||||
if line.startswith("{") or line == "null":
|
||||
try:
|
||||
return json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def quiet(auth, *args):
|
||||
"""Runs a gogdl command that answers in JSON; its log (stderr) is dropped, never echoed."""
|
||||
run = subprocess.run(gogdl(auth, *args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
return run.returncode, last_json(run.stdout), run.stderr
|
||||
|
||||
|
||||
def login(auth, code):
|
||||
os.makedirs(os.path.dirname(auth) or ".", exist_ok=True)
|
||||
status, data, _ = quiet(auth, "auth", "--code", code)
|
||||
if status != 0 or not isinstance(data, dict) or data.get("error") or not data.get("access_token"):
|
||||
emit(e="error", message="GOG did not accept the sign-in")
|
||||
return 1
|
||||
emit(e="done", user_id=str(data.get("user_id", "")))
|
||||
return 0
|
||||
|
||||
|
||||
def token(auth):
|
||||
if not os.path.isfile(auth):
|
||||
emit(e="error", message="signed out")
|
||||
return 1
|
||||
status, data, _ = quiet(auth, "auth")
|
||||
if status != 0 or not isinstance(data, dict) or not data.get("access_token"):
|
||||
emit(e="error", message="signed out")
|
||||
return 1
|
||||
expires = float(data.get("loginTime", 0)) + float(data.get("expires_in", 0))
|
||||
emit(e="token", access_token=data["access_token"], user_id=str(data.get("user_id", "")), expires=int(expires))
|
||||
return 0
|
||||
|
||||
|
||||
def sizes(size, language):
|
||||
"""Bytes to download and on disk: the depots every language needs ("*") plus one language's."""
|
||||
pick = [k for k in ("*", language) if k in size]
|
||||
if language not in size:
|
||||
pick += [k for k in size if k != "*"][:1]
|
||||
return (sum(int(size[k].get("download_size") or 0) for k in pick),
|
||||
sum(int(size[k].get("disk_size") or 0) for k in pick))
|
||||
|
||||
|
||||
def language_of(data):
|
||||
langs = data.get("languages") or []
|
||||
for want in ("en-US", "en"):
|
||||
if want in langs:
|
||||
return want
|
||||
return langs[0] if langs else "en-US"
|
||||
|
||||
|
||||
def info(auth, game_id, out=True):
|
||||
status, data, err = quiet(auth, "info", game_id, "--platform", PLATFORM, "--skip-dlcs")
|
||||
if status != 0 or not isinstance(data, dict) or not data.get("folder_name"):
|
||||
reason = failure(err) or "GOG has no Windows build of this game to download"
|
||||
if out:
|
||||
emit(e="error", message=reason)
|
||||
return None, reason
|
||||
language = language_of(data)
|
||||
download, disk = sizes(data.get("size") or {}, language)
|
||||
result = dict(folder=data["folder_name"], language=language, download_size=download, disk_size=disk,
|
||||
build=str(data.get("buildId", "")))
|
||||
if out:
|
||||
emit(e="info", **result)
|
||||
return result, None
|
||||
|
||||
|
||||
def failure(text):
|
||||
"""The last error gogdl logged, for the user; None when it logged none."""
|
||||
errors = [m.group(3) for m in (LOG.match(line) for line in (text or "").splitlines())
|
||||
if m and m.group(2) in ("ERROR", "CRITICAL")]
|
||||
return errors[-1] if errors else None
|
||||
|
||||
|
||||
def follow(argv):
|
||||
"""Runs a download, turning its progress lines into ours. Returns (status, last error)."""
|
||||
proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
|
||||
error, last = None, -1
|
||||
for line in proc.stdout:
|
||||
line = line.rstrip("\n")
|
||||
m = PROGRESS.search(line)
|
||||
if m:
|
||||
percent = int(float(m.group(1)))
|
||||
if percent != last:
|
||||
last = percent
|
||||
emit(e="progress", percent=percent, written=int(m.group(2)), total=int(m.group(3)))
|
||||
continue
|
||||
log = LOG.match(line)
|
||||
if log and log.group(2) in ("ERROR", "CRITICAL"):
|
||||
error = log.group(3)
|
||||
# Everything else goes to the app's log of this command as it is.
|
||||
sys.stdout.write(line + "\n")
|
||||
sys.stdout.flush()
|
||||
return proc.wait(), error
|
||||
|
||||
|
||||
def install(auth, game_id, base):
|
||||
data, _ = info(auth, game_id)
|
||||
if data is None:
|
||||
return 1
|
||||
target = os.path.join(base, data["folder"])
|
||||
os.makedirs(target, exist_ok=True)
|
||||
# Which game a folder is, from the first byte: the app lists a stopped download by it.
|
||||
with open(os.path.join(target, MARKER), "w", encoding="utf-8") as f:
|
||||
json.dump(dict(id=game_id, build=data["build"], language=data["language"]), f)
|
||||
status, error = follow(gogdl(auth, "download", game_id, "--platform", PLATFORM, "--path", base,
|
||||
"--skip-dlcs", "--lang", data["language"]))
|
||||
if status != 0 or not os.path.isfile(os.path.join(target, "goggame-%s.info" % game_id)):
|
||||
emit(e="error", message=error or "the download stopped (gogdl exit %d)" % status)
|
||||
return 1
|
||||
emit(e="done", dir=target)
|
||||
return 0
|
||||
|
||||
|
||||
def update(auth, game_id, target):
|
||||
data, _ = info(auth, game_id, out=False)
|
||||
language = data["language"] if data else "en-US"
|
||||
status, error = follow(gogdl(auth, "update", game_id, "--platform", PLATFORM, "--path", target,
|
||||
"--skip-dlcs", "--lang", language))
|
||||
if status != 0:
|
||||
emit(e="error", message=error or "the update stopped (gogdl exit %d)" % status)
|
||||
return 1
|
||||
emit(e="done", dir=target)
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 3:
|
||||
print(__doc__)
|
||||
return 2
|
||||
verb, auth, rest = argv[1], argv[2], argv[3:]
|
||||
if not os.path.isfile(GOGDL):
|
||||
emit(e="error", message="gogdl is not set up")
|
||||
return 1
|
||||
if verb == "login" and len(rest) == 1:
|
||||
return login(auth, rest[0])
|
||||
if verb == "token" and not rest:
|
||||
return token(auth)
|
||||
if verb == "info" and len(rest) == 1:
|
||||
return 0 if info(auth, rest[0])[0] else 1
|
||||
if verb == "install" and len(rest) == 2:
|
||||
return install(auth, rest[0], rest[1])
|
||||
if verb == "update" and len(rest) == 2:
|
||||
return update(auth, rest[0], rest[1])
|
||||
print(__doc__)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -126,8 +126,17 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
wayland-info >/dev/null 2>&1 && break
|
||||
sleep 0.1
|
||||
done
|
||||
# The desktop (DroidDeck's hosted package) is its own nested compositor, labwc, drawing straight
|
||||
# into the app's: no gamescope in between.
|
||||
# LXQt uses its nested compositor; Plasma Mobile starts a nested KWin session. The selected
|
||||
# primary desktop comes through BL_DESKTOP_ENV, while the independent secondary-display process
|
||||
# starts directly in plasma-mobile mode.
|
||||
if [ "$mode" = lxqt ] && [ "${BL_DESKTOP_ENV:-lxqt}" = plasma-mobile ]; then
|
||||
mode=plasma-mobile
|
||||
fi
|
||||
if [ "$mode" = plasma-mobile ]; then
|
||||
step "starting KDE Plasma Mobile"
|
||||
[ -x /usr/local/bin/droiddeck-plasma-mobile ] || { echo "== Plasma Mobile launcher is missing"; exit 66; }
|
||||
exec /usr/local/bin/droiddeck-plasma-mobile
|
||||
fi
|
||||
if [ "$mode" = lxqt ]; then
|
||||
step "starting the desktop"
|
||||
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
|
||||
@@ -140,16 +149,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 +159,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.
|
||||
@@ -172,8 +167,6 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
# HDR10: the app opened its compositor's colour-management gate for this session (BL_HDR=1);
|
||||
# gamescope then offers HDR to its clients through the same wp_color_manager_v1 it binds on ours.
|
||||
[ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
|
||||
# Extra gamescope arguments for an experiment (--debug-focus, say), from Download/droiddeck-env.
|
||||
[ -n "${BL_GAMESCOPE_ARGS:-}" ] && read -r -a _bl_extra <<<"$BL_GAMESCOPE_ARGS" && args+=("${_bl_extra[@]}")
|
||||
# Deck mode's performance overlay (Quick Access Menu → Performance → Overlay Level) is drawn by
|
||||
# mangoapp, which gamescope starts beside the client; the client sets the level by rewriting
|
||||
# MANGOHUD_CONFIGFILE. The apk stages Valve's aarch64 build (tools/mangoapp) - without it the menu
|
||||
@@ -447,37 +440,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
|
||||
|
||||
@@ -254,8 +254,7 @@ fi
|
||||
depot=
|
||||
best=0
|
||||
for name in %s; do
|
||||
for library in "$steam_root" /mnt/droiddeck-sd; do
|
||||
candidate="$library/steamapps/common/$name"
|
||||
candidate="$steam_root/steamapps/common/$name"
|
||||
[ -d "$candidate/files/bin-arm64" ] && [ -x "$candidate/proton" ] || continue
|
||||
build=0
|
||||
read -r build _ 2>/dev/null < "$candidate/version"
|
||||
@@ -264,7 +263,6 @@ for name in %s; do
|
||||
depot=$candidate
|
||||
best=$build
|
||||
fi
|
||||
done
|
||||
done
|
||||
if [ -n "$depot" ]; then
|
||||
bl_components "$depot"
|
||||
@@ -597,10 +595,10 @@ def depot_build(depot):
|
||||
|
||||
def find_source(steam_root):
|
||||
"""The newest ARM64 Proton depot the client has downloaded (the one the launcher runs), or None."""
|
||||
common = os.path.join(steam_root, "steamapps", "common")
|
||||
# bin-arm64 is what makes it the native build rather than the x86_64 one.
|
||||
found = [os.path.join(root, "steamapps", "common", name)
|
||||
for root in (steam_root, "/mnt/droiddeck-sd") for name in SOURCES
|
||||
if os.path.isdir(os.path.join(root, "steamapps", "common", name, "files", "bin-arm64"))]
|
||||
found = [os.path.join(common, name) for name in SOURCES
|
||||
if os.path.isdir(os.path.join(common, name, "files", "bin-arm64"))]
|
||||
return max(found, key=depot_build) if found else None
|
||||
|
||||
|
||||
|
||||
@@ -178,7 +178,7 @@ def unimported(steam_root, snapshot, candidates):
|
||||
|
||||
|
||||
def watch(steam_root, listing):
|
||||
games = [game for game in read_json(listing, []) if isinstance(game, dict) and not game.get("store")]
|
||||
games = read_json(listing, [])
|
||||
if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
|
||||
return
|
||||
candidates, sources = {}, {}
|
||||
@@ -344,10 +344,6 @@ def route(steam_root, acct, games):
|
||||
owned, candidates, sources = {}, {}, {}
|
||||
shortcuts, routes = [], {}
|
||||
for game in games:
|
||||
# A store's copy (GOG) is that store's game, never the Steam title of the same name.
|
||||
if game.get("store"):
|
||||
shortcuts.append(game)
|
||||
continue
|
||||
folder = game.get("folder", "")
|
||||
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
|
||||
stamp = source_stamp(game)
|
||||
|
||||
@@ -219,10 +219,9 @@ def main():
|
||||
for game in games:
|
||||
if not game.get("exe") or not game.get("name"):
|
||||
continue
|
||||
# A store's own launch arguments (a GOG play task's) unless the user has set some in Steam.
|
||||
entry = shortcut(game, game.get("args") or "")
|
||||
entry = shortcut(game)
|
||||
previous = managed.get(entry["appid"])
|
||||
if previous and isinstance(previous.get("LaunchOptions"), str) and previous["LaunchOptions"]:
|
||||
if previous and isinstance(previous.get("LaunchOptions"), str):
|
||||
entry["LaunchOptions"] = previous["LaunchOptions"]
|
||||
ours.append(entry)
|
||||
entries = {str(i): v for i, v in enumerate(kept + ours)}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
// libtracefs.so.1 for mangoapp: the GPU memory Valve's overlay reads, without the kernel's tracing.
|
||||
//
|
||||
// Valve's mangoapp (msm.cpp, ftrace_gpumem.c) takes the GPU's memory in use - the VRAM and PVRAM
|
||||
// lines - from the gpu_mem_total tracepoint (pid 0, the device's total) through libtracefs. An
|
||||
// Android app may not use tracefs at all: the instance could not be made, and both lines read 0.
|
||||
// This stands in for the libtracefs calls mangoapp makes, and hands its record walker one
|
||||
// gpu_mem_total record carrying what the app writes to /run/droiddeck-hud/gpu-mem (bytes; the
|
||||
// session's GpuMemComponent, from KGSL's own accounting). Only mangoapp loads this copy.
|
||||
//
|
||||
// The walker reads libtraceevent's structures directly, so the ones below are libtraceevent
|
||||
// 1.8.2's (event-parse.h), the version tools/mangoapp/packages.txt pins; tep_find_event_by_record
|
||||
// and tep_read_number are answered here too, ahead of the real libtraceevent in mangoapp's lookup.
|
||||
|
||||
#include <sched.h>
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define EXPORT __attribute__((visibility("default")))
|
||||
|
||||
struct tep_handle;
|
||||
struct tep_event;
|
||||
struct tep_print_arg;
|
||||
struct tep_print_parse;
|
||||
|
||||
struct tep_format_field {
|
||||
struct tep_format_field *next;
|
||||
struct tep_event *event;
|
||||
char *type;
|
||||
char *name;
|
||||
char *alias;
|
||||
int offset;
|
||||
int size;
|
||||
unsigned int arraylen;
|
||||
unsigned int elementsize;
|
||||
unsigned long flags;
|
||||
};
|
||||
|
||||
struct tep_format {
|
||||
int nr_common;
|
||||
int nr_fields;
|
||||
struct tep_format_field *common_fields;
|
||||
struct tep_format_field *fields;
|
||||
};
|
||||
|
||||
struct tep_print_fmt {
|
||||
char *format;
|
||||
struct tep_print_arg *args;
|
||||
struct tep_print_parse *print_cache;
|
||||
};
|
||||
|
||||
struct tep_event {
|
||||
struct tep_handle *tep;
|
||||
char *name;
|
||||
int id;
|
||||
int flags;
|
||||
struct tep_format format;
|
||||
struct tep_print_fmt print_fmt;
|
||||
char *system;
|
||||
void *handler;
|
||||
void *context;
|
||||
};
|
||||
|
||||
struct tep_record {
|
||||
unsigned long long ts;
|
||||
unsigned long long offset;
|
||||
long long missed_events;
|
||||
int record_size;
|
||||
int size;
|
||||
void *data;
|
||||
int cpu;
|
||||
int ref_count;
|
||||
int locked;
|
||||
void *priv;
|
||||
};
|
||||
|
||||
// gpu_mem_total's record: gpu_id, pid, size - as the kernel lays it out after the common fields.
|
||||
struct gpu_mem_total {
|
||||
unsigned int gpu_id;
|
||||
unsigned int pid;
|
||||
unsigned long long size;
|
||||
};
|
||||
|
||||
static struct tep_format_field size_field = {
|
||||
.name = "size", .offset = offsetof(struct gpu_mem_total, size), .size = 8};
|
||||
static struct tep_format_field pid_field = {
|
||||
.next = &size_field, .name = "pid", .offset = offsetof(struct gpu_mem_total, pid), .size = 4};
|
||||
static struct tep_event gpu_mem_event = {
|
||||
.name = "gpu_mem_total", .system = "gpu_mem", .format = {.nr_fields = 2, .fields = &pid_field}};
|
||||
|
||||
// Never dereferenced by mangoapp: they only have to be non-null.
|
||||
static char handle;
|
||||
static char instance;
|
||||
|
||||
static unsigned long long gpu_mem_bytes(void) {
|
||||
unsigned long long bytes = 0;
|
||||
FILE *f = fopen("/run/droiddeck-hud/gpu-mem", "r");
|
||||
if (f) {
|
||||
if (fscanf(f, "%llu", &bytes) != 1) bytes = 0;
|
||||
fclose(f);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
EXPORT void *tracefs_instance_create(const char *name) { (void)name; return &instance; }
|
||||
EXPORT char *tracefs_instance_get_dir(void *inst) { (void)inst; return strdup("/run/droiddeck-hud"); }
|
||||
EXPORT void tracefs_put_tracing_file(char *name) { free(name); }
|
||||
EXPORT struct tep_handle *tracefs_local_events(const char *dir) { (void)dir; return (struct tep_handle *)&handle; }
|
||||
EXPORT int tracefs_event_enable(void *inst, const char *system, const char *event) { (void)inst; (void)system; (void)event; return 0; }
|
||||
EXPORT int tracefs_event_disable(void *inst, const char *system, const char *event) { (void)inst; (void)system; (void)event; return 0; }
|
||||
EXPORT bool tracefs_instance_is_new(void *inst) { (void)inst; return false; }
|
||||
EXPORT int tracefs_instance_destroy(void *inst) { (void)inst; return 0; }
|
||||
EXPORT void tracefs_instance_free(void *inst) { (void)inst; }
|
||||
|
||||
EXPORT int tracefs_iterate_raw_events(struct tep_handle *tep, void *inst, cpu_set_t *cpus, int cpu_size,
|
||||
int (*callback)(struct tep_event *, struct tep_record *, int, void *),
|
||||
void *context) {
|
||||
(void)tep; (void)inst; (void)cpus; (void)cpu_size;
|
||||
if (!callback) return -1;
|
||||
struct gpu_mem_total data = {.gpu_id = 0, .pid = 0, .size = gpu_mem_bytes()};
|
||||
struct tep_record record = {.size = sizeof(data), .record_size = sizeof(data), .data = &data};
|
||||
callback(&gpu_mem_event, &record, 0, context);
|
||||
return 0;
|
||||
}
|
||||
|
||||
EXPORT struct tep_event *tep_find_event_by_record(struct tep_handle *tep, struct tep_record *record) {
|
||||
(void)tep; (void)record;
|
||||
return &gpu_mem_event;
|
||||
}
|
||||
|
||||
EXPORT unsigned long long tep_read_number(struct tep_handle *tep, const void *ptr, int size) {
|
||||
(void)tep;
|
||||
switch (size) {
|
||||
case 1: return *(const unsigned char *)ptr;
|
||||
case 2: return *(const unsigned short *)ptr;
|
||||
case 4: return *(const unsigned int *)ptr;
|
||||
case 8: return *(const unsigned long long *)ptr;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
EXPORT void tep_free(struct tep_handle *tep) { (void)tep; }
|
||||
@@ -1,4 +1,4 @@
|
||||
# Valve's aarch64 mangoapp (the Deck performance overlay) and the libraries it needs that the
|
||||
# Valve's aarch64 mangoapp (the Deck performance overlay) and the five libraries it needs that the
|
||||
# runtime does not have, at the versions it was built against (its .BUILDINFO: fmt 10.2.0,
|
||||
# spdlog 1.13.0). CI fetches each, checks the sha256 and stages the files named below into the apk
|
||||
# under usr/local/lib/mangoapp; SessionFiles copies them into the runtime at every launch.
|
||||
@@ -7,6 +7,5 @@
|
||||
ef7411229ea4e9b3ab4e36ac356a85b5072f362ee1de68b28d09c43f0b0ecc44 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/fmt-10.2.0-1-aarch64.pkg.tar.zst
|
||||
c9bfd2c3f15071329d381b9c2061d07503c4787ceb7001b9dfbf72a23c85cb04 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/spdlog-1.13.0-1-aarch64.pkg.tar.zst
|
||||
f9fae6c84a0382188f1cb20761424051593fd09b1456191cc250bd16e0a1d7a5 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/glfw-3.4-2-aarch64.pkg.tar.zst
|
||||
# libtracefs is ours (libtracefs-shim.c), and reads libtraceevent's structures as 1.8.2 lays them
|
||||
# out: moving libtraceevent off 1.8.2 means checking event-parse.h against the shim.
|
||||
0cccdc9c92cb3cae1e37ebeb0ed20b93bb3b5000c8f955b63d0e07bd878c7018 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/libtraceevent-1%3A1.8.2-2-aarch64.pkg.tar.zst
|
||||
47ffd6a953959d6a0df44539bef30a67d0b8c95cce0053273908d9d70ef7abc4 https://steamdeck-packages.steamos.cloud/archlinux-deckard/archlinux/mash-20240705.2/extra/os/aarch64/libtracefs-1.8.0-1-aarch64.pkg.tar.zst
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM menci/archlinuxarm:base-devel
|
||||
|
||||
# Pacman 7's Landlock sandbox cannot start in this Docker kernel. Package builds still run as the
|
||||
# container user; disable only the unavailable sandbox paths for the dependency-install layer.
|
||||
RUN sed -i \
|
||||
's/^[[:space:]]*#DownloadUser.*/DownloadUser =/; s/^#DisableSandboxFilesystem/DisableSandboxFilesystem/; s/^#DisableSandboxSyscalls/DisableSandboxSyscalls/' \
|
||||
/etc/pacman.conf \
|
||||
&& pacman -Syu --noconfirm --needed \
|
||||
base-devel cmake extra-cmake-modules git ninja pkgconf \
|
||||
plasma-mobile plasma-wayland-protocols vulkan-headers \
|
||||
&& pacman -Scc --noconfirm
|
||||
|
||||
WORKDIR /src
|
||||
@@ -0,0 +1,17 @@
|
||||
# Plasma Mobile 6.7.5 runtime backports
|
||||
|
||||
The Thor root installs Plasma Mobile 6.7.5. The app build backports KDE's
|
||||
[`Use effect caching` change](https://invent.kde.org/plasma/plasma-mobile/-/commit/73c5b4fd2815dc5d845c09cf578f60a9af3e708b)
|
||||
to fix the mobile task switcher state, and removes Folio's requirement for a
|
||||
shared KWayland client connection before it queries installed applications.
|
||||
|
||||
`tools/build_local.sh` stages the checked-in ARM64 modules under the generated
|
||||
`app/src/main/assets/linuxfs` tree. To rebuild those modules, run
|
||||
`tools/plasma-mobile/rebuild.sh`; it builds the affected targets in the Arch
|
||||
Linux ARM environment described by `Dockerfile` and refreshes `prebuilt/`.
|
||||
This keeps the changes isolated to the Plasma runtime; the LXQt/Steam root is
|
||||
not modified. The module sources and patches target tag `v6.7.5`.
|
||||
|
||||
The app-catalog patch currently logs whether Folio receives a KWayland
|
||||
connection and how many KService entries it finds. Those diagnostics are for
|
||||
Thor dogfooding and can be removed after the empty-drawer cause is confirmed.
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
plasma_version=6.7.5
|
||||
source_dir="${TMPDIR:-/tmp}/plasma-mobile-${plasma_version}"
|
||||
build_dir="${TMPDIR:-/tmp}/plasma-mobile-build-${plasma_version}"
|
||||
asset_root="${repo_root}/app/src/main/assets/linuxfs"
|
||||
|
||||
installed_version=$(pacman -Q plasma-mobile | awk '{print $2}')
|
||||
case "${installed_version}" in
|
||||
"${plasma_version}"-*) ;;
|
||||
*)
|
||||
echo "Expected plasma-mobile ${plasma_version}, found ${installed_version}." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
rm -rf -- "${source_dir}" "${build_dir}"
|
||||
git clone --quiet --depth 1 --branch "v${plasma_version}" \
|
||||
https://invent.kde.org/plasma/plasma-mobile.git "${source_dir}"
|
||||
git -C "${source_dir}" apply --check \
|
||||
"${repo_root}/tools/plasma-mobile/patches/0001-mobile-task-switcher.patch" \
|
||||
"${repo_root}/tools/plasma-mobile/patches/0002-folio-app-model.patch"
|
||||
git -C "${source_dir}" apply \
|
||||
"${repo_root}/tools/plasma-mobile/patches/0001-mobile-task-switcher.patch" \
|
||||
"${repo_root}/tools/plasma-mobile/patches/0002-folio-app-model.patch"
|
||||
|
||||
cmake -S "${source_dir}" -B "${build_dir}" -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
cmake --build "${build_dir}" --parallel "${DROIDDECK_PLASMA_BUILD_JOBS:-4}" \
|
||||
--target mobiletaskswitcherplugin org.kde.plasma.mobile.homescreen.folio
|
||||
|
||||
install -Dm644 "${build_dir}/bin/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so" \
|
||||
"${asset_root}/usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so"
|
||||
install -Dm644 "${build_dir}/kwin/mobiletaskswitcher/plugin/libmobiletaskswitcherplugin.so" \
|
||||
"${asset_root}/usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so"
|
||||
install -Dm644 "${source_dir}/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml" \
|
||||
"${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml"
|
||||
install -Dm644 "${source_dir}/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml" \
|
||||
"${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml"
|
||||
strip --strip-unneeded \
|
||||
"${asset_root}/usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so" \
|
||||
"${asset_root}/usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so"
|
||||
|
||||
echo "Built Plasma Mobile ${plasma_version} app-catalog and task-switcher backports."
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
source_dir="${repo_root}/tools/plasma-mobile/prebuilt"
|
||||
asset_root="${repo_root}/app/src/main/assets/linuxfs"
|
||||
|
||||
install -Dm644 "${source_dir}/org.kde.plasma.mobile.homescreen.folio.so" \
|
||||
"${asset_root}/usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so"
|
||||
install -Dm644 "${source_dir}/libmobiletaskswitcherplugin.so" \
|
||||
"${asset_root}/usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so"
|
||||
install -Dm644 "${source_dir}/FlickContainer.qml" \
|
||||
"${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml"
|
||||
install -Dm644 "${source_dir}/TaskSwitcher.qml" \
|
||||
"${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml"
|
||||
|
||||
echo "Staged the Plasma Mobile 6.7.5 ARM64 backports. Run tools/plasma-mobile/rebuild.sh to rebuild them."
|
||||
@@ -0,0 +1,278 @@
|
||||
diff --git a/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml b/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml
|
||||
index 8f89960..8a80991 100644
|
||||
--- a/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml
|
||||
+++ b/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml
|
||||
@@ -25,10 +25,16 @@ Flickable {
|
||||
|
||||
readonly property real startContentX: (taskSwitcherHelpers.taskWidth + taskSwitcherHelpers.taskSpacing) * tasksCount
|
||||
property bool movingRight: false // TODO needed for flickable not flicking workaround
|
||||
+ property bool resettingPosition: false
|
||||
|
||||
// update position from horizontal flickable movement
|
||||
property real oldContentX
|
||||
onContentXChanged: {
|
||||
+ if (resettingPosition) {
|
||||
+ oldContentX = contentX;
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
// disable if animations are running to prevent bugs
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
|
||||
@@ -43,6 +49,8 @@ Flickable {
|
||||
|
||||
onMovementStarted: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
+ oldContentX = contentX;
|
||||
+ movingRight = false;
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
}
|
||||
onMovementEnded: {
|
||||
@@ -63,6 +71,8 @@ Flickable {
|
||||
onDraggingChanged: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
if (dragging) {
|
||||
+ oldContentX = contentX;
|
||||
+ movingRight = false;
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
} else {
|
||||
resetPosition();
|
||||
@@ -70,7 +80,14 @@ Flickable {
|
||||
}
|
||||
|
||||
function resetPosition(): void {
|
||||
+ resettingPosition = true;
|
||||
+ cancelFlick();
|
||||
oldContentX = startContentX;
|
||||
contentX = startContentX;
|
||||
+ movingRight = false;
|
||||
+ Qt.callLater(() => {
|
||||
+ oldContentX = contentX;
|
||||
+ resettingPosition = false;
|
||||
+ });
|
||||
}
|
||||
}
|
||||
diff --git a/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml b/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml
|
||||
index e614639..ca3908e 100644
|
||||
--- a/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml
|
||||
+++ b/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml
|
||||
@@ -85,11 +85,12 @@ FocusScope {
|
||||
|
||||
Keys.onEscapePressed: hide();
|
||||
|
||||
- Component.onCompleted: {
|
||||
- initialSetup();
|
||||
- }
|
||||
-
|
||||
function initialSetup(): void {
|
||||
+ closeAnim.stop();
|
||||
+ container.opacity = 1;
|
||||
+ closeAllButton.closeRequested = false;
|
||||
+ oldTasksCount = tasksCount;
|
||||
+
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
state.updateWasInActiveTask(KWinComponents.Workspace.activeWindow);
|
||||
|
||||
@@ -102,12 +103,14 @@ FocusScope {
|
||||
taskSwitcherHelpers.hasVibrated = false;
|
||||
|
||||
taskSwitcherHelpers.closingFactor = 1;
|
||||
+ taskSwitcherHelpers.closingScalingFactor = 1;
|
||||
|
||||
taskSwitcherHelpers.taskSwitchCanLaunch = false;
|
||||
taskSwitchCanLaunchTimer.restart()
|
||||
|
||||
taskList.taskOffsetEasing = Easing.InOutQuart;
|
||||
taskList.homeTouchPositionX = 0;
|
||||
+ flickable.resetPosition();
|
||||
|
||||
backgroundColorOpacityAn.enabled = false;
|
||||
backgroundColorOpacity = state.wasInActiveTask ? 1 : 0;
|
||||
@@ -161,6 +164,11 @@ FocusScope {
|
||||
Connections {
|
||||
target: root.state
|
||||
|
||||
+ function onActivated(): void {
|
||||
+ root.tasksModel.refresh();
|
||||
+ root.initialSetup();
|
||||
+ }
|
||||
+
|
||||
// task scrub mode allows scrubbing through a number of tasks with a mostly horizontal motion
|
||||
function taskScrubMode(): void {
|
||||
taskList.setTaskOffsetValue(0, false, Easing.OutQuart);
|
||||
@@ -827,4 +835,3 @@ FocusScope {
|
||||
}
|
||||
}
|
||||
}
|
||||
-
|
||||
diff --git a/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.cpp b/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.cpp
|
||||
index 5c2f376..e8baaff 100644
|
||||
--- a/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.cpp
|
||||
+++ b/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.cpp
|
||||
@@ -35,8 +35,11 @@ void MobileTaskSwitcherState::init(KWin::QuickSceneEffect *parent)
|
||||
m_border = new EffectTouchBorder{m_effectState};
|
||||
m_taskModel = new TaskModel{parent};
|
||||
m_effect = parent;
|
||||
+ m_effect->setViewCachingEnabled(true);
|
||||
|
||||
// Connect signals
|
||||
+ connect(m_effect, &QuickSceneEffect::activated, this, &MobileTaskSwitcherState::activated);
|
||||
+ connect(m_effect, &QuickSceneEffect::deactivated, this, &MobileTaskSwitcherState::deactivated);
|
||||
connect(this, &MobileTaskSwitcherState::gestureEnabledChanged, this, &MobileTaskSwitcherState::refreshBorders);
|
||||
connect(m_border, &EffectTouchBorder::touchPositionChanged, this, &MobileTaskSwitcherState::processTouchPositionChanged);
|
||||
connect(this, &MobileTaskSwitcherState::gestureInProgressChanged, this, [this]() {
|
||||
@@ -223,13 +226,10 @@ void MobileTaskSwitcherState::restartDoubleClickTimer()
|
||||
|
||||
void MobileTaskSwitcherState::calculateFilteredVelocity(qreal primaryDelta, qreal orthogonalDelta)
|
||||
{
|
||||
- static qreal prevPrimaryDelta = 0;
|
||||
- static qreal prevOrthogonalDelta = 0;
|
||||
-
|
||||
qint64 frameTime = 0;
|
||||
if (!m_frameTimer.isValid()) {
|
||||
- prevPrimaryDelta = 0;
|
||||
- prevOrthogonalDelta = 0;
|
||||
+ m_previousPrimaryDelta = primaryDelta;
|
||||
+ m_previousOrthogonalDelta = orthogonalDelta;
|
||||
m_frameTimer.start();
|
||||
return;
|
||||
}
|
||||
@@ -239,10 +239,10 @@ void MobileTaskSwitcherState::calculateFilteredVelocity(qreal primaryDelta, qrea
|
||||
return;
|
||||
}
|
||||
|
||||
- qreal framePrimaryDelta = primaryDelta - prevPrimaryDelta;
|
||||
- qreal frameOrthogonalDelta = orthogonalDelta - prevOrthogonalDelta;
|
||||
- prevPrimaryDelta = primaryDelta;
|
||||
- prevOrthogonalDelta = orthogonalDelta;
|
||||
+ qreal framePrimaryDelta = primaryDelta - m_previousPrimaryDelta;
|
||||
+ qreal frameOrthogonalDelta = orthogonalDelta - m_previousOrthogonalDelta;
|
||||
+ m_previousPrimaryDelta = primaryDelta;
|
||||
+ m_previousOrthogonalDelta = orthogonalDelta;
|
||||
|
||||
// Implements an exponentially weighted moving average (EWMA) filter (= exponential smoothing)
|
||||
// Smoothing factor is approximated each event to achieve a chosen filter time constant
|
||||
@@ -253,6 +253,24 @@ void MobileTaskSwitcherState::calculateFilteredVelocity(qreal primaryDelta, qrea
|
||||
Q_EMIT velocityChanged();
|
||||
}
|
||||
|
||||
+void MobileTaskSwitcherState::clearVelocityFilter()
|
||||
+{
|
||||
+ m_frameTimer.invalidate();
|
||||
+ m_previousPrimaryDelta = 0;
|
||||
+ m_previousOrthogonalDelta = 0;
|
||||
+ m_xVelocity = 0;
|
||||
+ m_yVelocity = 0;
|
||||
+ m_totalSquaredVelocity = 0;
|
||||
+ Q_EMIT velocityChanged();
|
||||
+}
|
||||
+
|
||||
+void MobileTaskSwitcherState::resetGestureState()
|
||||
+{
|
||||
+ m_touchXPosition = 0;
|
||||
+ m_touchYPosition = 0;
|
||||
+ clearVelocityFilter();
|
||||
+}
|
||||
+
|
||||
void MobileTaskSwitcherState::processTouchPositionChanged(qreal primaryDelta, qreal orthogonalDelta)
|
||||
{
|
||||
calculateFilteredVelocity(primaryDelta, orthogonalDelta);
|
||||
@@ -289,6 +307,7 @@ void MobileTaskSwitcherState::activate()
|
||||
return;
|
||||
}
|
||||
|
||||
+ resetGestureState();
|
||||
m_effectState->setInProgress(false);
|
||||
invokeEffect();
|
||||
}
|
||||
@@ -339,6 +358,8 @@ void MobileTaskSwitcherState::setDBusState(bool active)
|
||||
|
||||
void MobileTaskSwitcherState::invokeEffect()
|
||||
{
|
||||
+ m_shutdownTimer->stop();
|
||||
+ resetGestureState();
|
||||
setInitialTaskIndex(currentTaskIndex()); // TODO! this is only until the crashing bug is fixed and recency sorting is in
|
||||
m_effect->setRunning(true);
|
||||
setDBusState(true);
|
||||
diff --git a/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.h b/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.h
|
||||
index d85f1cc..0aae2a7 100644
|
||||
--- a/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.h
|
||||
+++ b/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.h
|
||||
@@ -144,6 +144,7 @@ private Q_SLOTS:
|
||||
|
||||
private:
|
||||
void invokeEffect();
|
||||
+ void resetGestureState();
|
||||
|
||||
bool m_gestureEnabled{false};
|
||||
EffectTouchBorderState *m_effectState{nullptr};
|
||||
@@ -154,8 +155,8 @@ private:
|
||||
Status m_status = Status::Inactive;
|
||||
bool m_gestureInProgress = false;
|
||||
|
||||
- int m_currentTaskIndex;
|
||||
- int m_initialTaskIndex;
|
||||
+ int m_currentTaskIndex = 0;
|
||||
+ int m_initialTaskIndex = 0;
|
||||
|
||||
void clearVelocityFilter();
|
||||
void calculateFilteredVelocity(qreal primaryPosition, qreal orthogonalPosition);
|
||||
@@ -163,22 +164,24 @@ private:
|
||||
|
||||
// velocities in (logical) pixels/msec
|
||||
QElapsedTimer m_frameTimer;
|
||||
+ qreal m_previousPrimaryDelta = 0;
|
||||
+ qreal m_previousOrthogonalDelta = 0;
|
||||
qreal m_flickVelocityThreshold = 0.5 * 0.5; // squared because total velocity is kept as a square
|
||||
qreal m_filterTimeConstant = 0.03; // time constant of velocity filter
|
||||
|
||||
- qreal m_touchXPosition;
|
||||
- qreal m_touchYPosition;
|
||||
+ qreal m_touchXPosition = 0;
|
||||
+ qreal m_touchYPosition = 0;
|
||||
qreal m_xVelocity = 0;
|
||||
qreal m_yVelocity = 0;
|
||||
// Using the square of velocity for the total (2-axis) because we just need it
|
||||
// for one threshold comparison and we skip having to calculate the square root
|
||||
- qreal m_totalSquaredVelocity;
|
||||
+ qreal m_totalSquaredVelocity = 0;
|
||||
|
||||
// Positions of the task switcher effect itself
|
||||
qreal m_xPosition = 0;
|
||||
qreal m_yPosition = 0;
|
||||
|
||||
- bool m_wasInActiveTask;
|
||||
+ bool m_wasInActiveTask = false;
|
||||
|
||||
QElapsedTimer *m_doubleClickTimer;
|
||||
qint64 getDoubleClickInterval() const
|
||||
diff --git a/kwin/mobiletaskswitcher/plugin/taskfiltermodel.cpp b/kwin/mobiletaskswitcher/plugin/taskfiltermodel.cpp
|
||||
index 59e1f48..6e04c86 100644
|
||||
--- a/kwin/mobiletaskswitcher/plugin/taskfiltermodel.cpp
|
||||
+++ b/kwin/mobiletaskswitcher/plugin/taskfiltermodel.cpp
|
||||
@@ -43,6 +43,12 @@ void TaskFilterModel::setWindowModel(TaskModel *taskModel)
|
||||
sort(0);
|
||||
}
|
||||
|
||||
+void TaskFilterModel::refresh()
|
||||
+{
|
||||
+ invalidateFilter();
|
||||
+ sort(0);
|
||||
+}
|
||||
+
|
||||
QString TaskFilterModel::screenName() const
|
||||
{
|
||||
return m_output ? m_output->name() : QString();
|
||||
diff --git a/kwin/mobiletaskswitcher/plugin/taskfiltermodel.h b/kwin/mobiletaskswitcher/plugin/taskfiltermodel.h
|
||||
index 87244cc..ce3688a 100644
|
||||
--- a/kwin/mobiletaskswitcher/plugin/taskfiltermodel.h
|
||||
+++ b/kwin/mobiletaskswitcher/plugin/taskfiltermodel.h
|
||||
@@ -30,6 +30,8 @@ public:
|
||||
TaskModel *windowModel() const;
|
||||
void setWindowModel(KWin::TaskModel *taskModel);
|
||||
|
||||
+ Q_INVOKABLE void refresh();
|
||||
+
|
||||
QString screenName() const;
|
||||
void setScreenName(const QString &screenName);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
diff --git a/containments/homescreens/folio/applicationlistmodel.cpp b/containments/homescreens/folio/applicationlistmodel.cpp
|
||||
--- a/containments/homescreens/folio/applicationlistmodel.cpp
|
||||
+++ b/containments/homescreens/folio/applicationlistmodel.cpp
|
||||
@@ -35,9 +35,9 @@ ApplicationListModel::ApplicationListModel(HomeScreen *parent)
|
||||
|
||||
// initialize wayland window checking
|
||||
KWayland::Client::ConnectionThread *connection = KWayland::Client::ConnectionThread::fromApplication(this);
|
||||
- if (!connection) {
|
||||
- return;
|
||||
- }
|
||||
-
|
||||
+ qDebug() << "Folio app model Wayland client connection:" << (connection != nullptr);
|
||||
+ // Listing and launching desktop entries does not need a Wayland client connection. In an
|
||||
+ // embedded compositor session KWayland may not expose its shared connection to this model;
|
||||
+ // still populate the catalog so the drawer is usable.
|
||||
load();
|
||||
}
|
||||
@@ -93,6 +93,7 @@ void ApplicationListModel::load()
|
||||
}
|
||||
|
||||
const KService::List currentApps = queryApplications();
|
||||
+ qDebug() << "Folio application service query returned" << currentApps.size() << "entries";
|
||||
QList<KService::Ptr> toInsert;
|
||||
|
||||
for (const KService::Ptr &service : currentApps) {
|
||||
diff --git a/containments/homescreens/folio/qml/AppDrawer.qml b/containments/homescreens/folio/qml/AppDrawer.qml
|
||||
index a389b20..5b1840a 100644
|
||||
--- a/containments/homescreens/folio/qml/AppDrawer.qml
|
||||
+++ b/containments/homescreens/folio/qml/AppDrawer.qml
|
||||
@@ -87,7 +87,7 @@ Item {
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.bottom: parent.bottom
|
||||
- opacity: 0 // we display with the opacity gradient below
|
||||
+ opacity: 1 // Render app tiles directly with Qt's software Quick backend.
|
||||
headerHeight: root.headerHeight
|
||||
|
||||
// Keyboard navigation
|
||||
@@ -104,10 +104,5 @@ Item {
|
||||
}
|
||||
}
|
||||
|
||||
- // Opacity gradient at grid edges
|
||||
- MobileShell.FlickableOpacityGradient {
|
||||
- anchors.fill: appDrawerGrid
|
||||
- flickable: appDrawerGrid
|
||||
- }
|
||||
}
|
||||
}
|
||||
diff --git a/containments/homescreens/folio/qml/AppDrawerGrid.qml b/containments/homescreens/folio/qml/AppDrawerGrid.qml
|
||||
--- a/containments/homescreens/folio/qml/AppDrawerGrid.qml
|
||||
+++ b/containments/homescreens/folio/qml/AppDrawerGrid.qml
|
||||
@@ -29,6 +29,5 @@ MobileShell.GridView {
|
||||
|
||||
cacheBuffer: cellHeight * 20
|
||||
reuseItems: true
|
||||
- layer.enabled: true
|
||||
|
||||
keyNavigationEnabled: true
|
||||
highlightMoveDuration: 0
|
||||
@@ -0,0 +1,93 @@
|
||||
// SPDX-FileCopyrightText: 2021-2023 Devin Lin <devin@kde.org>
|
||||
// SPDX-FileCopyrightText: 2025 Luis Büchi <luis.buechi@kdemail.net>
|
||||
// SPDX-License-Identifier: LGPL-2.0-or-later
|
||||
|
||||
pragma ComponentBehavior: Bound
|
||||
|
||||
import QtQuick
|
||||
|
||||
Flickable {
|
||||
// TODO flickable is busted, it refuses to actually do any flicks with touch input, only works with mouse
|
||||
// we work around this somewhat by snapping to the nearest task in which direction it was moving when letting go
|
||||
// no matter how far away we are (and no matter how fast we go)
|
||||
id: root
|
||||
|
||||
required property var taskSwitcherState
|
||||
required property var taskSwitcherHelpers
|
||||
required property int tasksCount
|
||||
|
||||
// we use flickable solely for capturing flicks, not positioning elements
|
||||
// the horizontal distance we can swipe in one flick
|
||||
contentWidth: (taskSwitcherHelpers.taskWidth + taskSwitcherHelpers.taskSpacing) * tasksCount
|
||||
contentHeight: height
|
||||
contentX: startContentX
|
||||
|
||||
|
||||
readonly property real startContentX: (taskSwitcherHelpers.taskWidth + taskSwitcherHelpers.taskSpacing) * tasksCount
|
||||
property bool movingRight: false // TODO needed for flickable not flicking workaround
|
||||
property bool resettingPosition: false
|
||||
|
||||
// update position from horizontal flickable movement
|
||||
property real oldContentX
|
||||
onContentXChanged: {
|
||||
if (resettingPosition) {
|
||||
oldContentX = contentX;
|
||||
return;
|
||||
}
|
||||
|
||||
// disable if animations are running to prevent bugs
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
|
||||
if (moving) {
|
||||
// TODO whenever flicking actually works this should probably be swapped with
|
||||
// a minimum velocity after which it should snap to the nearest task
|
||||
taskSwitcherState.xPosition += contentX - oldContentX;
|
||||
}
|
||||
movingRight = contentX < oldContentX;
|
||||
oldContentX = contentX;
|
||||
}
|
||||
|
||||
onMovementStarted: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
oldContentX = contentX;
|
||||
movingRight = false;
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
}
|
||||
onMovementEnded: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
taskSwitcherHelpers.snapToNearestTaskWorkaround(movingRight);
|
||||
resetPosition();
|
||||
}
|
||||
|
||||
onFlickStarted: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
root.cancelFlick();
|
||||
}
|
||||
onFlickEnded: {
|
||||
// taskSwitcherHelpers.snapToNearestTaskWorkaround(movingRight);
|
||||
// resetPosition();
|
||||
}
|
||||
|
||||
onDraggingChanged: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
if (dragging) {
|
||||
oldContentX = contentX;
|
||||
movingRight = false;
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
} else {
|
||||
resetPosition();
|
||||
}
|
||||
}
|
||||
|
||||
function resetPosition(): void {
|
||||
resettingPosition = true;
|
||||
cancelFlick();
|
||||
oldContentX = startContentX;
|
||||
contentX = startContentX;
|
||||
movingRight = false;
|
||||
Qt.callLater(() => {
|
||||
oldContentX = contentX;
|
||||
resettingPosition = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,837 @@
|
||||
// SPDX-FileCopyrightText: 2015 Marco Martin <notmart@gmail.com>
|
||||
// SPDX-FileCopyrightText: 2021-2024 Devin Lin <devin@kde.org>
|
||||
// SPDX-FileCopyrightText: 2024-2025 Luis Büchi <luis.buechi@kdemail.net>
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
pragma ComponentBehavior: Bound
|
||||
|
||||
import QtQuick
|
||||
import QtQuick.Layouts
|
||||
|
||||
import org.kde.kirigami as Kirigami
|
||||
import org.kde.plasma.core as PlasmaCore
|
||||
import org.kde.plasma.components 3.0 as PlasmaComponents
|
||||
import org.kde.plasma.private.mobileshell as MobileShell
|
||||
import org.kde.plasma.private.mobileshell.state as MobileShellState
|
||||
import org.kde.plasma.private.mobileshell.shellsettingsplugin as ShellSettings
|
||||
import org.kde.plasma.private.mobileshell.taskswitcherplugin as TaskSwitcherPlugin
|
||||
|
||||
import org.kde.kwin 3.0 as KWinComponents
|
||||
import org.kde.kwin.private.effects 1.0
|
||||
import org.kde.kitemmodels
|
||||
|
||||
|
||||
/**
|
||||
* Component that provides a task switcher.
|
||||
*/
|
||||
FocusScope {
|
||||
id: root
|
||||
focus: true
|
||||
|
||||
property TaskSwitcherPlugin.MobileTaskSwitcherState state
|
||||
readonly property QtObject effect: KWinComponents.SceneView.effect
|
||||
readonly property QtObject targetScreen: KWinComponents.SceneView.screen
|
||||
|
||||
readonly property real navBottomMargin: MobileShell.Constants.navigationPanelOnSide(width, height) ? 0 : MobileShell.Constants.navigationPanelThickness
|
||||
readonly property real navRightMargin: MobileShell.Constants.navigationPanelOnSide(width, height) ? MobileShell.Constants.navigationPanelThickness : 0
|
||||
readonly property real topMargin: ShellSettings.Settings.autoHidePanelsEnabled ? 0 : MobileShell.Constants.topPanelHeight
|
||||
readonly property real bottomMargin: ShellSettings.Settings.autoHidePanelsEnabled ? 0 : navBottomMargin
|
||||
readonly property real leftMargin: 0
|
||||
readonly property real rightMargin: ShellSettings.Settings.autoHidePanelsEnabled ? 0 : navRightMargin
|
||||
|
||||
property var taskSwitcherHelpers: TaskSwitcherHelpers {
|
||||
taskSwitcher: root
|
||||
taskList: taskList
|
||||
}
|
||||
|
||||
MobileShell.HapticsEffect {
|
||||
id: haptics
|
||||
}
|
||||
|
||||
property TaskSwitcherPlugin.TaskFilterModel tasksModel: TaskSwitcherPlugin.TaskFilterModel {
|
||||
screenName: root.targetScreen.name
|
||||
windowModel: root.state.taskModel
|
||||
}
|
||||
|
||||
readonly property int tasksCount: taskList.count
|
||||
|
||||
// keep track of task list events
|
||||
property int oldTasksCount: tasksCount
|
||||
onTasksCountChanged: {
|
||||
// we need to subtract 1 from the current index when the closed task index is smaller
|
||||
// this is because this part of the list has been shifted down by 1 when the closed task was removed.
|
||||
if (taskSwitcherHelpers.lastClosedTask < state.currentTaskIndex) {
|
||||
state.currentTaskIndex -= 1;
|
||||
|
||||
// animated at the same speed as the task x position in the TaskList so that the task appears not to move from the perspective of the user.
|
||||
taskSwitcherHelpers.animateGoToTaskIndex(state.currentTaskIndex, Kirigami.Units.longDuration, Easing.InOutQuad);
|
||||
taskSwitcherHelpers.lastClosedTask = -1;
|
||||
}
|
||||
|
||||
if (tasksCount === 0 && oldTasksCount !== 0) {
|
||||
hide();
|
||||
} else if (tasksCount < oldTasksCount) {
|
||||
if (state.currentTaskIndex < 0) {
|
||||
// if the user is on the first task, and it is closed, scroll right
|
||||
taskSwitcherHelpers.animateGoToTaskIndex(0, Kirigami.Units.longDuration);
|
||||
} else if (state.currentTaskIndex >= tasksCount) {
|
||||
// if the user is on the last task, and it is closed, scroll left
|
||||
taskSwitcherHelpers.animateGoToTaskIndex(tasksCount - 1, Kirigami.Units.longDuration);
|
||||
}
|
||||
}
|
||||
|
||||
oldTasksCount = tasksCount;
|
||||
}
|
||||
|
||||
Keys.onEscapePressed: hide();
|
||||
|
||||
function initialSetup(): void {
|
||||
closeAnim.stop();
|
||||
container.opacity = 1;
|
||||
closeAllButton.closeRequested = false;
|
||||
oldTasksCount = tasksCount;
|
||||
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
state.updateWasInActiveTask(KWinComponents.Workspace.activeWindow);
|
||||
|
||||
// ensure the task drawer is not opened and reset values to defaults
|
||||
taskSwitcherHelpers.reachedHeightThreshold = false;
|
||||
taskSwitcherHelpers.gestureState = TaskSwitcherHelpers.GestureStates.Undecided;
|
||||
taskSwitcherHelpers.isInTaskScrubMode = false;
|
||||
taskSwitcherHelpers.inLastFrame = false;
|
||||
|
||||
taskSwitcherHelpers.hasVibrated = false;
|
||||
|
||||
taskSwitcherHelpers.closingFactor = 1;
|
||||
taskSwitcherHelpers.closingScalingFactor = 1;
|
||||
|
||||
taskSwitcherHelpers.taskSwitchCanLaunch = false;
|
||||
taskSwitchCanLaunchTimer.restart()
|
||||
|
||||
taskList.taskOffsetEasing = Easing.InOutQuart;
|
||||
taskList.homeTouchPositionX = 0;
|
||||
flickable.resetPosition();
|
||||
|
||||
backgroundColorOpacityAn.enabled = false;
|
||||
backgroundColorOpacity = state.wasInActiveTask ? 1 : 0;
|
||||
backgroundColorOpacityAn.enabled = true;
|
||||
|
||||
// reset the offset to have the task drawer off screen
|
||||
taskList.setTaskOffsetValue(state.wasInActiveTask ? taskSwitcherHelpers.taskOffsetValue : taskSwitcherHelpers.homeOffsetValue, true);
|
||||
|
||||
// task index from the last time using the switcher
|
||||
state.initialTaskIndex = Math.min(state.currentTaskIndex, tasksCount - 1);
|
||||
if (state.wasInActiveTask) {
|
||||
// if we were in an active task instead set initial task index to the position of that task
|
||||
state.initialTaskIndex = taskSwitcherHelpers.getTaskIndexFromWindow(KWinComponents.Workspace.activeWindow);
|
||||
} else {
|
||||
// reset the task index to the start if on home screen
|
||||
state.initialTaskIndex = 0
|
||||
}
|
||||
state.currentTaskIndex = state.initialTaskIndex
|
||||
|
||||
taskSwitcherHelpers.currentDisplayTask = state.currentTaskIndex;
|
||||
|
||||
taskSwitcherHelpers.goToTaskIndex(state.initialTaskIndex);
|
||||
taskList.minimizeAll();
|
||||
|
||||
// fully open the switcher (if this is a button press, not gesture)
|
||||
if (!state.gestureInProgress) {
|
||||
taskSwitcherHelpers.fromButton = true;
|
||||
if (state.wasInActiveTask) {
|
||||
taskList.setTaskOffsetValue(0, true);
|
||||
} else {
|
||||
taskList.setTaskOffsetValue(0);
|
||||
}
|
||||
backgroundColorOpacity = 1;
|
||||
taskSwitcherHelpers.open();
|
||||
}
|
||||
}
|
||||
|
||||
// called by c++ plugin
|
||||
function hideAnimation(): void {
|
||||
closeAnim.restart();
|
||||
}
|
||||
|
||||
function instantHide(): void {
|
||||
state.deactivate(true);
|
||||
}
|
||||
|
||||
function hide(): void {
|
||||
state.deactivate(false);
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: root.state
|
||||
|
||||
function onActivated(): void {
|
||||
root.tasksModel.refresh();
|
||||
root.initialSetup();
|
||||
}
|
||||
|
||||
// task scrub mode allows scrubbing through a number of tasks with a mostly horizontal motion
|
||||
function taskScrubMode(): void {
|
||||
taskList.setTaskOffsetValue(0, false, Easing.OutQuart);
|
||||
if (!root.taskSwitcherHelpers.isInTaskScrubMode) {
|
||||
root.backgroundColorOpacity = 1;
|
||||
root.taskSwitcherHelpers.cancelAnimations();
|
||||
root.taskSwitcherHelpers.open();
|
||||
if (!root.taskSwitcherHelpers.hasVibrated) {
|
||||
// Haptic feedback when the task scrub mode engages
|
||||
haptics.buttonVibrate();
|
||||
root.taskSwitcherHelpers.hasVibrated = true;
|
||||
}
|
||||
}
|
||||
// TODO this makes sense, but makes scrub mode feel a bit weird
|
||||
// improve trigger distance logic for task scrub mode to fix
|
||||
let newTaskIndex = Math.max(0, Math.min(root.tasksCount - 1, Math.floor(root.state.touchXPosition / root.taskSwitcherHelpers.taskScrubDistance) + root.state.initialTaskIndex - (root.state.wasInActiveTask ? 0 : 1)));
|
||||
if (newTaskIndex != root.state.currentTaskIndex || !root.taskSwitcherHelpers.isInTaskScrubMode) {
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(newTaskIndex);
|
||||
root.taskSwitcherHelpers.isInTaskScrubMode = true;
|
||||
}
|
||||
}
|
||||
|
||||
function onTouchPositionChanged(): void {
|
||||
let unmodifiedYposition = Math.abs(root.state.touchYPosition)
|
||||
if (root.taskSwitcherHelpers.isInTaskScrubMode || // once in scrub mode, let's not allow to go out, that can result in inconsistent UX
|
||||
(Math.abs(root.state.xVelocity) > Math.abs(root.state.yVelocity) * 3 && // gesture needs to be almost completely horizontal
|
||||
Math.abs(root.state.xVelocity) < 2.5 && // and not with a fast flick TODO! evaluate whether to keep this, it's kinda awkward
|
||||
Math.abs(root.state.touchXPosition) > root.taskSwitcherHelpers.taskScrubDistance * 0.95 && // and have moved far enough sideways
|
||||
unmodifiedYposition < Kirigami.Units.largeSpacing * 2 && // and be close to the screen edge
|
||||
root.tasksCount > 0 && // and there needs to be more than none task open
|
||||
!root.taskSwitcherHelpers.taskDrawerOpened // and the task drawer must not be open
|
||||
)) {
|
||||
taskScrubMode();
|
||||
} else {
|
||||
if (root.taskSwitcherHelpers.currentlyBeingClosed) {
|
||||
// if the task switch is still open but playing the close animation
|
||||
// setup some values and return to the initial setup so that the user can always navigate with no down time
|
||||
root.state.wasInActiveTask = root.taskSwitcherHelpers.openAppAnim.running ? true : false
|
||||
taskList.setTaskOffsetValue(root.state.wasInActiveTask ? root.taskSwitcherHelpers.taskOffsetValue : root.taskSwitcherHelpers.homeOffsetValue, true);
|
||||
root.state.status = !root.state.wasInActiveTask ? (root.taskSwitcherHelpers.openAppAnim.closeAnim && !root.taskSwitcherHelpers.taskDrawerWillOpen ? TaskSwitcherPlugin.MobileTaskSwitcherState.Active : TaskSwitcherPlugin.MobileTaskSwitcherState.Inactive) : TaskSwitcherPlugin.MobileTaskSwitcherState.Inactive
|
||||
root.initialSetup();
|
||||
} else if (root.taskSwitcherHelpers.openAnim.running) {
|
||||
root.taskSwitcherHelpers.cancelAnimations();
|
||||
root.state.status = root.taskSwitcherHelpers.stateClass.Active;
|
||||
}
|
||||
|
||||
root.state.yPosition = unmodifiedYposition + (root.taskSwitcherHelpers.taskDrawerOpened || !root.state.wasInActiveTask ? root.taskSwitcherHelpers.openedYPosition : 0);
|
||||
|
||||
let newXPosition = root.taskSwitcherHelpers.xPositionFromTaskIndex(root.state.initialTaskIndex);
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState && !root.taskSwitcherHelpers.currentlyBeingClosed) {
|
||||
newXPosition = newXPosition - (root.state.touchXPosition / root.taskSwitcherHelpers.currentScale);
|
||||
}
|
||||
root.state.xPosition = newXPosition;
|
||||
|
||||
// allows the user to move the task drawer left and right when on the home screen
|
||||
taskList.homeTouchPositionX = root.taskSwitcherHelpers.notHomeScreenState ? 0 : (root.state.touchXPosition * 0.35);
|
||||
|
||||
// dynamically update the task switcher state based off of the touch position and velocity
|
||||
updateTaskSwitcherState()
|
||||
}
|
||||
}
|
||||
|
||||
function updateTaskSwitcherState(): void {
|
||||
let unmodifiedYposition = Math.abs(root.state.touchYPosition)
|
||||
|
||||
// if the touch is above heightThreshold, set reachedHeightThreshold to true
|
||||
if (unmodifiedYposition > root.taskSwitcherHelpers.heightThreshold) {
|
||||
// set reachedHeightThreshold when above or below two separate points to helps prevent flickering when the task switcher moves in and out of view
|
||||
root.taskSwitcherHelpers.reachedHeightThreshold = true;
|
||||
root.backgroundColorOpacity = root.taskSwitcherHelpers.notHomeScreenState ? 0 : 1;
|
||||
} else if (unmodifiedYposition > root.taskSwitcherHelpers.undoYThreshold) {
|
||||
root.backgroundColorOpacity = 1;
|
||||
} else {
|
||||
root.backgroundColorOpacity = root.taskSwitcherHelpers.notHomeScreenState ? 1 : 0;
|
||||
}
|
||||
|
||||
if (root.state.totalSquaredVelocity > root.state.flickVelocityThreshold) {
|
||||
// flick
|
||||
// ratio between y and x velocity as threshold between vertical and horizontal flick
|
||||
let xyVelocityRatio = 1.7; // with 1.7 swipes up to ~60° from horizontal are counted as horizontal
|
||||
if (root.state.yVelocity > Math.abs(root.state.xVelocity) * xyVelocityRatio) {
|
||||
// downwards flick
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Undecided);
|
||||
if (unmodifiedYposition < root.taskSwitcherHelpers.undoYThreshold) {
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.notHomeScreenState ? 0 : root.taskSwitcherHelpers.homeOffsetValue);
|
||||
}
|
||||
} else if (-root.state.yVelocity > Math.abs(root.state.xVelocity) * xyVelocityRatio || (root.taskSwitcherHelpers.reachedHeightThreshold && root.taskSwitcherHelpers.notHomeScreenState)) {
|
||||
// upwards flick or if the touch is above heightThreshold
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
// if in app or task switcher, go home
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Home);
|
||||
if (root.taskSwitcherHelpers.reachedHeightThreshold) {
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.taskOffsetValue);
|
||||
}
|
||||
} else if (unmodifiedYposition > root.taskSwitcherHelpers.undoYThreshold) {
|
||||
// else, keep the task switcher in view
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.TaskSwitcher);
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.peekOffsetValue);
|
||||
}
|
||||
} else if (!root.taskSwitcherHelpers.reachedHeightThreshold && !root.taskSwitcherHelpers.isInTaskScrubMode) {
|
||||
// sideways flick
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
taskList.setTaskOffsetValue(0, unmodifiedYposition < root.taskSwitcherHelpers.openedYPosition ? true : false);
|
||||
}
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.HorizontalSwipe);
|
||||
}
|
||||
} else {
|
||||
if (unmodifiedYposition > root.taskSwitcherHelpers.undoYThreshold) {
|
||||
// if just moveing out of undoYThreshold, set the state to home
|
||||
if (root.taskSwitcherHelpers.gestureState < TaskSwitcherHelpers.GestureStates.TaskSwitcher) {
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Home)
|
||||
}
|
||||
// if the touch is above heightThreshold, it will return home
|
||||
if (unmodifiedYposition > root.taskSwitcherHelpers.heightThreshold) {
|
||||
root.taskSwitcherHelpers.hasVibrated = true;
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
// move the task switcher out of view
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Home);
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.taskOffsetValue);
|
||||
} else {
|
||||
// keep the task switcher in view when above heightThreshold and from home
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.TaskSwitcher);
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.peekOffsetValue);
|
||||
}
|
||||
// minus largeSpacing from the heightThreshold to help prevent flickering when the task switcher moves in and out of view
|
||||
} else if ((unmodifiedYposition < root.taskSwitcherHelpers.heightThreshold - Kirigami.Units.largeSpacing) || root.taskSwitcherHelpers.reachedHeightThreshold == false) {
|
||||
// set reachedHeightThreshold when above or below two separate points to helps prevent flickering when the task switcher moves in and out of view
|
||||
root.taskSwitcherHelpers.reachedHeightThreshold = false;
|
||||
if (root.state.totalSquaredVelocity < root.state.flickVelocityThreshold && root.taskSwitcherHelpers.taskSwitchCanLaunch) {
|
||||
// if velocity is small enough, move the task switcher into view
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.TaskSwitcher);
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.notHomeScreenState ? 0 : root.taskSwitcherHelpers.peekOffsetValue);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// if under the undo threshold, it will go back to the task switcher if it is open
|
||||
if (root.taskSwitcherHelpers.taskDrawerOpened) {
|
||||
root.taskSwitcherHelpers.reachedHeightThreshold = false;
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.TaskSwitcher)
|
||||
taskList.setTaskOffsetValue(0);
|
||||
} else {
|
||||
root.taskSwitcherHelpers.reachedHeightThreshold = false;
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Undecided)
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.notHomeScreenState ? 0 : root.taskSwitcherHelpers.homeOffsetValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// returns to the currently centered app. usually used to "back out" of the switcher
|
||||
// if accidentally invoked, but can also be used to switch to an adjacent app and then open it
|
||||
function returnToApp(): void {
|
||||
let newIndex = root.taskSwitcherHelpers.getNearestTaskIndex();
|
||||
root.taskSwitcherHelpers.openApp(newIndex);
|
||||
}
|
||||
|
||||
// diagonal quick switch gesture logic
|
||||
function quickSwitch(): void {
|
||||
// should "quick switch" to adjacent app in task switcher, but only if we were in an app before
|
||||
let unmodifiedYposition = Math.abs(root.state.touchYPosition)
|
||||
let newIndex = root.state.currentTaskIndex;
|
||||
let shouldSwitch = false;
|
||||
if (root.state.xVelocity > 0) {
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
// flick to the right, go to the app on the left
|
||||
newIndex = root.state.currentTaskIndex + 1;
|
||||
}
|
||||
if (newIndex < root.tasksCount) {
|
||||
// switch only if flick doesn't go over end of list
|
||||
shouldSwitch = true;
|
||||
}
|
||||
} else if (root.state.xVelocity < 0) {
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
// flick to the left, go to app to the right
|
||||
newIndex = root.state.currentTaskIndex - 1;
|
||||
if (newIndex >= 0) {
|
||||
// switch only if flick doesn't go over end of list
|
||||
shouldSwitch = true;
|
||||
}
|
||||
} else {
|
||||
// flick to the left on the home screen, dismiss the gesture
|
||||
root.taskSwitcherHelpers.close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (shouldSwitch) {
|
||||
if (!root.taskSwitcherHelpers.taskDrawerOpened && unmodifiedYposition < root.taskSwitcherHelpers.openedYPosition) {
|
||||
// if in a app, switch it to the new task when it is under the openedYPosition
|
||||
taskList.setTaskOffsetValue(0, unmodifiedYposition < root.taskSwitcherHelpers.openedYPosition && root.taskSwitcherHelpers.notHomeScreenState);
|
||||
root.taskSwitcherHelpers.openApp(newIndex, Kirigami.Units.longDuration * 4, Easing.OutExpo);
|
||||
} else {
|
||||
// if already in the task switcher or above the openedYPosition, only change the focus to the new task
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(newIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
}
|
||||
} else {
|
||||
// if not switching, just open task switcher
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(root.state.currentTaskIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
}
|
||||
}
|
||||
|
||||
// Logic for deciding how to handle the end of a gesture input
|
||||
function onGestureInProgressChanged(): void {
|
||||
root.taskSwitcherHelpers.fromButton = false;
|
||||
if (root.state.gestureInProgress) {
|
||||
root.taskSwitcherHelpers.currentDisplayTask = root.state.currentTaskIndex;
|
||||
return;
|
||||
}
|
||||
|
||||
if (taskList.count === 0) {
|
||||
// dismiss the gesture if the task list is empty
|
||||
root.taskSwitcherHelpers.close();
|
||||
} if (root.taskSwitcherHelpers.isInTaskScrubMode) {
|
||||
// TODO! do we want to handle upwards flick to dismiss in task scrub mode?
|
||||
let unmodifiedYposition = Math.abs(root.state.touchYPosition)
|
||||
root.backgroundColorOpacity = 1;
|
||||
if (root.taskSwitcherHelpers.taskDrawerOpened || unmodifiedYposition > root.taskSwitcherHelpers.undoYThreshold) {
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(root.state.currentTaskIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
root.taskSwitcherHelpers.isInTaskScrubMode = false;
|
||||
} else {
|
||||
root.taskSwitcherHelpers.openApp(root.state.currentTaskIndex);
|
||||
}
|
||||
} else if (root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.Undecided) {
|
||||
if (root.taskSwitcherHelpers.taskDrawerOpened) {
|
||||
// if in the task switcher, return to it
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(root.state.currentTaskIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
} else if (root.state.wasInActiveTask) {
|
||||
// if inside a app, return to it
|
||||
returnToApp();
|
||||
} else {
|
||||
// else dismiss the gesture
|
||||
root.taskSwitcherHelpers.close();
|
||||
}
|
||||
} else if (root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.HorizontalSwipe) {
|
||||
// sideways flick
|
||||
root.backgroundColorOpacity = 1;
|
||||
quickSwitch();
|
||||
} else if (root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.TaskSwitcher) {
|
||||
// open the task drawer
|
||||
root.backgroundColorOpacity = 1;
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(root.state.currentTaskIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
} else if (root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.Home) {
|
||||
root.taskSwitcherHelpers.close();
|
||||
}
|
||||
}
|
||||
|
||||
function onVelocityChanged(): void {
|
||||
|
||||
}
|
||||
|
||||
function onXPositionChanged(): void {
|
||||
root.taskSwitcherHelpers.updateTaskIndex();
|
||||
}
|
||||
}
|
||||
|
||||
// kind of a hack, but this prevents the gesture from immediately activating the task switcher when it is not supposed to
|
||||
Timer {
|
||||
id: taskSwitchCanLaunchTimer
|
||||
interval: 1; running: true; repeat: false
|
||||
onTriggered: root.taskSwitcherHelpers.taskSwitchCanLaunch = true;
|
||||
}
|
||||
|
||||
function setTaskDrawerState(value: int): void {
|
||||
if (taskSwitcherHelpers.gestureState != TaskSwitcherHelpers.GestureStates.TaskSwitcher && value == TaskSwitcherHelpers.GestureStates.TaskSwitcher) {
|
||||
// vibrate only if switching to task drawer
|
||||
if (!taskSwitcherHelpers.hasVibrated) {
|
||||
// Haptic feedback when the task scrub mode engages
|
||||
haptics.buttonVibrate();
|
||||
taskSwitcherHelpers.hasVibrated = true;
|
||||
}
|
||||
|
||||
}
|
||||
taskSwitcherHelpers.gestureState = value;
|
||||
}
|
||||
|
||||
// view of the desktop background
|
||||
KWinComponents.DesktopBackground {
|
||||
id: backgroundItem
|
||||
activity: KWinComponents.Workspace.currentActivity
|
||||
desktop: KWinComponents.Workspace.currentDesktop
|
||||
outputName: root.targetScreen.name
|
||||
}
|
||||
|
||||
// background colour
|
||||
Rectangle {
|
||||
id: backgroundRect
|
||||
anchors.fill: root
|
||||
|
||||
opacity: container.opacity
|
||||
color: {
|
||||
return Qt.rgba(0, 0, 0, 0.6 * root.taskSwitcherHelpers.closingFactor * root.backgroundColorOpacity);
|
||||
}
|
||||
}
|
||||
|
||||
// animate the background opacity based off of the state.
|
||||
property real backgroundColorOpacity: 1
|
||||
Behavior on backgroundColorOpacity {
|
||||
id: backgroundColorOpacityAn
|
||||
NumberAnimation {
|
||||
duration: Kirigami.Units.longDuration
|
||||
}
|
||||
}
|
||||
|
||||
// status bar
|
||||
// TODO: improve load times, it is quite slow
|
||||
// MobileShell.StatusBar {
|
||||
// id: statusBar
|
||||
// z: 1
|
||||
// colorGroup: Kirigami.Theme.ComplementaryColorGroup
|
||||
// backgroundColor: "transparent"
|
||||
//
|
||||
// height: root.topMargin
|
||||
// anchors.top: parent.top
|
||||
// anchors.left: parent.left
|
||||
// anchors.right: parent.right
|
||||
// }
|
||||
|
||||
// Gesture panel
|
||||
Component {
|
||||
id: gesturePanelComponent
|
||||
|
||||
MobileShell.GesturePanel {
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.bottom: parent.bottom
|
||||
|
||||
Kirigami.Theme.inherit: false
|
||||
Kirigami.Theme.colorSet: Kirigami.Theme.Complementary
|
||||
opaqueBar: false
|
||||
|
||||
// Trigger home action on tap
|
||||
onHandleClicked: {
|
||||
if (taskList.count === 0) {
|
||||
root.hide();
|
||||
} else {
|
||||
if (taskList.count > 1 &&
|
||||
root.state.elapsedTimeSinceStart != -1 &&
|
||||
root.state.elapsedTimeSinceStart < root.state.doubleClickInterval) {
|
||||
root.taskSwitcherHelpers.openApp(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentIndex = root.state.currentTaskIndex;
|
||||
root.taskSwitcherHelpers.openApp(root.state.currentTaskIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation panel
|
||||
Component {
|
||||
id: navigationPanelComponent
|
||||
|
||||
MobileShell.NavigationPanel {
|
||||
id: navigationPanel
|
||||
backgroundColor: Qt.rgba(0, 0, 0, 0.1)
|
||||
foregroundColorGroup: Kirigami.Theme.Complementary
|
||||
shadow: false
|
||||
|
||||
isVertical: MobileShell.Constants.navigationPanelOnSide(root.width, root.height)
|
||||
|
||||
MobileShellState.PanelSettingsDBusClient {
|
||||
id: panelSettings
|
||||
screenName: Screen.name
|
||||
}
|
||||
|
||||
leftPadding: panelSettings.navigationPanelLeftPadding
|
||||
rightPadding: panelSettings.navigationPanelRightPadding
|
||||
|
||||
leftAction: MobileShell.NavigationPanelAction {
|
||||
enabled: true
|
||||
iconSource: "mobile-task-switcher"
|
||||
shrinkSize: 4
|
||||
|
||||
onTriggered: {
|
||||
if (taskList.count === 0) {
|
||||
root.hide();
|
||||
} else {
|
||||
if (taskList.count > 1 &&
|
||||
root.state.elapsedTimeSinceStart != -1 &&
|
||||
root.state.elapsedTimeSinceStart < root.state.doubleClickInterval) {
|
||||
root.taskSwitcherHelpers.openApp(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentIndex = root.state.currentTaskIndex;
|
||||
root.taskSwitcherHelpers.openApp(root.state.currentTaskIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// home button
|
||||
middleAction: MobileShell.NavigationPanelAction {
|
||||
enabled: true
|
||||
iconSource: "start-here-kde"
|
||||
onTriggered: root.hide()
|
||||
}
|
||||
|
||||
// close app/keyboard button
|
||||
rightAction: MobileShell.NavigationPanelAction {
|
||||
enabled: true
|
||||
iconSource: "mobile-close-app"
|
||||
shrinkSize: 4
|
||||
|
||||
onTriggered: {
|
||||
taskList.getTaskAt(root.state.currentTaskIndex).closeApp();
|
||||
}
|
||||
}
|
||||
|
||||
rightCornerAction: MobileShell.NavigationPanelAction {
|
||||
visible: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loader {
|
||||
id: panelLoader
|
||||
z: !root.taskSwitcherHelpers.currentlyBeingClosed ? 1 : 0
|
||||
sourceComponent: {
|
||||
if (ShellSettings.Settings.navigationPanelEnabled) {
|
||||
return navigationPanelComponent;
|
||||
} else if (ShellSettings.Settings.gesturePanelEnabled) {
|
||||
return gesturePanelComponent;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
states: [
|
||||
State {
|
||||
name: "landscape"
|
||||
when: MobileShell.Constants.navigationPanelOnSide(root.width, root.height)
|
||||
AnchorChanges {
|
||||
target: panelLoader
|
||||
anchors {
|
||||
right: root.right
|
||||
top: root.top
|
||||
bottom: root.bottom
|
||||
left: undefined
|
||||
}
|
||||
}
|
||||
PropertyChanges {
|
||||
target: panelLoader
|
||||
width: navRightMargin
|
||||
anchors.topMargin: root.topMargin
|
||||
}
|
||||
},
|
||||
State {
|
||||
name: "portrait"
|
||||
when: !MobileShell.Constants.navigationPanelOnSide(root.width, root.height)
|
||||
AnchorChanges {
|
||||
target: panelLoader
|
||||
anchors {
|
||||
top: undefined
|
||||
right: root.right
|
||||
left: root.left
|
||||
bottom: root.bottom
|
||||
}
|
||||
}
|
||||
PropertyChanges {
|
||||
target: panelLoader
|
||||
height: navBottomMargin
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
// task list
|
||||
Item {
|
||||
id: container
|
||||
|
||||
// provide shell margins
|
||||
anchors.fill: root
|
||||
anchors.leftMargin: root.leftMargin
|
||||
anchors.rightMargin: root.rightMargin
|
||||
anchors.bottomMargin: root.bottomMargin
|
||||
anchors.topMargin: root.topMargin
|
||||
|
||||
NumberAnimation on opacity {
|
||||
id: closeAnim
|
||||
running: false
|
||||
to: 0
|
||||
duration: Kirigami.Units.longDuration
|
||||
easing.type: Easing.InOutQuad
|
||||
|
||||
onFinished: {
|
||||
closeAllButton.closeRequested = false;
|
||||
}
|
||||
}
|
||||
|
||||
// placeholder message
|
||||
ColumnLayout {
|
||||
id: placeholder
|
||||
spacing: Kirigami.Units.gridUnit
|
||||
|
||||
opacity: {
|
||||
let baseOpacity = ((root.tasksCount === 0 && !root.taskSwitcherHelpers.currentlyBeingClosed) ? 0.9 : 0);
|
||||
return root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.TaskSwitcher ? baseOpacity : 0;
|
||||
}
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.veryLongDuration } }
|
||||
|
||||
anchors.centerIn: container
|
||||
|
||||
Kirigami.Icon {
|
||||
id: icon
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
implicitWidth: Kirigami.Units.iconSizes.large
|
||||
implicitHeight: Kirigami.Units.iconSizes.large
|
||||
source: "edit-none-symbolic"
|
||||
color: "white"
|
||||
}
|
||||
|
||||
Kirigami.Heading {
|
||||
Layout.fillWidth: true
|
||||
Layout.maximumWidth: root.width * 0.75
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
color: "white"
|
||||
level: 3
|
||||
wrapMode: Text.Wrap
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
text: i18n("No applications are running.")
|
||||
}
|
||||
}
|
||||
|
||||
RowLayout {
|
||||
id: scrubIconList
|
||||
opacity: root.taskSwitcherHelpers.isInTaskScrubMode ? 1 : 0
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.longDuration } }
|
||||
|
||||
anchors.bottom: container.bottom
|
||||
anchors.right: container.horizontalCenter
|
||||
anchors.bottomMargin: root.taskSwitcherHelpers.scrubModeBottomMargin
|
||||
|
||||
anchors.rightMargin: {
|
||||
let size = Kirigami.Units.iconSizes.large + Kirigami.Units.largeSpacing * 2;
|
||||
let offset = (root.state.currentTaskIndex + 0.5) * size;
|
||||
return -offset;
|
||||
}
|
||||
Behavior on anchors.rightMargin {
|
||||
NumberAnimation {
|
||||
duration: root.taskSwitcherHelpers.xAnimDuration;
|
||||
easing.type: root.taskSwitcherHelpers.xAnimEasingType;
|
||||
}
|
||||
}
|
||||
|
||||
spacing: Kirigami.Units.largeSpacing * 2
|
||||
|
||||
layoutDirection: Qt.RightToLeft
|
||||
|
||||
Repeater {
|
||||
model: root.tasksModel
|
||||
|
||||
delegate: Kirigami.Icon {
|
||||
id: iconDelegate
|
||||
|
||||
required property QtObject window
|
||||
required property int index
|
||||
|
||||
readonly property bool isCenteredIcon: iconDelegate.index === root.state.currentTaskIndex;
|
||||
Layout.preferredHeight: isCenteredIcon ? Kirigami.Units.iconSizes.huge : Kirigami.Units.iconSizes.large
|
||||
Layout.preferredWidth: isCenteredIcon ? Kirigami.Units.iconSizes.huge : Kirigami.Units.iconSizes.large
|
||||
Layout.alignment: Qt.AlignVCenter
|
||||
source: iconDelegate.window.icon
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RowLayout {
|
||||
id: scrubIndicator
|
||||
opacity: root.taskSwitcherHelpers.isInTaskScrubMode ? 1 : 0
|
||||
Behavior on opacity { NumberAnimation { duration: 200 } }
|
||||
|
||||
anchors.bottom: container.bottom
|
||||
anchors.horizontalCenter: container.horizontalCenter
|
||||
anchors.bottomMargin: root.taskSwitcherHelpers.openedYPosition * 1 / 4
|
||||
|
||||
Kirigami.Icon {
|
||||
id: iconScrubBack
|
||||
opacity: root.state.currentTaskIndex == 0 ? 0.3 : 1
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.longDuration * 2; easing.type: Easing.OutExpo } }
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
implicitWidth: Kirigami.Units.iconSizes.medium
|
||||
implicitHeight: Kirigami.Units.iconSizes.medium
|
||||
source: "draw-arrow-back"
|
||||
color: "white"
|
||||
}
|
||||
|
||||
Item {
|
||||
width: root.taskSwitcherHelpers.windowWidth / 4
|
||||
}
|
||||
|
||||
Kirigami.Icon {
|
||||
id: iconScrubFront
|
||||
opacity: root.state.currentTaskIndex == root.tasksCount - 1 ? 0.3 : 1
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.longDuration * 2; easing.type: Easing.OutExpo } }
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
implicitWidth: Kirigami.Units.iconSizes.medium
|
||||
implicitHeight: Kirigami.Units.iconSizes.medium
|
||||
source: "draw-arrow-forward"
|
||||
color: "white"
|
||||
}
|
||||
}
|
||||
|
||||
// flicking area for task switcher
|
||||
FlickContainer {
|
||||
id: flickable
|
||||
anchors.fill: container
|
||||
|
||||
taskSwitcherState: root.state
|
||||
taskSwitcherHelpers: root.taskSwitcherHelpers
|
||||
tasksCount: root.tasksCount
|
||||
|
||||
// don't allow FlickContainer to steal from swiping on tasks
|
||||
interactive: taskList.taskInteractingCount === 0
|
||||
|
||||
// the item is effectively anchored to the flickable bounds
|
||||
TaskList {
|
||||
id: taskList
|
||||
taskSwitcher: root
|
||||
shellTopMargin: root.topMargin
|
||||
shellBottomMargin: root.bottomMargin
|
||||
|
||||
|
||||
x: flickable.contentX
|
||||
width: flickable.width
|
||||
height: flickable.height
|
||||
}
|
||||
|
||||
PlasmaComponents.ToolButton {
|
||||
id: closeAllButton
|
||||
property bool closeRequested: false
|
||||
visible: root.tasksCount !== 0 && !root.taskSwitcherHelpers.isInTaskScrubMode
|
||||
enabled: !root.taskSwitcherHelpers.currentlyBeingClosed && !root.state.gestureInProgress
|
||||
|
||||
Kirigami.Theme.inherit: false
|
||||
Kirigami.Theme.colorSet: Kirigami.Theme.Complementary
|
||||
|
||||
anchors {
|
||||
bottom: taskList.bottom
|
||||
bottomMargin: (taskList.taskYBase) * 0.75
|
||||
horizontalCenter: taskList.horizontalCenter
|
||||
}
|
||||
|
||||
opacity: (root.taskSwitcherHelpers.currentlyBeingClosed || root.state.gestureInProgress || !root.taskSwitcherHelpers.taskDrawerOpened) ? 0.0 : 1.0
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.shortDuration } }
|
||||
|
||||
icon.name: "edit-clear-history"
|
||||
font.bold: true
|
||||
|
||||
text: closeRequested ? i18n("Confirm Close All") : i18n("Close All")
|
||||
|
||||
onClicked: {
|
||||
if (closeRequested) {
|
||||
taskList.closeAll();
|
||||
} else {
|
||||
closeRequested = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
image_name=${DROIDDECK_PLASMA_BUILD_IMAGE:-droiddeck-plasma-mobile-builder:6.7.5}
|
||||
|
||||
if ! docker image inspect "${image_name}" >/dev/null 2>&1; then
|
||||
docker build --platform linux/arm64 -t "${image_name}" \
|
||||
-f "${repo_root}/tools/plasma-mobile/Dockerfile" "${repo_root}/tools/plasma-mobile"
|
||||
fi
|
||||
|
||||
docker run --rm --platform linux/arm64 \
|
||||
--user "$(id -u):$(id -g)" -e HOME=/tmp \
|
||||
-v "${repo_root}:/src" -w /src "${image_name}" \
|
||||
bash /src/tools/plasma-mobile/build-in-container.sh
|
||||
|
||||
prebuilt="${repo_root}/tools/plasma-mobile/prebuilt"
|
||||
asset_root="${repo_root}/app/src/main/assets/linuxfs"
|
||||
cp "${asset_root}/usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so" \
|
||||
"${prebuilt}/org.kde.plasma.mobile.homescreen.folio.so"
|
||||
cp "${asset_root}/usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so" \
|
||||
"${prebuilt}/libmobiletaskswitcherplugin.so"
|
||||
cp "${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml" \
|
||||
"${prebuilt}/FlickContainer.qml"
|
||||
cp "${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml" \
|
||||
"${prebuilt}/TaskSwitcher.qml"
|
||||
echo "Refreshed the Plasma Mobile backports from ${image_name##*:}."
|
||||
@@ -80,15 +80,3 @@ Added by DroidDeck:
|
||||
The `faccessat2` exit stop (termux 5ba8b95, for glibc's ENOSYS fallback on kernels before 5.8) and
|
||||
the `statx` one (emulation on kernels before 4.11) are dropped when the running kernel is newer.
|
||||
Host build: `ioctl` 31.6 -> 0.5 us; `stat`/`statx`/`faccessat2` about 44 -> 28 us (one stop).
|
||||
|
||||
Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-performance.md`):
|
||||
|
||||
- `0014-fastpath-trampoline.patch` - with `PROOT_FASTPATH`, every `SECCOMP_RET_TRACE` in the filter
|
||||
is preceded by a check of the caller's address, and a syscall made from the fast path's trampoline
|
||||
page (`fastpath/fastpath.c`, `0xffff00000`) runs without a stop: the tracee already translated it.
|
||||
The check comes after the syscall-number dispatch, so untraced syscalls stay constant-ALLOW and keep
|
||||
the kernel's seccomp action cache (checking first cost every syscall the full filter: +0.5 ms an
|
||||
exec). `chdir`/`fchdir`, still emulated, also move the kernel's cwd to the host directory, and the
|
||||
first tracee starts at `-w`'s, so relative lookups inside the tracee resolve where proot would.
|
||||
SM8850 (adb shell): `stat` 25.3 -> 0.6 us, `open+close` 25.3 -> 0.9 us, ENOENT 22.9 -> 1.6 us,
|
||||
8 threads `stat`ing 89k -> 3.6M/s; equivalence suite (`bench/equiv.py`) byte-identical to proot.
|
||||
@@ -1,32 +0,0 @@
|
||||
import os, sys
|
||||
paths = ["/etc/os-release", "/root/abs-link", "/root/to-bind", "/root/to-bind/inbind.txt", "/root/rel-to-bind",
|
||||
"/root/rel-to-bind/inbind.txt", "/root/dotdot", "/root/dotdot/libc.so.6", "/root/dangling", "/root/loop",
|
||||
"/usr/lib/../lib/libc.so.6", "/usr//lib/./libc.so.6", "/lib", "/lib/libc.so.6", "/bin/env", "/nope", "/nope/x",
|
||||
"/etc/os-release/x", "/mnt/droiddeck-sd", "/mnt/droiddeck-sd/inbind.txt", "/mnt/droiddeck-sd/../bannerlator",
|
||||
"/dev/null", "/dev/shm", "/dev/shm/inbind.txt", "/dev/random", "/proc/self/exe", "/proc/version", "/proc",
|
||||
"/sys/class/thermal/thermal_zone28/temp", "/sdcard", "/", "/tmp", "/root/in-root-abs-dir/os-release",
|
||||
"/data/local/tmp/dd/tmp/inbind.txt", "/data/local/tmp/dd/mini/etc/os-release", "/root/to-bind/missing/x", "/root/to-bind/inbind.txt/x", "/usr/lib/nope/deeper/x.so", "/mnt/droiddeck-sd/nope/x", "/root/dangling/x", "/root/abs-link/x", "/nope/a/b/c", "/sdcard/nope/x"]
|
||||
rels = ["os-release", "inbind.txt", "../etc/os-release", "abs-link", "to-bind/inbind.txt", "rel-to-bind",
|
||||
"shm/inbind.txt", "null", "lib/libc.so.6", "mnt/droiddeck-sd/inbind.txt", "proc/version", "nope", "."]
|
||||
def probe(p):
|
||||
out = []
|
||||
for name, fn in [("stat", lambda: (lambda s: (oct(s.st_mode), s.st_size if not os.path.isdir(p) else 0))(os.stat(p))),
|
||||
("lstat", lambda: oct(os.lstat(p).st_mode)),
|
||||
("readlink", lambda: os.readlink(p)),
|
||||
("read", lambda: open(p, "rb").read(12)),
|
||||
("list", lambda: sorted(x for x in os.listdir(p) if not x.startswith("proot-"))[:6]),
|
||||
("access", lambda: (os.access(p, os.R_OK), os.access(p, os.W_OK), os.access(p, os.X_OK)))]:
|
||||
try: out.append(f"{name}={fn()!r}")
|
||||
except OSError as e: out.append(f"{name}=E{e.errno}")
|
||||
return " ".join(out)
|
||||
for p in paths: print(p, probe(p))
|
||||
for cwd in ["/", "/root", "/etc", "/mnt/droiddeck-sd", "/dev", "/usr/lib", "/data/local/tmp/dd/tmp", "/root/to-bind", "/root/dotdot"]:
|
||||
try: os.chdir(cwd)
|
||||
except OSError as e: print("chdir", cwd, e.errno); continue
|
||||
print("== cwd", cwd, os.getcwd())
|
||||
for r in rels: print(" ", r, probe(r))
|
||||
d = os.open(".", os.O_RDONLY)
|
||||
for r in rels[:6]:
|
||||
try: print(" at", r, oct(os.stat(r, dir_fd=d).st_mode))
|
||||
except OSError as e: print(" at", r, "E", e.errno)
|
||||
os.close(d)
|
||||
@@ -1,274 +0,0 @@
|
||||
/* Cost of the syscall-interception mechanisms available to an Android app, measured on the
|
||||
* trapped call getppid() (the tracer/handler does no work, so this is pure mechanism cost).
|
||||
*
|
||||
* mechbench filter <n_linear> allowed syscall through a filter of n JEQs (linear, proot-style)
|
||||
* mechbench tree allowed syscall through a binary-search filter (~150 entries)
|
||||
* mechbench ptrace [spin] [regs] seccomp RET_TRACE + ptrace tracer (proot's mechanism)
|
||||
* mechbench sigsys seccomp RET_TRAP + in-process SIGSYS handler
|
||||
* mechbench notif [sync] [spin] seccomp RET_USER_NOTIF + supervisor thread
|
||||
* mechbench openat2 <root> <path> openat2(RESOLVE_IN_ROOT) vs openat on the host path
|
||||
* Env CPU_T / CPU_S pin the trapped thread / the tracer-supervisor to a cpu.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/audit.h>
|
||||
#include <linux/filter.h>
|
||||
#include <linux/openat2.h>
|
||||
#include <linux/seccomp.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/ptrace.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
#include <linux/elf.h>
|
||||
|
||||
#ifndef SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP
|
||||
#define SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP (1UL << 0)
|
||||
#endif
|
||||
#ifndef SECCOMP_IOCTL_NOTIF_SET_FLAGS
|
||||
#define SECCOMP_IOCTL_NOTIF_SET_FLAGS SECCOMP_IOW(4, __u64)
|
||||
#endif
|
||||
|
||||
#define TRAPPED SYS_getppid
|
||||
static int N = 100000;
|
||||
|
||||
static double now(void) {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
return t.tv_sec * 1e9 + t.tv_nsec;
|
||||
}
|
||||
|
||||
static void pin(const char *env) {
|
||||
const char *v = getenv(env);
|
||||
if (!v) return;
|
||||
cpu_set_t s;
|
||||
CPU_ZERO(&s);
|
||||
CPU_SET(atoi(v), &s);
|
||||
sched_setaffinity(0, sizeof s, &s);
|
||||
}
|
||||
|
||||
static double time_trapped(void) {
|
||||
for (int i = 0; i < N / 10; i++) syscall(TRAPPED);
|
||||
double t0 = now();
|
||||
for (int i = 0; i < N; i++) syscall(TRAPPED);
|
||||
return (now() - t0) / N;
|
||||
}
|
||||
|
||||
/* A filter: arch check, then `n` JEQs on numbers that never match (like proot's list of ~150
|
||||
* traced syscalls seen by an allowed syscall), then `action` for TRAPPED, else ALLOW. */
|
||||
static int install(int n_linear, uint32_t action, unsigned flags) {
|
||||
struct sock_filter *f = calloc(n_linear + 16, sizeof *f);
|
||||
int k = 0;
|
||||
f[k++] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch));
|
||||
f[k++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_AARCH64, 1, 0);
|
||||
f[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW);
|
||||
f[k++] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr));
|
||||
for (int i = 0; i < n_linear; i++) /* numbers far above any real syscall */
|
||||
f[k++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 5000 + i, 0, 0);
|
||||
f[k++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TRAPPED, 0, 1);
|
||||
f[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, action);
|
||||
f[k++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW);
|
||||
struct sock_fprog p = {.len = k, .filter = f};
|
||||
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
|
||||
return syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, flags, &p);
|
||||
}
|
||||
|
||||
/* ~150 traced numbers as a balanced binary search (what libseccomp's optimize=2 emits). */
|
||||
static int emit_tree(struct sock_filter *f, int *k, int lo, int hi) {
|
||||
if (lo > hi) { f[(*k)++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW); return 0; }
|
||||
int mid = (lo + hi) / 2;
|
||||
f[(*k)++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 5000 + mid, 0, 1);
|
||||
f[(*k)++] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE);
|
||||
f[(*k)++] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JGT | BPF_K, 5000 + mid, 0, 1);
|
||||
int ja = (*k)++;
|
||||
int left = *k;
|
||||
emit_tree(f, k, lo, mid - 1);
|
||||
f[ja] = (struct sock_filter)BPF_STMT(BPF_JMP | BPF_JA, *k - left);
|
||||
emit_tree(f, k, mid + 1, hi);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void *sigsys_unused;
|
||||
static void on_sigsys(int sig, siginfo_t *si, void *ctx) {
|
||||
(void)sig; (void)si;
|
||||
ucontext_t *uc = ctx;
|
||||
uc->uc_mcontext.regs[0] = 4242; /* the emulated result */
|
||||
}
|
||||
|
||||
struct notif_arg { int fd; int spin; };
|
||||
static void *supervisor(void *a) {
|
||||
struct notif_arg *na = a;
|
||||
pin("CPU_S");
|
||||
struct seccomp_notif *req = calloc(1, 256);
|
||||
struct seccomp_notif_resp *resp = calloc(1, 256);
|
||||
for (;;) {
|
||||
memset(req, 0, sizeof *req);
|
||||
if (ioctl(na->fd, SECCOMP_IOCTL_NOTIF_RECV, req) < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
return NULL;
|
||||
}
|
||||
resp->id = req->id;
|
||||
resp->val = 4242;
|
||||
resp->error = 0;
|
||||
resp->flags = 0;
|
||||
ioctl(na->fd, SECCOMP_IOCTL_NOTIF_SEND, resp);
|
||||
}
|
||||
}
|
||||
|
||||
static int notif_fd;
|
||||
static int notif_flags_sync;
|
||||
static void *notified_worker(void *a) {
|
||||
(void)a;
|
||||
pin("CPU_T");
|
||||
notif_fd = install(0, SECCOMP_RET_USER_NOTIF, SECCOMP_FILTER_FLAG_NEW_LISTENER);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (getenv("N")) N = atoi(getenv("N"));
|
||||
const char *mode = argc > 1 ? argv[1] : "filter";
|
||||
if (!strcmp(mode, "filter")) {
|
||||
pin("CPU_T");
|
||||
printf("no filter getppid %6.0f ns\n", time_trapped());
|
||||
int n = argc > 2 ? atoi(argv[2]) : 150;
|
||||
if (install(n, SECCOMP_RET_ALLOW, 0) < 0) { perror("seccomp"); return 1; }
|
||||
printf("linear %4d JEQs getppid %6.0f ns\n", n, time_trapped());
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(mode, "tree")) {
|
||||
pin("CPU_T");
|
||||
printf("no filter getppid %6.0f ns\n", time_trapped());
|
||||
struct sock_filter f[2048];
|
||||
int k = 0;
|
||||
f[k++] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr));
|
||||
emit_tree(f, &k, 0, 149);
|
||||
struct sock_fprog p = {.len = k, .filter = f};
|
||||
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
|
||||
if (syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &p) < 0) { perror("seccomp"); return 1; }
|
||||
printf("tree of 150 (%d insns) getppid %6.0f ns\n", k, time_trapped());
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(mode, "sigsys")) {
|
||||
pin("CPU_T");
|
||||
struct sigaction sa = {0};
|
||||
sa.sa_sigaction = on_sigsys;
|
||||
sa.sa_flags = SA_SIGINFO;
|
||||
sigaction(SIGSYS, &sa, NULL);
|
||||
if (install(0, SECCOMP_RET_TRAP, 0) < 0) { perror("seccomp"); return 1; }
|
||||
long r = syscall(TRAPPED);
|
||||
printf("sigsys trap (result %ld) %6.0f ns\n", r, time_trapped());
|
||||
(void)sigsys_unused;
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(mode, "notif")) {
|
||||
int sync = argc > 2 && strstr(argv[2], "sync");
|
||||
pthread_t w, s;
|
||||
pthread_create(&w, NULL, notified_worker, NULL);
|
||||
pthread_join(w, NULL);
|
||||
if (notif_fd < 0) { perror("NEW_LISTENER"); return 1; }
|
||||
if (sync) {
|
||||
if (ioctl(notif_fd, SECCOMP_IOCTL_NOTIF_SET_FLAGS, SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP) < 0) perror("SYNC_WAKE_UP");
|
||||
else printf("(sync wake-up on)\n");
|
||||
}
|
||||
/* The filter lives on thread w, which has exited; install again on a fresh worker that
|
||||
* does the timing. */
|
||||
struct notif_arg na = {.fd = -1};
|
||||
(void)na;
|
||||
printf("note: user-notif is measured in 'notif2'\n");
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(mode, "notif2")) {
|
||||
/* Supervisor = child thread (unfiltered), timed thread = main after installing. */
|
||||
int sync = argc > 2 && !strcmp(argv[2], "sync");
|
||||
pin("CPU_T");
|
||||
int fd = install(0, SECCOMP_RET_USER_NOTIF, SECCOMP_FILTER_FLAG_NEW_LISTENER);
|
||||
if (fd < 0) { perror("NEW_LISTENER"); return 1; }
|
||||
if (sync && ioctl(fd, SECCOMP_IOCTL_NOTIF_SET_FLAGS, SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP, 0) < 0) perror("SYNC_WAKE_UP");
|
||||
/* The supervisor thread is created AFTER the filter, so it inherits it - but it only
|
||||
* makes ioctl calls, which the filter allows. */
|
||||
static struct notif_arg na;
|
||||
na.fd = fd;
|
||||
pthread_t s;
|
||||
pthread_create(&s, NULL, supervisor, &na);
|
||||
long r = syscall(TRAPPED);
|
||||
printf("user_notif%s (result %ld) %6.0f ns\n", sync ? "+sync" : "", r, time_trapped());
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(mode, "ptrace")) {
|
||||
int spin = 0, regs = 0;
|
||||
for (int i = 2; i < argc; i++) { if (!strcmp(argv[i], "spin")) spin = 1; if (!strcmp(argv[i], "regs")) regs = 1; }
|
||||
pid_t c = fork();
|
||||
if (c == 0) {
|
||||
pin("CPU_T");
|
||||
ptrace(PTRACE_TRACEME, 0, 0, 0);
|
||||
raise(SIGSTOP);
|
||||
if (install(0, SECCOMP_RET_TRACE, 0) < 0) { perror("seccomp"); _exit(1); }
|
||||
printf("ptrace+seccomp%s%s %6.0f ns\n", spin ? " spin" : "", regs ? " +getregs+setregs" : "", time_trapped());
|
||||
fflush(stdout);
|
||||
_exit(0);
|
||||
}
|
||||
pin("CPU_S");
|
||||
int st;
|
||||
waitpid(c, &st, 0);
|
||||
ptrace(PTRACE_SETOPTIONS, c, 0, PTRACE_O_TRACESECCOMP | PTRACE_O_EXITKILL);
|
||||
ptrace(PTRACE_CONT, c, 0, 0);
|
||||
for (;;) {
|
||||
pid_t p;
|
||||
if (spin) { do p = waitpid(c, &st, WNOHANG | __WALL); while (p == 0); }
|
||||
else p = waitpid(c, &st, __WALL);
|
||||
if (p < 0 || WIFEXITED(st) || WIFSIGNALED(st)) break;
|
||||
int sig = 0;
|
||||
if ((st >> 8) == (SIGTRAP | (PTRACE_EVENT_SECCOMP << 8))) {
|
||||
if (regs) {
|
||||
struct user_regs { uint64_t r[31], sp, pc, pstate; } ur;
|
||||
struct iovec io = {&ur, sizeof ur};
|
||||
ptrace(PTRACE_GETREGSET, c, NT_PRSTATUS, &io);
|
||||
ptrace(PTRACE_SETREGSET, c, NT_PRSTATUS, &io);
|
||||
}
|
||||
} else if (WIFSTOPPED(st) && WSTOPSIG(st) != SIGTRAP) sig = WSTOPSIG(st);
|
||||
ptrace(PTRACE_CONT, c, 0, sig);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (!strcmp(mode, "openat2")) {
|
||||
const char *root = argv[2], *path = argv[3];
|
||||
char host[4096];
|
||||
snprintf(host, sizeof host, "%s%s", root, path);
|
||||
int rfd = open(root, O_PATH | O_DIRECTORY);
|
||||
struct open_how how = {.flags = O_RDONLY | O_CLOEXEC, .resolve = RESOLVE_IN_ROOT};
|
||||
long fd = syscall(SYS_openat2, rfd, path, &how, sizeof how);
|
||||
if (fd < 0) { perror("openat2 RESOLVE_IN_ROOT"); return 1; }
|
||||
close(fd);
|
||||
double t0 = now();
|
||||
for (int i = 0; i < N; i++) close(open(host, O_RDONLY | O_CLOEXEC));
|
||||
printf("openat host path %6.0f ns\n", (now() - t0) / N);
|
||||
t0 = now();
|
||||
for (int i = 0; i < N; i++) close(syscall(SYS_openat2, rfd, path, &how, sizeof how));
|
||||
printf("openat2 RESOLVE_IN_ROOT %6.0f ns\n", (now() - t0) / N);
|
||||
struct stat st;
|
||||
t0 = now();
|
||||
for (int i = 0; i < N; i++) stat(host, &st);
|
||||
printf("stat host path %6.0f ns\n", (now() - t0) / N);
|
||||
struct open_how ph = {.flags = O_PATH | O_CLOEXEC, .resolve = RESOLVE_IN_ROOT | RESOLVE_NO_MAGICLINKS};
|
||||
t0 = now();
|
||||
for (int i = 0; i < N; i++) { int f = syscall(SYS_openat2, rfd, path, &ph, sizeof ph); fstat(f, &st); close(f); }
|
||||
printf("openat2(O_PATH)+fstat+close %6.0f ns\n", (now() - t0) / N);
|
||||
return 0;
|
||||
}
|
||||
fprintf(stderr, "unknown mode\n");
|
||||
return 2;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
/* T threads each stat()ing a path for D seconds: aggregate trapped-syscall throughput. */
|
||||
#define _GNU_SOURCE
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
static const char *path; static volatile int stop; static long counts[64];
|
||||
static void *run(void *a) { long i = (long)a, n = 0; struct stat st; while (!stop) { stat(path, &st); n++; } counts[i] = n; return 0; }
|
||||
int main(int c, char **v) {
|
||||
path = v[1]; int T = atoi(v[2]); double D = c > 3 ? atof(v[3]) : 2;
|
||||
pthread_t t[64]; for (long i = 0; i < T; i++) pthread_create(&t[i], 0, run, (void *)i);
|
||||
struct timespec ts = {(time_t)D, (long)((D - (long)D) * 1e9)}; nanosleep(&ts, 0); stop = 1;
|
||||
long tot = 0; for (int i = 0; i < T; i++) { pthread_join(t[i], 0); tot += counts[i]; }
|
||||
printf("threads=%d %8.0f stat/s total %6.1f us/stat per thread\n", T, tot / D, T * D * 1e6 / tot);
|
||||
return 0; }
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user