diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8eb47b0a1..f5f189da8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -22,8 +22,10 @@ permissions: pull-requests: write concurrency: - group: build-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true + # Replace older builds only for the same PR. Each push/dispatch gets its own group so one main + # build cannot cancel another before it signs and publishes. + group: build-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: PRELOAD_CACHE_VERSION: v2 @@ -34,12 +36,18 @@ jobs: if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ubuntu-24.04 timeout-minutes: 45 + outputs: + variants: ${{ steps.variants.outputs.list }} steps: - uses: actions/checkout@v4 with: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} fetch-depth: 0 + - 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: No private key in the tree run: | set -euo pipefail @@ -140,6 +148,8 @@ jobs: label="${BUILD_REF} at ${BUILD_SHA:0:7}" fi echo "label=$label" >> "$GITHUB_OUTPUT" + echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV" + echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV" echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" - name: Cache the preloads @@ -301,6 +311,9 @@ jobs: set -o pipefail ./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log + - name: Steam import and game environment tests + run: python3 -m unittest discover -s tools/tests -p 'test_*.py' + - name: Unit tests run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION" @@ -374,7 +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. After approval, a maintainer can run **PR Release Publish** from \`main\` to create an APK that installs over the release." + 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" @@ -427,5 +440,139 @@ jobs: uses: ./.github/workflows/sign.yml with: environment: signing-main - variants: '["standard"]' + variants: ${{ needs.build.outputs.variants }} secrets: inherit + + # Each signed main build as a prerelease of the public Droid-Deck/DroidDeck-CI (main-, the + # last KEEP kept), where anyone can download it without a GitHub account, then a post in the + # Discord's builds channel linking to it. The release is made with a token of the org's + # "DroidDeck CI Publisher" app (installed on DroidDeck-CI only, Contents: write): its ID in the + # DROIDDECK_CI_APP_ID variable, its private key in the DROIDDECK_CI_APP_KEY secret. + # DISCORD_BUILDS_WEBHOOK is the channel's webhook URL. + announce: + needs: [build, sign] + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + pull-requests: read + env: + CI_REPO: Droid-Deck/DroidDeck-CI + KEEP: 10 + steps: + - uses: actions/download-artifact@v4 + with: + pattern: droiddeck-signed-* + merge-multiple: true + path: signed + + - 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 + + # What this build is, for the top of the release notes: the merged PR's title and the first + # paragraph of its description, or the commit's subject for a push made without a PR. + - name: Describe the change + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + pr=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" \ + --jq '[.[] | select(.merged_at != null and .base.ref == "main")] | first // empty') + if [ -n "$pr" ]; then + number=$(jq -r .number <<<"$pr") + title=$(jq -r .title <<<"$pr") + merged=$(jq -r '.merged_at[:10]' <<<"$pr") + summary=$(jq -r '.body // ""' <<<"$pr" | tr -d '\r' | { grep -v '^🤖' || true; } | + awk '!p && /^#/ { next } NF { p = 1; print; next } p { exit }' | head -n 6 | cut -c1-400) + { + echo "**Merged to main** - [PR #$number]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$number): $title (merged $merged)" + if [ -n "$summary" ]; then + echo + echo "$summary" + fi + } > notes-head.md + else + subject=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA" --jq '.commit.message | split("\n")[0]') + echo "**Pushed to main** without a PR - $subject" > notes-head.md + fi + cat notes-head.md + + - name: Publish to DroidDeck-CI + id: publish + env: + GH_TOKEN: ${{ steps.ci-token.outputs.token }} + run: | + set -euo pipefail + tag=main-${GITHUB_SHA::7} + cat signed/SHA256SUMS-*.txt > signed/SHA256SUMS.txt + rm signed/SHA256SUMS-*.txt + 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. + 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) + \`\`\`" + gh release delete "$tag" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null || true + gh release create "$tag" -R "$CI_REPO" --target main --prerelease \ + --title "main ${GITHUB_SHA::7}" --notes "$notes" signed/* + # Keep the newest main builds by publication time. GitHub App releases can share createdAt. + gh release list -R "$CI_REPO" -L 200 --json tagName,publishedAt \ + --jq '[.[] | select(.tagName | startswith("main-"))] | sort_by(.publishedAt) | reverse | .['"$KEEP"':][] | .tagName' | + while IFS= read -r old; do + # Never remove this run's release, even if the API returns an unexpected ordering. + if [ "$old" = "$tag" ]; then + continue + fi + # Another main publish may have removed the same old release concurrently. + if ! gh release delete "$old" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null; then + if gh release view "$old" -R "$CI_REPO" >/dev/null 2>&1; then + echo "::error::Could not delete old release $old" + exit 1 + fi + fi + done + published=$(gh release view "$tag" -R "$CI_REPO" --json tagName,assets) + jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<< "$published" >/dev/null + url="$GITHUB_SERVER_URL/$CI_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=$url" >> "$GITHUB_OUTPUT" + echo "apk=$GITHUB_SERVER_URL/$CI_REPO/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT" + echo "Published $url" + + - name: Post to Discord + env: + WEBHOOK: ${{ secrets.DISCORD_BUILDS_WEBHOOK }} + GH_TOKEN: ${{ github.token }} + 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 + commit=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA") + subject=$(jq -r '.commit.message | split("\n")[0]' <<<"$commit") + # A merge commit's subject is "Merge pull request #N from ..."; its body's first line is + # the PR's title, which says more. + title=$(jq -r '.commit.message | split("\n") | map(select(length > 0)) | .[1] // ""' <<<"$commit") + pr=$(sed -n 's/^Merge pull request #\([0-9]*\).*/\1/p' <<<"$subject") + if [ -n "$pr" ]; then + what="[#$pr]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$pr): ${title:-$subject}" + else + what="[\`${GITHUB_SHA::7}\`]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA): $subject" + fi + get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE") + content=$(printf '**New signed build** `main-%s`\n%s\n%s' "${GITHUB_SHA::7}" "$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" diff --git a/.github/workflows/pr-release-cleanup.yml b/.github/workflows/pr-release-cleanup.yml new file mode 100644 index 000000000..abe506be3 --- /dev/null +++ b/.github/workflows/pr-release-cleanup.yml @@ -0,0 +1,39 @@ +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 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: {} + +jobs: + cleanup: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + # A token of the org's "DroidDeck CI Publisher" app, as build.yml's announce job uses. + - uses: actions/create-github-app-token@v2 + id: ci-token + with: + app-id: ${{ vars.DROIDDECK_CI_APP_ID }} + private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }} + owner: Droid-Deck + repositories: DroidDeck-CI + - name: Delete the test build + env: + GH_TOKEN: ${{ steps.ci-token.outputs.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + set -euo pipefail + 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 diff --git a/.github/workflows/pr-release-publish.yml b/.github/workflows/pr-release-publish.yml index 1759674c1..afc3cfa09 100644 --- a/.github/workflows/pr-release-publish.yml +++ b/.github/workflows/pr-release-publish.yml @@ -5,7 +5,7 @@ on: workflow_dispatch: inputs: pr_number: - description: Open, approved pull request + description: Open pull request required: true type: number @@ -26,8 +26,16 @@ jobs: run_id: ${{ steps.gate.outputs.run_id }} head_sha: ${{ steps.gate.outputs.head_sha }} label: ${{ steps.gate.outputs.label }} + variants: ${{ steps.variants.outputs.list }} steps: - - name: Check the PR, review, and build + - uses: actions/checkout@v4 + with: + persist-credentials: false + # Every variant a main build ships, so a PR build can be tried under any of them. + - name: The packages a signed build ships as + id: variants + run: echo "list=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT" + - name: Check the PR and build id: gate env: GH_TOKEN: ${{ github.token }} @@ -52,24 +60,11 @@ jobs: any(.pull_requests[]?; .number == $number and .head.sha == $head and .base.sha == $base) ' <<<"$run" >/dev/null - approved=$(gh api --paginate --slurp \ - "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/reviews?per_page=100" | - jq -r --arg head "$head" '[.[][] | select(.commit_id == $head)] | - group_by(.user.login) | map(max_by(.id)) | .[] | - select(.state == "APPROVED") | .user.login') - maintainer_approved=false - while IFS= read -r reviewer; do - [[ -n "$reviewer" ]] || continue - permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$reviewer/permission" --jq .permission) - [[ "$permission" == write || "$permission" == admin ]] && maintainer_approved=true - done <<<"$approved" - [[ "$maintainer_approved" == true ]] || { echo '::error::A maintainer must approve this commit'; exit 1; } - sdk=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}} tools=$(find "$sdk/build-tools" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -1) - stable_tag=$(gh api repos/The412Banner/DroidDeck/releases/latest --jq .tag_name) + stable_tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name) mkdir -p "$RUNNER_TEMP/stable" "$RUNNER_TEMP/pr" - gh release download "$stable_tag" -R The412Banner/DroidDeck \ + gh release download "$stable_tag" -R "$GITHUB_REPOSITORY" \ -p "DroidDeck-$stable_tag.apk" -D "$RUNNER_TEMP/stable" gh run download "$run_id" -R "$GITHUB_REPOSITORY" -n droiddeck-apk -D "$RUNNER_TEMP/pr" mapfile -t apks < <(find "$RUNNER_TEMP/pr" -type f -name '*.apk') @@ -89,9 +84,6 @@ jobs: .state == "open" and .draft == false and .base.ref == "main" and .head.sha == $head and .base.sha == $base ' <<<"$current" >/dev/null - [[ $(gh pr view "$PR_NUMBER" -R "$GITHUB_REPOSITORY" --json reviewDecision --jq .reviewDecision) == APPROVED ]] || { - echo '::error::The current PR revision still needs approval'; exit 1; - } { echo "run_id=$run_id" echo "head_sha=$head" @@ -103,7 +95,7 @@ jobs: uses: ./.github/workflows/sign.yml with: environment: signing-main - variants: '["standard"]' + variants: ${{ needs.authorize.outputs.variants }} run_id: ${{ needs.authorize.outputs.run_id }} label: ${{ needs.authorize.outputs.label }} artifact: droiddeck-pr-signed @@ -115,37 +107,71 @@ jobs: permissions: actions: read contents: read + pull-requests: read steps: - uses: actions/download-artifact@v4 with: - name: droiddeck-pr-signed-standard + pattern: droiddeck-pr-signed-* + merge-multiple: true path: signed - - name: Publish to DroidDeck-CI when configured + # What this build is, for the top of the release notes: the PR's title and the first + # paragraph of its description. + - name: Describe the change env: - GH_TOKEN: ${{ secrets.DROIDDECK_CI_TOKEN }} + GH_TOKEN: ${{ github.token }} PR_NUMBER: ${{ inputs.pr_number }} - HEAD_SHA: ${{ needs.authorize.outputs.head_sha }} - LABEL: ${{ needs.authorize.outputs.label }} run: | set -euo pipefail - if [[ -z "$GH_TOKEN" ]]; then - echo '::warning::No CI token; download the signed APK from this run' - exit 0 - fi + pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") + title=$(jq -r .title <<<"$pr") + summary=$(jq -r '.body // ""' <<<"$pr" | tr -d '\r' | { grep -v '^🤖' || true; } | + awk '!p && /^#/ { next } NF { p = 1; print; next } p { exit }' | head -n 6 | cut -c1-400) + { + echo "**Not merged** - a test build of open [PR #$PR_NUMBER]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$PR_NUMBER): $title" + if [ -n "$summary" ]; then + echo + echo "$summary" + fi + } > notes-head.md + cat notes-head.md + # A token of the org's "DroidDeck CI Publisher" app, as build.yml's announce job uses. + - uses: actions/create-github-app-token@v2 + id: ci-token + with: + app-id: ${{ vars.DROIDDECK_CI_APP_ID }} + private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }} + owner: Droid-Deck + repositories: DroidDeck-CI + - name: Publish to DroidDeck-CI + env: + GH_TOKEN: ${{ steps.ci-token.outputs.token }} + PR_NUMBER: ${{ inputs.pr_number }} + HEAD_SHA: ${{ needs.authorize.outputs.head_sha }} + run: | + set -euo pipefail repo=Droid-Deck/DroidDeck-CI tag="pr-$PR_NUMBER" - apk="DroidDeck-$LABEL.apk" - sha=$(sha256sum "signed/$apk" | cut -d ' ' -f 1) - notes="Source: https://github.com/$GITHUB_REPOSITORY/pull/$PR_NUMBER + cat signed/SHA256SUMS-*.txt > signed/SHA256SUMS.txt + rm signed/SHA256SUMS-*.txt + notes="$(cat notes-head.md) + + Source: https://github.com/$GITHUB_REPOSITORY/pull/$PR_NUMBER Commit: $HEAD_SHA - APK SHA-256: $sha" + 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) + \`\`\`" 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 fi - gh release upload "$tag" "signed/$apk" -R "$repo" --clobber + 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. + keep=$(cd signed && ls | jq -R . | jq -sc .) gh api "repos/$repo/releases/tags/$tag" | - jq -r --arg keep "$apk" '.assets[] | select(.name | endswith(".apk")) | select(.name != $keep) | .id' | + jq -r --argjson keep "$keep" '.assets[] | select(.name as $n | $keep | index($n) | not) | .id' | while IFS= read -r id; do gh api --method DELETE "repos/$repo/releases/assets/$id" >/dev/null done diff --git a/.gitignore b/.gitignore index 54cad4e34..3240a2ea0 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ captures/ # copies cannot drift. app/src/main/assets/linuxfs/ app/src/main/jniLibs/arm64-v8a/libproot.so +app/src/main/jniLibs/arm64-v8a/.proot-inputs app/src/main/jniLibs/arm64-v8a/libproot-loader.so # Kotlin compiler session files (build-tool state, never source). @@ -29,3 +30,6 @@ app/src/main/jniLibs/arm64-v8a/libproot-loader.so droiddeck-release-key/ password.txt __pycache__/ + +# Local signing with the release key (tools/build_local.sh); holds a password. +.signing.env diff --git a/README.md b/README.md index 664860498..ea1242bb2 100644 --- a/README.md +++ b/README.md @@ -7,14 +7,20 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton. +

Join the DroidDeck Discord

+

Tapping DroidDeck on the Android home screen and landing in Steam Big Picture

## 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/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. +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, 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 Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, and `zstd` installed. It builds the ARM64 audio sinks from PulseAudio 13.0 and packages them into the APK at `app/build/outputs/apk/release/app-release.apk`. Set `DROIDDECK_PA13_SOURCE_DIR` to an existing PulseAudio 13.0 source directory to skip downloading it. To install the APK on an attached device, run `tools/deploy_local.sh`. @@ -25,4 +31,4 @@ Compatibility and performance vary by device; hardware validation is limited. De ## Credits and licence -GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. +GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. diff --git a/app/build.gradle b/app/build.gradle index 4195f0be8..37efe56dc 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -49,6 +49,20 @@ if (!(treeState in ['clean', 'dirty'])) { buildLabel = "${buildOrigin} ${treeState} · ${buildLabel}" def escapedBuildLabel = buildLabel.replace('\\', '\\\\').replace('"', '\\"') +// What the in-app updater compares against the published builds: the commit this build is of (a PR +// build's head, not the merge CI makes of it), its PR, and whether CI made it at all. +def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getOrNull() + ?: providers.environmentVariable('GITHUB_SHA').getOrNull() ?: gitValue(['rev-parse', 'HEAD']) ?: '' +def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' } +def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true' +// When the source was committed, for "built 3 hours ago": fixed per commit, so it costs no rebuilds. +def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with { it.isLong() ? it : '0' } +// tools/release/variants.txt as "package=suffix;...", so the updater picks the apk of the package it runs as. +def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines() + .findAll { it.trim() && !it.startsWith('#') } + .collect { def f = it.trim().split(/\s+/); "${f[1]}=${f[2] == '-' ? '' : f[2]}" } + .join(';') + android { namespace 'com.droiddeck.launcher' compileSdk 34 @@ -66,6 +80,11 @@ android { versionCode 9 versionName "0.2.0" buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\"" + buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\"" + buildConfigField "int", "PR_NUMBER", "${prNumber}" + buildConfigField "boolean", "CI_BUILD", "${ciBuild}" + buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L" + buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\"" ndk { abiFilters 'arm64-v8a' @@ -176,4 +195,5 @@ dependencies { implementation 'com.termux.termux-app:terminal-view:0.118.0' testImplementation 'junit:junit:4.13.2' + testImplementation 'org.robolectric:robolectric:4.16.1' } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index fba4727ba..55cb72337 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -22,6 +22,8 @@ relay helper opens the input stream under this uid, and PulseAudio exposes it to the Steam client as DirectAudioMic. --> + + @@ -130,6 +132,9 @@ + #include @@ -24,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -31,12 +34,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -80,6 +85,11 @@ static constexpr uint32_t FAKE_INPUT_RING_CAPACITY = 4096; static constexpr unsigned int FAKE_INPUT_MAJOR = 13; static constexpr unsigned int FAKE_INPUT_EVENT_MINOR_BASE = 64; static constexpr unsigned int FAKE_INPUT_JS_MINOR_BASE = 0; +// Nodes from event16 up are the virtual pads programs make through the /dev/uinput stand-in; +// below that are the app's own rings, one per slot. +static constexpr int UINPUT_EVENT_BASE = 16; +static constexpr int UINPUT_EVENT_LIMIT = 64; +static constexpr uint32_t UINPUT_DESCRIPTION_MAGIC = 0x46495544; struct FakeInputRingHeader { uint32_t magic; // 0 @@ -107,8 +117,28 @@ static constexpr size_t FAKE_INPUT_RING_SIZE = FAKE_INPUT_RING_HEADER_SIZE + (FAKE_INPUT_RING_CAPACITY * FAKE_INPUT_EVENT_SIZE); +// What a program told the /dev/uinput stand-in about the device it made, stored after the ring +// in that device's file so every process that opens the node answers the same identity. +struct UinputDescription { + uint32_t magic; + int32_t owner_pid; + struct input_id id; + uint32_t ff_effects_max; + char name[UINPUT_MAX_NAME_SIZE]; + char phys[64]; + uint8_t evbits[(EV_MAX + 8) / 8]; + uint8_t keybits[(KEY_MAX + 8) / 8]; + uint8_t absbits[(ABS_MAX + 8) / 8]; + uint8_t ffbits[(FF_MAX + 8) / 8]; + struct input_absinfo absinfo[ABS_CNT]; +}; + +static constexpr size_t UINPUT_FILE_SIZE = FAKE_INPUT_RING_SIZE + sizeof(UinputDescription); + struct FakeController { char *event = nullptr; + // Set for a node made through the /dev/uinput stand-in; null for the app's own pads. + const UinputDescription *uinput = nullptr; int slot = -1; FakeInputRingHeader *ring = nullptr; uint64_t read_seq = 0; @@ -189,6 +219,7 @@ struct FakeConfig { const char *udev_data_dir; bool vibration_enabled; bool xbox360_identity; + bool uinput_enabled; }; static FakeConfig &config() { @@ -201,6 +232,7 @@ static FakeConfig &config() { getenv("FAKE_EVDEV_VIBRATION") && atoi(getenv("FAKE_EVDEV_VIBRATION")); const char *identity = getenv("FAKE_EVDEV_IDENTITY"); c->xbox360_identity = identity && !strcmp(identity, "xbox360"); + c->uinput_enabled = getenv("FAKE_EVDEV_UINPUT") && atoi(getenv("FAKE_EVDEV_UINPUT")); pthread_atfork(controller_fork_prepare, controller_fork_parent, controller_fork_child); Logger::init(); @@ -233,6 +265,7 @@ static const char *fake_hook_dir() { return config().hook_dir; } static const char *fake_udev_data_dir() { return config().udev_data_dir; } static bool fake_vibration_enabled() { return config().vibration_enabled; } static bool fake_xbox360_identity() { return config().xbox360_identity; } +static bool fake_uinput_enabled() { return config().uinput_enabled; } static bool ring_paths_loaded = false; static int next_ff_id = 0; @@ -535,10 +568,22 @@ keyframe_value(const FakeController &fake, uint16_t type, uint16_t code) { return 0; // SYN / unknown } +// A virtual pad's ring and description live beside its node, hidden from anything that lists +// event* names: /dev/input/.uinput-event. +__attribute__((visibility("hidden"))) static std::string uinput_ring_path(int node) { + return std::string(fake_hook_dir()) + "/.uinput-event" + std::to_string(node); +} + +__attribute__((visibility("hidden"))) static bool process_alive(pid_t pid) { + return pid > 0 && (kill(pid, 0) == 0 || errno == EPERM); +} + __attribute__((visibility("hidden"))) static int open_fake_input_ring(const char *event, int flags) { int slot = get_event_number(event); - std::string ring_path = get_ring_path_for_slot(slot); + bool virtual_pad = slot >= UINPUT_EVENT_BASE; + std::string ring_path = virtual_pad ? uinput_ring_path(slot) : get_ring_path_for_slot(slot); + size_t mapping_size = virtual_pad ? UINPUT_FILE_SIZE : FAKE_INPUT_RING_SIZE; if (ring_path.empty()) { Logger::log("No input ring is configured for %s (slot %d)\n", event, slot); errno = ENODEV; @@ -551,8 +596,7 @@ open_fake_input_ring(const char *event, int flags) { if (fd < 0) return -1; - void *mapping = - mmap(nullptr, FAKE_INPUT_RING_SIZE, PROT_READ, MAP_SHARED, fd, 0); + void *mapping = mmap(nullptr, mapping_size, PROT_READ, MAP_SHARED, fd, 0); if (mapping == MAP_FAILED) { int saved_errno = errno; syscall(SYS_close, fd); @@ -562,9 +606,16 @@ open_fake_input_ring(const char *event, int flags) { FakeInputRingHeader *ring = reinterpret_cast(mapping); - if (!ring_header_is_valid(ring)) { + const UinputDescription *description = + virtual_pad ? reinterpret_cast( + static_cast(mapping) + FAKE_INPUT_RING_SIZE) + : nullptr; + // A virtual pad whose maker has gone (a crashed client leaves its files) is not there. + if (!ring_header_is_valid(ring) || + (description && (description->magic != UINPUT_DESCRIPTION_MAGIC || + !process_alive(description->owner_pid)))) { Logger::log("Input ring %s has no valid header\n", ring_path.c_str()); - munmap(mapping, FAKE_INPUT_RING_SIZE); + munmap(mapping, mapping_size); syscall(SYS_close, fd); errno = ENODEV; return -1; @@ -574,7 +625,8 @@ open_fake_input_ring(const char *event, int flags) { controller->event = strdup(event); controller->slot = slot; controller->ring = ring; - controller->mapping_size = FAKE_INPUT_RING_SIZE; + controller->uinput = description; + controller->mapping_size = mapping_size; controller->generation = ring_generation(ring); // Establish the cursor at open so taps arriving before the first read stay // queued. If publication is busy, read() will finish establishing it later. @@ -618,20 +670,32 @@ __attribute__((visibility("hidden"))) static bool presents_steam_virtual() { // 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. -__attribute__((visibility("hidden"))) static uint16_t presented_abs_code(uint16_t code) { - if (!presents_steam_virtual()) return code; +// 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 || presents_steam_virtual(); +} + +__attribute__((visibility("hidden"))) static uint16_t +presented_abs_code(const FakeController &fake, uint16_t code) { + if (!presents_xbox_triggers(fake)) return code; if (code == ABS_BRAKE) return ABS_Z; if (code == ABS_GAS) return ABS_RZ; return code; } -__attribute__((visibility("hidden"))) static uint16_t ring_abs_code(uint16_t code) { - if (!presents_steam_virtual()) return code; +// The snapshot keeps the triggers in the ABS_GAS/ABS_BRAKE places either way. +__attribute__((visibility("hidden"))) static uint16_t snapshot_abs_code(uint16_t code) { if (code == ABS_Z) return ABS_BRAKE; if (code == ABS_RZ) return ABS_GAS; return code; } +__attribute__((visibility("hidden"))) static uint16_t +ring_abs_code(const FakeController &fake, uint16_t code) { + return presents_xbox_triggers(fake) ? snapshot_abs_code(code) : code; +} + __attribute__((visibility("hidden"))) static void copy_slot_ioctl_string(int op, void *argp, const char *format, int event_number) { size_t size = _IOC_SIZE(op); @@ -707,6 +771,793 @@ __attribute__((visibility("hidden"))) static long long monotonic_ms() { return static_cast(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL; } +// ---- /dev/uinput, stood in for ---- +// +// Under Steam, a game is meant to read Steam Input's output, not the pad: the client hides the +// physical pad from the game (SDL_GAMECONTROLLER_IGNORE_DEVICES, and its overlay refuses the +// open) and makes it a virtual X-Box 360 pad through /dev/uinput, which it then drives with the +// layout the player chose. The sandbox has no uinput the client may use, so the virtual pad never +// appeared and every game was left reading the physical pad as-is. +// +// So /dev/uinput is answered here. A gamepad the client makes becomes another of this library's +// nodes - /dev/input/event16 and up - backed by a ring file of the same layout the app writes, +// and the client's writes are that ring's events. Any process reading the node sees the identity +// the client gave it and gets exactly what the client wrote. A device that is not a gamepad (the +// client's virtual keyboard and mouse) is accepted and its events dropped, which is what happened +// to them before. +struct UinputWriter { + UinputDescription description{}; + bool created = false; + bool published = false; + int node = -1; + pid_t owner = 0; + FakeInputRingHeader *ring = nullptr; + UinputDescription *shared = nullptr; + std::vector pending; + uint32_t buttons = 0; + int16_t axes[8] = {}; +}; + +static std::unordered_map> &uinput_map() { + static auto *map = new std::unordered_map>(); + return *map; +} + +__attribute__((visibility("hidden"))) static bool is_uinput_path(const char *pathname) { + return pathname && (!strcmp(pathname, "/dev/uinput") || !strcmp(pathname, "/dev/input/uinput")); +} + +__attribute__((visibility("hidden"))) static void set_bit(uint8_t *bits, size_t size, int bit) { + if (bit >= 0 && static_cast(bit) / 8 < size) bits[bit / 8] |= 1u << (bit % 8); +} + +__attribute__((visibility("hidden"))) static bool test_bit(const uint8_t *bits, size_t size, int bit) { + return bit >= 0 && static_cast(bit) / 8 < size && (bits[bit / 8] >> (bit % 8)) & 1u; +} + +// A real uinput fd reads EV_UINPUT requests and polls as writable. An eventfd that is never +// signalled does both: nothing to read, always writable, blocking or not as the caller asked. +__attribute__((visibility("hidden"))) static int open_uinput(int flags) { + int fd = eventfd(0, ((flags & O_NONBLOCK) ? EFD_NONBLOCK : 0) | ((flags & O_CLOEXEC) ? EFD_CLOEXEC : 0)); + if (fd < 0) return -1; + auto writer = std::make_shared(); + writer->owner = getpid(); + std::lock_guard guard(controller_mutex()); + uinput_map()[fd] = writer; + Logger::log("uinput: opened as fd %d\n", fd); + return fd; +} + +// The layout the client asks for only matters to readers; what makes it a pad is a south button +// and a left stick, which is also what every pad the ring format carries has. +__attribute__((visibility("hidden"))) static bool is_gamepad(const UinputDescription &d) { + return test_bit(d.evbits, sizeof(d.evbits), EV_KEY) && test_bit(d.keybits, sizeof(d.keybits), BTN_SOUTH) && + test_bit(d.evbits, sizeof(d.evbits), EV_ABS) && test_bit(d.absbits, sizeof(d.absbits), ABS_X); +} + +__attribute__((visibility("hidden"))) static void unpublish_uinput(UinputWriter &w) { + if (!w.published) return; + // Readers holding the mapping see the generation move and report the device gone; the node's + // removal is what tells SDL and Wine through inotify. + __atomic_add_fetch(&w.ring->generation, 1, __ATOMIC_RELEASE); + std::string node = std::string(fake_hook_dir()) + "/event" + std::to_string(w.node); + unlink(node.c_str()); + unlink((uinput_ring_path(w.node) + ".uevent").c_str()); + unlink(uinput_ring_path(w.node).c_str()); + munmap(w.ring, UINPUT_FILE_SIZE); + Logger::log("uinput: removed event%d\n", w.node); + w.ring = nullptr; + w.shared = nullptr; + w.published = false; +} + +// A node number is claimed by creating its ring file exclusively, so two processes making pads +// at once cannot take the same one. A file left by a process that has gone is reclaimed. +__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) { + static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) { + std::string path = uinput_ring_path(node); + int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + if (fd >= 0) { + *fd_out = fd; + return node; + } + if (errno != EEXIST) return -1; + int existing = my_open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (existing < 0) continue; + UinputDescription old{}; + bool stale = pread(existing, &old, sizeof(old), FAKE_INPUT_RING_SIZE) == sizeof(old) && + old.magic == UINPUT_DESCRIPTION_MAGIC && !process_alive(old.owner_pid); + syscall(SYS_close, existing); + if (stale) { + unlink((std::string(fake_hook_dir()) + "/event" + std::to_string(node)).c_str()); + unlink((path + ".uevent").c_str()); + unlink(path.c_str()); + node--; // try the same number again + } + } + errno = ENOSPC; + return -1; +} + +__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) { + static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + int fd = -1; + int node = claim_uinput_node(&fd); + if (node < 0) return -1; + void *mapping = MAP_FAILED; + if (ftruncate(fd, UINPUT_FILE_SIZE) == 0) + mapping = mmap(nullptr, UINPUT_FILE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + syscall(SYS_close, fd); + std::string ring_path = uinput_ring_path(node); + if (mapping == MAP_FAILED) { + unlink(ring_path.c_str()); + return -1; + } + auto *ring = static_cast(mapping); + ring->magic = FAKE_INPUT_RING_MAGIC; + ring->version = FAKE_INPUT_RING_VERSION; + ring->event_size = FAKE_INPUT_EVENT_SIZE; + ring->capacity = FAKE_INPUT_RING_CAPACITY; + ring->generation = 1; + auto *shared = reinterpret_cast(static_cast(mapping) + FAKE_INPUT_RING_SIZE); + *shared = w.description; + shared->magic = UINPUT_DESCRIPTION_MAGIC; + shared->owner_pid = w.owner; + __atomic_thread_fence(__ATOMIC_RELEASE); + + // The identity Wine's HID bus reads through libudev (inputudev.c in libblsession), written + // before the node so the first lookup finds it. + char uevent[256]; + int length = snprintf(uevent, sizeof(uevent), "PRODUCT=%x/%x/%x/%x\nNAME=\"%s\"\nPHYS=\"%s\"\n", + shared->id.bustype, shared->id.vendor, shared->id.product, shared->id.version, + shared->name, shared->phys); + int uevent_fd = my_open((ring_path + ".uevent").c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (uevent_fd >= 0) { + if (write(uevent_fd, uevent, std::min(length, sizeof(uevent) - 1)) < 0) {} + syscall(SYS_close, uevent_fd); + } + std::string node_path = std::string(fake_hook_dir()) + "/event" + std::to_string(node); + int node_fd = my_open(node_path.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0644); + if (node_fd < 0) { + munmap(mapping, UINPUT_FILE_SIZE); + unlink((ring_path + ".uevent").c_str()); + unlink(ring_path.c_str()); + return -1; + } + syscall(SYS_close, node_fd); + w.node = node; + w.ring = ring; + w.shared = shared; + w.published = true; + Logger::log("uinput: \"%s\" %04x:%04x is /dev/input/event%d\n", shared->name, shared->id.vendor, + shared->id.product, node); + return 0; +} + +// Same publication as the app's writer (FakeInputWriter.flushBufferToRing): the events, then the +// absolute state under its seqlock, then the cursor that makes both visible. +__attribute__((visibility("hidden"))) static void flush_uinput(UinputWriter &w) { + if (!w.published || w.pending.empty()) { + w.pending.clear(); + return; + } + FakeInputRingHeader *ring = w.ring; + auto *events = reinterpret_cast(reinterpret_cast(ring) + + FAKE_INPUT_RING_HEADER_SIZE); + uint64_t write_seq = __atomic_load_n(&ring->write_seq, __ATOMIC_RELAXED); + struct timeval now = {}; + gettimeofday(&now, nullptr); + for (struct input_event ev : w.pending) { + ev.time = now; + events[write_seq % FAKE_INPUT_RING_CAPACITY] = ev; + write_seq++; + if (ev.type == EV_KEY) { + for (size_t i = 0; i < kSnapshotButtonCount; i++) + if (kSnapshotButtons[i] == ev.code) + w.buttons = ev.value ? (w.buttons | (1u << i)) : (w.buttons & ~(1u << i)); + } else if (ev.type == EV_ABS) { + uint16_t code = snapshot_abs_code(ev.code); + for (int i = 0; i < 8; i++) + if (kSnapshotAxisCodes[i] == code) + w.axes[i] = static_cast(std::max(-32768, std::min(32767, ev.value))); + } + } + w.pending.clear(); + uint64_t sequence = __atomic_load_n(&ring->snapshot_seq, __ATOMIC_RELAXED); + __atomic_store_n(&ring->snapshot_seq, sequence + 1, __ATOMIC_RELAXED); + __atomic_thread_fence(__ATOMIC_RELEASE); + __atomic_store_n(&ring->snapshot_buttons, w.buttons, __ATOMIC_RELAXED); + for (int i = 0; i < 8; i++) __atomic_store_n(&ring->snapshot_axes[i], w.axes[i], __ATOMIC_RELAXED); + __atomic_thread_fence(__ATOMIC_RELEASE); + __atomic_store_n(&ring->snapshot_seq, sequence + 2, __ATOMIC_RELEASE); + __atomic_store_n(&ring->write_seq, write_seq, __ATOMIC_RELEASE); +} + +__attribute__((visibility("hidden"))) static ssize_t +write_uinput(UinputWriter &w, const void *buf, size_t count) { + if (!w.created) { + // The legacy description: written once, before UI_DEV_CREATE. + if (count != sizeof(struct uinput_user_dev)) { + errno = EINVAL; + return -1; + } + const auto *legacy = static_cast(buf); + memcpy(w.description.name, legacy->name, sizeof(w.description.name)); + w.description.name[sizeof(w.description.name) - 1] = '\0'; + w.description.id = legacy->id; + w.description.ff_effects_max = legacy->ff_effects_max; + for (int i = 0; i < ABS_CNT; i++) { + w.description.absinfo[i].minimum = legacy->absmin[i]; + w.description.absinfo[i].maximum = legacy->absmax[i]; + w.description.absinfo[i].fuzz = legacy->absfuzz[i]; + w.description.absinfo[i].flat = legacy->absflat[i]; + } + return static_cast(count); + } + if (count % sizeof(struct input_event)) { + errno = EINVAL; + return -1; + } + const auto *events = static_cast(buf); + for (size_t i = 0; i < count / sizeof(struct input_event); i++) { + w.pending.push_back(events[i]); + // A frame ends at SYN_REPORT; a writer that never sends one still gets its events out. + if ((events[i].type == EV_SYN && events[i].code == SYN_REPORT) || w.pending.size() >= 64) + flush_uinput(w); + } + return static_cast(count); +} + +__attribute__((visibility("hidden"))) static int +ioctl_uinput(UinputWriter &w, ioctl_request_t op, void *argp) { + if (_IOC_TYPE(op) != UINPUT_IOCTL_BASE) { + errno = ENOTTY; + return -1; + } + int number = _IOC_NR(op); + int value = static_cast(reinterpret_cast(argp)); + UinputDescription &d = w.description; + if (number == _IOC_NR(UI_GET_VERSION)) { + *static_cast(argp) = 5; + return 0; + } + if (number == _IOC_NR(UI_GET_SYSNAME(0))) { + if (!w.created) { + errno = ENOENT; + return -1; + } + snprintf(static_cast(argp), _IOC_SIZE(op), "input%d", w.published ? w.node : 0); + return 0; + } + if (number == _IOC_NR(UI_DEV_DESTROY)) { + if (getpid() == w.owner) unpublish_uinput(w); + w.created = false; + return 0; + } + if (w.created && number != _IOC_NR(UI_BEGIN_FF_UPLOAD) && number != _IOC_NR(UI_END_FF_UPLOAD) && + number != _IOC_NR(UI_BEGIN_FF_ERASE) && number != _IOC_NR(UI_END_FF_ERASE)) { + errno = EINVAL; // the kernel refuses configuration once the device exists + return -1; + } + switch (number) { + case _IOC_NR(UI_SET_EVBIT): set_bit(d.evbits, sizeof(d.evbits), value); return 0; + case _IOC_NR(UI_SET_KEYBIT): set_bit(d.keybits, sizeof(d.keybits), value); return 0; + case _IOC_NR(UI_SET_ABSBIT): set_bit(d.absbits, sizeof(d.absbits), value); return 0; + case _IOC_NR(UI_SET_FFBIT): set_bit(d.ffbits, sizeof(d.ffbits), value); return 0; + case _IOC_NR(UI_SET_RELBIT): + case _IOC_NR(UI_SET_MSCBIT): + case _IOC_NR(UI_SET_LEDBIT): + case _IOC_NR(UI_SET_SNDBIT): + case _IOC_NR(UI_SET_SWBIT): + case _IOC_NR(UI_SET_PROPBIT): + return 0; + case _IOC_NR(UI_SET_PHYS): + snprintf(d.phys, sizeof(d.phys), "%s", static_cast(argp)); + return 0; + case _IOC_NR(UI_DEV_SETUP): { + const auto *setup = static_cast(argp); + d.id = setup->id; + memcpy(d.name, setup->name, sizeof(d.name)); + d.name[sizeof(d.name) - 1] = '\0'; + d.ff_effects_max = setup->ff_effects_max; + return 0; + } + case _IOC_NR(UI_ABS_SETUP): { + const auto *setup = static_cast(argp); + if (setup->code >= ABS_CNT) { + errno = EINVAL; + return -1; + } + d.absinfo[setup->code] = setup->absinfo; + return 0; + } + case _IOC_NR(UI_DEV_CREATE): + w.created = true; + if (!is_gamepad(d)) { + Logger::log("uinput: \"%s\" %04x:%04x is not a gamepad; its events are dropped\n", d.name, + d.id.vendor, d.id.product); + return 0; + } + if (publish_uinput(w) < 0) { + Logger::log("uinput: could not publish \"%s\": %s\n", d.name, strerror(errno)); + w.created = false; + errno = ENOMEM; + return -1; + } + return 0; + // Force feedback reaches the client only as EV_UINPUT requests on this fd, and none are ever + // sent: a game's rumble on a virtual pad goes straight to the app (check_ff_event). + case _IOC_NR(UI_BEGIN_FF_UPLOAD): + case _IOC_NR(UI_END_FF_UPLOAD): + case _IOC_NR(UI_BEGIN_FF_ERASE): + case _IOC_NR(UI_END_FF_ERASE): + errno = EINVAL; + return -1; + default: + Logger::log("uinput: unhandled ioctl %d\n", number); + errno = EINVAL; + return -1; + } +} + +// Only the process that made the device takes it down: a forked child closing its inherited +// copy of the fd (as a spawn does before exec) must not remove the parent's pad. +__attribute__((visibility("hidden"))) static void close_uinput(int fd) { + std::lock_guard guard(controller_mutex()); + auto it = uinput_map().find(fd); + if (it == uinput_map().end()) return; + if (getpid() == it->second->owner) unpublish_uinput(*it->second); + uinput_map().erase(it); +} + +// ---- The pad as a Steam Deck controller ---- +// +// On a Deck, and on the handhelds InputPlumber serves, the Steam client reads the built-in +// controller itself as a Steam Deck controller: a vendor HID device it talks to over hidraw, which +// is what gives it the Quick Access button, the back grips, gyro and trackpads, and Steam Input's +// full treatment of the pad. With FAKE_EVDEV_DECK set the app's pad in ring slot 0 is presented to +// the client that way: /dev/hidraw16, found through the sysfs tree the app binds into the session +// (SteamDeckPad.kt), streams the Deck's 64-byte state report every 4 ms, as the real one does, built +// from the ring's absolute snapshot; its feature reports are answered as InputPlumber answers them +// for a virtual Deck. The evdev nodes of the app's pads are then withdrawn - the client would +// otherwise count the pad twice - and games get Steam Input's virtual pad (the /dev/uinput stand-in). +// +// A read returns one report and never blocks past the next one, so the fd is one end of a +// SOCK_SEQPACKET socket pair with a thread writing reports into the other end: poll, select and +// epoll then work on it with no help from the hooks here. +static constexpr const char *DECK_HIDRAW_PATH = "/dev/hidraw16"; +static constexpr unsigned int DECK_HIDRAW_MAJOR = 240; +static constexpr unsigned int DECK_HIDRAW_MINOR = 16; +static constexpr int DECK_REPORT_BYTES = 64; +static constexpr int DECK_REPORT_INTERVAL_US = 4000; +static constexpr const char *DECK_NAME = "Valve Software Steam Deck Controller"; +static constexpr const char *DECK_SERIAL = "DROIDDECK0001"; + +// InputPlumber, src/drivers/steam_deck/report_descriptor.rs (CONTROLLER_DESCRIPTOR): one 64-byte +// vendor input report and one 64-byte feature report, no report ids. +static const uint8_t kDeckReportDescriptor[] = { + 0x06, 0xff, 0xff, 0x09, 0x01, 0xa1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, + 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x06, 0x09, 0x07, + 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0}; + +// Feature report ids (SDL, src/joystick/hidapi/steam/controller_constants.h). +static constexpr uint8_t DECK_GET_ATTRIBUTES_VALUES = 0x83; +static constexpr uint8_t DECK_GET_STRING_ATTRIBUTE = 0xAE; +static constexpr uint8_t DECK_GET_CHIP_ID = 0xBA; +static constexpr uint8_t DECK_TRIGGER_RUMBLE_CMD = 0xEB; + +// Button bits of the state report (SDL, SDL_hidapi_steamdeck.c): the low word, then the high. +static constexpr uint32_t DECK_L_R2 = 0x00000001, DECK_L_L2 = 0x00000002, DECK_L_R1 = 0x00000004, + DECK_L_L1 = 0x00000008, DECK_L_Y = 0x00000010, DECK_L_B = 0x00000020, + DECK_L_X = 0x00000040, DECK_L_A = 0x00000080, DECK_L_UP = 0x00000100, + DECK_L_RIGHT = 0x00000200, DECK_L_LEFT = 0x00000400, + DECK_L_DOWN = 0x00000800, DECK_L_VIEW = 0x00001000, + DECK_L_STEAM = 0x00002000, DECK_L_MENU = 0x00004000, + DECK_L_L3 = 0x00400000, DECK_L_R3 = 0x04000000; +static constexpr uint32_t DECK_L_L5 = 0x00008000, DECK_L_R5 = 0x00010000, + DECK_L_LEFT_PAD = 0x00020000, DECK_L_RIGHT_PAD = 0x00040000, + DECK_L_LEFT_TOUCH = 0x00080000, DECK_L_RIGHT_TOUCH = 0x00100000; +static constexpr uint32_t DECK_H_L4 = 0x00000200, DECK_H_R4 = 0x00000400; +static constexpr uint32_t DECK_H_QAM = 0x00040000; +// Bit 11 of the ring snapshot's button word: the Quick Access button, which an Xbox pad does not +// have and the evdev nodes therefore never report (FakeInputWriter.SNAPSHOT_IDX_QAM). +static constexpr uint32_t SNAPSHOT_QAM_BIT = 1u << 11; + +struct DeckHidraw { + int peer = -1; + FakeInputRingHeader *ring = nullptr; + size_t mapping_size = 0; + uint8_t pending_feature = 0; +}; + +// What the Deck has and an Xbox pad does not, after the ring's events: motion (PadMotion) and the +// back grips and trackpads (the second screen's Deck controls, DeckControls), already in the +// Deck's axes and units, under a seqlock (FakeInputWriter.writeMotion / writeDeckControls). +// Absent from a ring file written without one. +struct DeckImu { + uint32_t magic; // IMU1 once written + uint32_t reserved; + uint64_t seq; // odd while being written + int16_t accel[3]; + int16_t gyro[3]; + int16_t pads[4]; // left X, Y, right X, Y: -32768..32767, Y up + uint16_t pressure[2]; // left, right: 0..32767 + uint32_t controls; // DECK_EXTRA_* bits +}; +// DeckImu::controls (DeckControls.kt). +static constexpr uint32_t DECK_EXTRA_L4 = 1, DECK_EXTRA_R4 = 2, DECK_EXTRA_L5 = 4, + DECK_EXTRA_R5 = 8, DECK_EXTRA_LPAD_TOUCH = 16, + DECK_EXTRA_RPAD_TOUCH = 32, DECK_EXTRA_LPAD_CLICK = 64, + DECK_EXTRA_RPAD_CLICK = 128; + +struct DeckExtras { + int16_t accel[3] = {}; + int16_t gyro[3] = {}; + int16_t pads[4] = {}; + uint16_t pressure[2] = {}; + uint32_t controls = 0; +}; +static constexpr uint32_t DECK_IMU_MAGIC = 0x31554D49; +static constexpr size_t DECK_IMU_BLOCK_SIZE = 64; +static_assert(sizeof(DeckImu) <= DECK_IMU_BLOCK_SIZE, "the IMU block is 64 bytes in the ring file"); + +__attribute__((visibility("hidden"))) static bool read_deck_extras(const DeckHidraw &deck, DeckExtras &out) { + if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return false; + const auto *imu = reinterpret_cast(reinterpret_cast(deck.ring) + + FAKE_INPUT_RING_SIZE); + for (int attempt = 0; attempt < 4; attempt++) { + uint64_t seq = __atomic_load_n(&imu->seq, __ATOMIC_ACQUIRE); + if (seq & 1) continue; + if (__atomic_load_n(&imu->magic, __ATOMIC_RELAXED) != DECK_IMU_MAGIC) return false; + DeckExtras read; + for (int i = 0; i < 3; i++) { + read.accel[i] = __atomic_load_n(&imu->accel[i], __ATOMIC_RELAXED); + read.gyro[i] = __atomic_load_n(&imu->gyro[i], __ATOMIC_RELAXED); + } + for (int i = 0; i < 4; i++) read.pads[i] = __atomic_load_n(&imu->pads[i], __ATOMIC_RELAXED); + for (int i = 0; i < 2; i++) read.pressure[i] = __atomic_load_n(&imu->pressure[i], __ATOMIC_RELAXED); + read.controls = __atomic_load_n(&imu->controls, __ATOMIC_RELAXED); + __atomic_thread_fence(__ATOMIC_ACQUIRE); + if (seq == __atomic_load_n(&imu->seq, __ATOMIC_RELAXED)) { + out = read; + return true; + } + } + return false; +} + +static std::unordered_map> &deck_map() { + static auto *map = new std::unordered_map>(); + return *map; +} + +static bool fake_deck_enabled() { + static int enabled = -1; + if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0; + return enabled == 1; +} + +// The Deck is the client's alone: a game that found it would have the pad twice, once through it +// and once through Steam Input's virtual pad. +__attribute__((visibility("hidden"))) static bool process_is_steam_client() { + static int known; + if (known == 0) { + char exe[PATH_MAX]; + ssize_t length = readlink("/proc/self/exe", exe, sizeof(exe) - 1); + bool client = false; + if (length > 0) { + exe[length] = '\0'; + const char *name = strrchr(exe, '/'); + client = !strcmp(name ? name + 1 : exe, "steam"); + } + known = client ? 1 : -1; + } + return known == 1; +} + +__attribute__((visibility("hidden"))) static bool is_deck_hidraw_path(const char *pathname) { + return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH); +} + +// The app's own pads are the Deck now; their evdev nodes are withdrawn from everyone. +__attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const char *pathname) { + if (!fake_deck_enabled() || !pathname || strncmp(pathname, "/dev/input/", 11)) return false; + const char *event = strrchr(pathname, '/') + 1; + if (strncmp(event, "event", 5) && strncmp(event, "js", 2)) return false; + int number = get_event_number(event); + return number >= 0 && number < UINPUT_EVENT_BASE; +} + +static inline void put16(uint8_t *at, int value) { + at[0] = static_cast(value & 0xff); + at[1] = static_cast((value >> 8) & 0xff); +} + +static inline void put32(uint8_t *at, uint32_t value) { + for (int i = 0; i < 4; i++) at[i] = static_cast(value >> (8 * i)); +} + +// The Deck's state report (SDL, controller_structs.h: ValveInReportHeader_t then +// SteamDeckStatePacket_t) from the ring's snapshot: kSnapshotButtons order, kSnapshotAxisCodes +// order, sticks as evdev has them (Y down), triggers 0..255. +__attribute__((visibility("hidden"))) static void +build_deck_report(uint8_t *report, uint32_t packet, uint32_t buttons, const int32_t *axes, + const DeckExtras &extras) { + memset(report, 0, DECK_REPORT_BYTES); + report[0] = 0x01; // report version + report[2] = 0x09; // ID_CONTROLLER_DECK_STATE + report[3] = DECK_REPORT_BYTES; + put32(report + 4, packet); + static const uint32_t kButtonBits[11] = {DECK_L_A, DECK_L_B, DECK_L_X, DECK_L_Y, + DECK_L_L1, DECK_L_R1, DECK_L_VIEW, DECK_L_MENU, + DECK_L_L3, DECK_L_R3, DECK_L_STEAM}; + uint32_t low = 0, high = 0; + for (int i = 0; i < 11; i++) + if (buttons & (1u << i)) low |= kButtonBits[i]; + if (buttons & SNAPSHOT_QAM_BIT) high |= DECK_H_QAM; + int32_t hat_x = axes[6], hat_y = axes[7]; + if (hat_y < 0) low |= DECK_L_UP; + if (hat_y > 0) low |= DECK_L_DOWN; + if (hat_x < 0) low |= DECK_L_LEFT; + if (hat_x > 0) low |= DECK_L_RIGHT; + int32_t left_trigger = axes[5], right_trigger = axes[4]; // ABS_BRAKE, ABS_GAS + if (left_trigger > 127) low |= DECK_L_L2; + if (right_trigger > 127) low |= DECK_L_R2; + uint32_t controls = extras.controls; + if (controls & DECK_EXTRA_L4) high |= DECK_H_L4; + if (controls & DECK_EXTRA_R4) high |= DECK_H_R4; + if (controls & DECK_EXTRA_L5) low |= DECK_L_L5; + if (controls & DECK_EXTRA_R5) low |= DECK_L_R5; + if (controls & DECK_EXTRA_LPAD_TOUCH) low |= DECK_L_LEFT_TOUCH; + if (controls & DECK_EXTRA_RPAD_TOUCH) low |= DECK_L_RIGHT_TOUCH; + if (controls & DECK_EXTRA_LPAD_CLICK) low |= DECK_L_LEFT_PAD; + if (controls & DECK_EXTRA_RPAD_CLICK) low |= DECK_L_RIGHT_PAD; + put32(report + 8, low); + put32(report + 12, high); + for (int i = 0; i < 4; i++) put16(report + 16 + i * 2, extras.pads[i]); // s{Left,Right}PadX/Y + for (int i = 0; i < 3; i++) { + put16(report + 24 + i * 2, extras.accel[i]); // sAccelX/Y/Z + put16(report + 30 + i * 2, extras.gyro[i]); // sGyroX/Y/Z + } + put16(report + 56, extras.pressure[0]); // sPressurePadLeft + put16(report + 58, extras.pressure[1]); // sPressurePadRight + put16(report + 44, std::min(32767, left_trigger * 32767 / 255)); + put16(report + 46, std::min(32767, right_trigger * 32767 / 255)); + auto stick = [](int32_t value) { return std::max(-32767, std::min(32767, value)); }; + put16(report + 48, stick(axes[0])); + put16(report + 50, stick(-axes[1])); + put16(report + 52, stick(axes[2])); + put16(report + 54, stick(-axes[3])); +} + +__attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg) { + auto *deck = static_cast *>(arg); + std::shared_ptr self = *deck; + delete deck; + uint32_t packet = 0; + SnapshotState snap; + uint32_t buttons = 0; + int32_t axes[8] = {}; + DeckExtras extras; + for (;;) { + if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) { + buttons = snap.buttons; + memcpy(axes, snap.axes, sizeof(axes)); + } + read_deck_extras(*self, extras); + uint8_t report[DECK_REPORT_BYTES]; + build_deck_report(report, ++packet, buttons, axes, extras); + // A reader that fell behind loses reports rather than getting stale ones later; a reader that + // has closed ends the stream. + if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 && + errno != EAGAIN && errno != EWOULDBLOCK) + break; + struct timespec interval = {0, DECK_REPORT_INTERVAL_US * 1000L}; + nanosleep(&interval, nullptr); + } + syscall(SYS_close, self->peer); + munmap(self->ring, self->mapping_size); + return nullptr; +} + +__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { + static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + if (!process_is_steam_client()) { + 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) { + errno = ENODEV; + return -1; + } + // The IMU block is mapped only where the file has one: past its end a mapping faults. + struct stat ring_stat; + size_t mapping_size = FAKE_INPUT_RING_SIZE; + if (fstat(ring_fd, &ring_stat) == 0 && + static_cast(ring_stat.st_size) >= FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) + mapping_size = FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE; + 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(mapping))) { + 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) { + munmap(mapping, mapping_size); + return -1; + } + // Room for a few reports only, so what the client reads is never more than a few ms old. + int buffer = DECK_REPORT_BYTES * 4; + setsockopt(pair[1], SOL_SOCKET, SO_SNDBUF, &buffer, sizeof(buffer)); + if (!(flags & O_CLOEXEC)) fcntl(pair[0], F_SETFD, 0); + if (flags & O_NONBLOCK) fcntl(pair[0], F_SETFL, fcntl(pair[0], F_GETFL) | O_NONBLOCK); + auto deck = std::make_shared(); + deck->peer = pair[1]; + deck->ring = static_cast(mapping); + deck->mapping_size = mapping_size; + { + std::lock_guard guard(controller_mutex()); + deck_map()[pair[0]] = deck; + } + pthread_t thread; + auto *arg = new std::shared_ptr(deck); + if (pthread_create(&thread, nullptr, deck_report_thread, arg) != 0) { + delete arg; + std::lock_guard guard(controller_mutex()); + deck_map().erase(pair[0]); + syscall(SYS_close, pair[0]); + syscall(SYS_close, pair[1]); + munmap(mapping, mapping_size); + errno = ENOMEM; + return -1; + } + pthread_detach(thread); + Logger::log("deck: %s opened as fd %d\n", DECK_HIDRAW_PATH, pair[0]); + return pair[0]; +} + +// libudev (systemd's sd-device) accepts a device only where its directory is on sysfs, which it +// checks with fstatfs on the directory it resolved. The Deck's sysfs is the app's own files bound +// into /sys, so those paths are said to be sysfs; nothing else is touched. +static constexpr long SYSFS_FS_MAGIC = 0x62656572; + +__attribute__((visibility("hidden"))) static bool is_deck_sysfs_path(const char *path) { + 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) { + char link[64], path[PATH_MAX]; + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); + ssize_t length = readlink(link, path, sizeof(path) - 1); + if (length <= 0) return false; + path[length] = '\0'; + return is_deck_sysfs_path(path); +} + +EXPORT int fstatfs(int fd, struct statfs *buf) { + static auto real = reinterpret_cast(dlsym(RTLD_NEXT, "fstatfs")); + int result = real(fd, buf); + 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(dlsym(RTLD_NEXT, "statfs")); + int result = real(path, buf); + if (result == 0 && fake_deck_enabled() && is_deck_sysfs_path(path)) buf->f_type = SYSFS_FS_MAGIC; + return result; +} + +#ifdef __GLIBC__ +EXPORT int fstatfs64(int fd, struct statfs64 *buf) { + return fstatfs(fd, reinterpret_cast(buf)); +} + +EXPORT int statfs64(const char *path, struct statfs64 *buf) { + return statfs(path, reinterpret_cast(buf)); +} +#endif + +__attribute__((visibility("hidden"))) static int copy_ioctl_string(ioctl_request_t op, void *argp, const char *value) { + size_t size = _IOC_SIZE(op); + if (!argp || !size) return 0; + snprintf(static_cast(argp), size, "%s", value); + return static_cast(std::min(size, strlen(value) + 1)); +} + +// Feature reports carry the report id (0) first, then the Valve message: type, length, payload. +__attribute__((visibility("hidden"))) static int +deck_feature(DeckHidraw &deck, ioctl_request_t op, uint8_t *buf, bool set) { + size_t size = _IOC_SIZE(op); + if (!buf || size < 2) { + errno = EINVAL; + return -1; + } + if (set) { + deck.pending_feature = buf[1]; + if (buf[1] == DECK_TRIGGER_RUMBLE_CMD && size >= 10) { + int left = buf[6] | buf[7] << 8, right = buf[8] | buf[9] << 8; + send_vibration(left, right, left || right ? 1000 : 0, 0); + } + Logger::log("deck: feature 0x%02x set\n", buf[1]); + return static_cast(size); + } + uint8_t reply[DECK_REPORT_BYTES + 1] = {}; + switch (deck.pending_feature) { + case DECK_GET_ATTRIBUTES_VALUES: { + // InputPlumber's capture from a real Deck (steam_deck_uhid.rs, handle_get_report). + static const uint8_t kAttributes[] = {0x00, 0x83, 0x2d, 0x01, 0x05, 0x12, 0x00, 0x00, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x0a, 0x2b, 0x12, 0xa9, 0x62, + 0x04, 0xad, 0xf1, 0xe4, 0x65, 0x09, 0x2e, 0x00, 0x00, + 0x00, 0x0b, 0xa0, 0x0f, 0x00, 0x00, 0x0d, 0x00, 0x00, + 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x0e}; + memcpy(reply, kAttributes, sizeof(kAttributes)); + break; + } + case DECK_GET_STRING_ATTRIBUTE: + reply[1] = DECK_GET_STRING_ATTRIBUTE; + reply[2] = 0x14; + reply[3] = 0x01; + memcpy(reply + 4, DECK_SERIAL, strlen(DECK_SERIAL)); + break; + case DECK_GET_CHIP_ID: + reply[1] = DECK_GET_CHIP_ID; + reply[2] = 0x11; + memcpy(reply + 4, "DROIDDECKCHIP01", 15); + break; + default: + reply[1] = deck.pending_feature; + break; + } + 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(length); +} + +__attribute__((visibility("hidden"))) static int +ioctl_deck(DeckHidraw &deck, ioctl_request_t op, void *argp) { + if (_IOC_TYPE(op) != 'H') { + errno = ENOTTY; + return -1; + } + switch (_IOC_NR(op)) { + case 0x01: // HIDIOCGRDESCSIZE + *static_cast(argp) = sizeof(kDeckReportDescriptor); + return 0; + case 0x02: { // HIDIOCGRDESC: struct hidraw_report_descriptor { __u32 size; __u8 value[4096]; } + auto *descriptor = static_cast(argp); + uint32_t size; + memcpy(&size, descriptor, sizeof(size)); + memcpy(descriptor + 4, kDeckReportDescriptor, std::min(size, sizeof(kDeckReportDescriptor))); + return 0; + } + case 0x03: { // HIDIOCGRAWINFO: struct hidraw_devinfo { __u32 bustype; __s16 vendor, product; } + struct { + uint32_t bustype; + int16_t vendor; + int16_t product; + } info = {BUS_USB, static_cast(0x28de), static_cast(0x1205)}; + memcpy(argp, &info, sizeof(info)); + return 0; + } + case 0x04: return copy_ioctl_string(op, argp, DECK_NAME); // HIDIOCGRAWNAME + case 0x05: return copy_ioctl_string(op, argp, "usb-droiddeck-1/input2"); // HIDIOCGRAWPHYS + case 0x08: return copy_ioctl_string(op, argp, DECK_SERIAL); // HIDIOCGRAWUNIQ + case 0x06: return deck_feature(deck, op, static_cast(argp), true); // HIDIOCSFEATURE + case 0x07: return deck_feature(deck, op, static_cast(argp), false); // HIDIOCGFEATURE + default: + Logger::log("deck: unhandled hidraw ioctl 0x%02x\n", _IOC_NR(op)); + errno = EINVAL; + return -1; + } +} + EXPORT int open(const char *pathname, int flags, ...) { va_list va; mode_t mode; @@ -725,6 +1576,13 @@ EXPORT int open(const char *pathname, int flags, ...) { static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags); + if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags); + if (is_withdrawn_pad_path(pathname)) { + errno = ENOENT; + return -1; + } + char *fake_path = nullptr; const char *event = nullptr; if (pathname) { @@ -788,6 +1646,13 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) { static auto my_openat = reinterpret_cast(dlsym(RTLD_NEXT, "openat")); + if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags); + if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags); + if (is_withdrawn_pad_path(pathname)) { + errno = ENOENT; + return -1; + } + char *fake_path = nullptr; const char *event = nullptr; if (pathname) { @@ -836,6 +1701,17 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) { EXPORT int stat(const char *pathname, struct stat *statbuf) { static auto my_stat = reinterpret_cast(dlsym(RTLD_NEXT, "stat")); + if (is_withdrawn_pad_path(pathname) || (is_deck_hidraw_path(pathname) && !process_is_steam_client())) { + errno = ENOENT; + return -1; + } + if (is_deck_hidraw_path(pathname)) { + memset(statbuf, 0, sizeof(*statbuf)); + statbuf->st_mode = S_IFCHR | 0666; + statbuf->st_rdev = makedev(DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR); + return 0; + } + const char *event = nullptr; char *fake_path = nullptr; @@ -879,6 +1755,11 @@ EXPORT int fstat(int fd, struct stat *buf) { int ret = my_fstat(fd, buf); std::lock_guard guard(controller_mutex()); + if (ret == 0 && deck_map().count(fd)) { + buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFCHR; + buf->st_rdev = makedev(DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR); + return ret; + } auto controller = controller_map().find(fd); if (ret == 0 && controller != controller_map().end()) { buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFCHR; @@ -890,6 +1771,12 @@ EXPORT int fstat(int fd, struct stat *buf) { EXPORT int access(const char *pathname, int mode) { static auto my_access = reinterpret_cast(dlsym(RTLD_NEXT, "access")); + if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0; + if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0; + if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) { + errno = ENOENT; + return -1; + } char *fake_path = nullptr; if (pathname) { @@ -920,6 +1807,12 @@ EXPORT int access(const char *pathname, int mode) { EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) { static auto my_faccessat = reinterpret_cast(dlsym(RTLD_NEXT, "faccessat")); + if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0; + if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0; + if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) { + errno = ENOENT; + return -1; + } char *fake_path = nullptr; if (pathname) { @@ -1034,6 +1927,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { // blocking ioctl(BINDER_WRITE_READ), so a parked binder pool thread would own // controller_mutex() for as long as it waits and deadlock every other ioctl. std::unique_lock guard(controller_mutex()); + auto maker = uinput_map().find(fd); + if (maker != uinput_map().end()) return ioctl_uinput(*maker->second, op, argp); + auto deck = deck_map().find(fd); + if (deck != deck_map().end()) return ioctl_deck(*deck->second, op, argp); auto controller = controller_map().find(fd); if (controller == controller_map().end()) { guard.unlock(); @@ -1044,6 +1941,8 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { int number = (op >> 0 & 0xFF); const char *event = controller->second->event ? controller->second->event : "event0"; int event_number = controller->second->slot; + // A virtual pad answers with what its maker described, not with the app's pad identity. + const UinputDescription *made = controller->second->uinput; if (type == 0x45 && number == 0x1) { Logger::log("Hooking ioctl EVIOCGVERSION for event %s\n", event); @@ -1055,7 +1954,9 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { struct input_id id; memset(&id, 0, sizeof(id)); id.bustype = 0x03; - if (presents_steam_virtual()) { + if (made) { + id = made->id; + } else if (presents_steam_virtual()) { id.vendor = STEAM_VIRTUAL_VENDOR_ID; id.product = STEAM_VIRTUAL_PRODUCT_ID; } else if (fake_xbox360_identity()) { @@ -1065,11 +1966,15 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { id.vendor = static_cast(GAMEPAD_VENDOR_ID_BASE + event_number); id.product = static_cast(GAMEPAD_PRODUCT_ID_BASE + event_number); } - id.version = GAMEPAD_VERSION; + if (!made) id.version = GAMEPAD_VERSION; memcpy(argp, (void *)&id, sizeof(id)); return 0; } else if (type == 0x45 && number == 0x6) { Logger::log("Hooking ioctl EVIOCGNAME for event %s\n", event); + if (made) { + if (argp && _IOC_SIZE(op)) snprintf(static_cast(argp), _IOC_SIZE(op), "%s", made->name); + return 0; + } copy_slot_ioctl_string(op, argp, presents_steam_virtual() ? STEAM_VIRTUAL_NAME_TEMPLATE : (fake_xbox360_identity() ? X360_NAME_TEMPLATE : GAMEPAD_NAME_TEMPLATE), @@ -1077,10 +1982,18 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { return 0; } else if (type == 0x45 && number == 0x7) { Logger::log("Hooking ioctl EVIOCGPHYS for event %s\n", event); + if (made) { + if (argp && _IOC_SIZE(op)) snprintf(static_cast(argp), _IOC_SIZE(op), "%s", made->phys); + return 0; + } copy_slot_ioctl_string(op, argp, GAMEPAD_PHYS_TEMPLATE, event_number); return 0; } else if (type == 0x45 && number == 0x8) { Logger::log("Hooking ioctl EVIOCGUNIQ for event %s\n", event); + if (made) { + if (argp && _IOC_SIZE(op)) static_cast(argp)[0] = '\0'; + return 0; + } copy_slot_ioctl_string(op, argp, GAMEPAD_UNIQ_TEMPLATE, event_number); return 0; } else if (type == 0x45 && number == 0x9) { @@ -1097,6 +2010,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { return copy_ioctl_bits(op, argp, bitmask); } else if (type == 0x45 && number == 0x20) { Logger::log("Hooking ioctl EVIOCGBIT(0, len) for event %s\n", event); + if (made) return copy_ioctl_bits(op, argp, made->evbits); unsigned char bitmask[(EV_MAX + 8) / 8] = {}; bitmask[EV_SYN / 8] |= (1 << (EV_SYN % 8)); bitmask[EV_KEY / 8] |= (1 << (EV_KEY % 8)); @@ -1104,6 +2018,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { return copy_ioctl_bits(op, argp, bitmask); } else if (type == 0x45 && number == 0x21) { Logger::log("Hooking ioctl EVIOCGBIT(EV_KEY, len) for event %s\n", event); + if (made) return copy_ioctl_bits(op, argp, made->keybits); unsigned char bitmask[(KEY_MAX + 8) / 8] = {}; const int xbox_buttons[] = {BTN_A, BTN_B, BTN_X, BTN_Y, BTN_TL, BTN_TR, BTN_SELECT, BTN_START, @@ -1117,13 +2032,14 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { return copy_ioctl_bits(op, argp, bitmask); } else if (type == 0x45 && number == 0x23) { Logger::log("Hooking ioctl EVIOCGBIT(EV_ABS, len) for event %s\n", event); + if (made) return copy_ioctl_bits(op, argp, made->absbits); unsigned char bitmask[(ABS_MAX + 8) / 8] = {}; bitmask[ABS_X / 8] |= (1 << (ABS_X % 8)); bitmask[ABS_Y / 8] |= (1 << (ABS_Y % 8)); bitmask[ABS_RX / 8] |= (1 << (ABS_RX % 8)); bitmask[ABS_RY / 8] |= (1 << (ABS_RY % 8)); for (uint16_t trigger : {ABS_GAS, ABS_BRAKE}) { - uint16_t code = presented_abs_code(trigger); + uint16_t code = presented_abs_code(*controller->second, trigger); bitmask[code / 8] |= (1 << (code % 8)); } bitmask[ABS_HAT0X / 8] |= (1 << (ABS_HAT0X % 8)); @@ -1131,6 +2047,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { return copy_ioctl_bits(op, argp, bitmask); } else if (type == 0x45 && number == 0x35) { Logger::log("Hooking ioctl EVIOCGBIT(EV_FF, len) for event %s\n", event); + if (made) return copy_ioctl_bits(op, argp, made->ffbits); unsigned char bitmask[(FF_MAX + 8) / 8] = {}; bitmask[FF_RUMBLE / 8] |= (1 << (FF_RUMBLE % 8)); bitmask[FF_PERIODIC / 8] |= (1 << (FF_PERIODIC % 8)); @@ -1163,8 +2080,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { Logger::log("Hooking ioctl EVIOCGABS(ABS) for event %s\n", event); struct input_absinfo abs_info; memset(&abs_info, 0, sizeof(abs_info)); - uint16_t code = ring_abs_code(number - 0x40); - if (code == ABS_GAS || code == ABS_BRAKE) { + uint16_t code = ring_abs_code(*controller->second, number - 0x40); + if (made) { + abs_info = made->absinfo[number - 0x40]; + } else if (code == ABS_GAS || code == ABS_BRAKE) { abs_info.value = 0; abs_info.minimum = 0; abs_info.maximum = 255; @@ -1218,7 +2137,9 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { EXPORT int close(int fd) { static auto my_close = reinterpret_cast(dlsym(RTLD_NEXT, "close")); + close_uinput(fd); std::unique_lock guard(controller_mutex()); + deck_map().erase(fd); auto controller = controller_map().find(fd); if (controller != controller_map().end()) { Logger::log("Removing controller, fd %d event %s\n", controller->first, @@ -1283,7 +2204,7 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { size_t index = (fake.read_seq + i) % FAKE_INPUT_RING_CAPACITY; struct input_event ev; memcpy(&ev, ring_events + index * FAKE_INPUT_EVENT_SIZE, FAKE_INPUT_EVENT_SIZE); - if (ev.type == EV_ABS) ev.code = presented_abs_code(ev.code); + if (ev.type == EV_ABS) ev.code = presented_abs_code(fake, ev.code); memcpy(static_cast(buf) + i * FAKE_INPUT_EVENT_SIZE, &ev, FAKE_INPUT_EVENT_SIZE); } @@ -1309,7 +2230,7 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { ev.type = kNeutralEvents[index].type; ev.code = kNeutralEvents[index].code; ev.value = keyframe_value(fake, ev.type, ev.code); - if (ev.type == EV_ABS) ev.code = presented_abs_code(ev.code); + if (ev.type == EV_ABS) ev.code = presented_abs_code(fake, ev.code); memcpy(static_cast(buf) + i * FAKE_INPUT_EVENT_SIZE, &ev, FAKE_INPUT_EVENT_SIZE); --fake.keyframe_remaining; @@ -1333,6 +2254,9 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) { static auto my_write = reinterpret_cast(dlsym(RTLD_NEXT, "write")); std::unique_lock guard(controller_mutex()); + auto made = uinput_map().find(fd); + if (made != uinput_map().end()) return write_uinput(*made->second, buf, count); + if (deck_map().count(fd)) return static_cast(count); auto controller = controller_map().find(fd); if (controller != controller_map().end()) { if (fake_fd_is_stale(fd)) { @@ -1355,6 +2279,22 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) { EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) { std::unique_lock guard(controller_mutex()); + if (deck_map().count(fd)) { + ssize_t total = 0; + for (int i = 0; i < iovcnt; i++) total += static_cast(iov[i].iov_len); + return total; + } + auto made = uinput_map().find(fd); + if (made != uinput_map().end()) { + // One description or whole events per vector, which is how uinput writers write. + ssize_t total = 0; + for (int i = 0; i < iovcnt; i++) { + ssize_t written = write_uinput(*made->second, iov[i].iov_base, iov[i].iov_len); + if (written < 0) return total ? total : -1; + total += written; + } + return total; + } auto controller = controller_map().find(fd); if (controller != controller_map().end()) { if (fake_fd_is_stale(fd)) { diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_alpha.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_alpha.cpp index 73be35b59..04a37b720 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_alpha.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_alpha.cpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_alpha.hpp" #include "lsfg_shaders.hpp" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_alpha.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_alpha.hpp index 6c233c16c..9a4e15ddf 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_alpha.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_alpha.hpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_beta.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_beta.cpp index 299e22cf7..d9413e647 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_beta.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_beta.cpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_beta.hpp" #include "lsfg_shaders.hpp" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_beta.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_beta.hpp index 1d1e77a56..7d259f9e2 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_beta.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_beta.hpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_chain.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_chain.cpp index f9ff4b4f8..54acb1a0f 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_chain.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_chain.cpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_chain.hpp" #include "lsfg_shaders.hpp" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_chain.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_chain.hpp index 4324c80bc..4bab527fd 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_chain.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_chain.hpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_common.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_common.cpp index b72eb2287..c93275486 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_common.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_common.cpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_common.hpp" #include "lsfg_shaders.hpp" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_common.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_common.hpp index 1f6b20983..c5ab3e0ad 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_common.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_common.hpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_delta.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_delta.cpp index ddba102d5..cf9b31bfa 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_delta.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_delta.cpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_delta.hpp" #include "lsfg_shaders.hpp" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_delta.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_delta.hpp index 8d8232675..e40ffe7bd 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_delta.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_delta.hpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_dll.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_dll.cpp index 78ddbccc7..0af479be8 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_dll.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_dll.cpp @@ -1,9 +1,9 @@ // See lsfg_dll.h. PE resource walk + on-device SPIR-V cache for the Lossless // Scaling frame-generation chain. // -// Derived from WinNative's lsfg_dll.c (GPL-3.0-or-later), LSFG port credited to -// Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk -// (PancakeTAS). Bannerlator is GPL-3.0. +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk (PancakeTAS). Ported to WinNative (lsfg_dll.c) and DroidDeck +// by @maxjivi05. GPL-3.0-or-later. #include "lsfg_dll.h" #include "lsfg_dxbc.h" @@ -478,20 +478,6 @@ DllStatus validateDll(const std::string& dllPath) { return status; } -Variant dllVariant(const std::string& dllPath, bool preferFp16) { - if (dllPath.empty()) return Variant::None; - - PeImage img; - if (!img.open(dllPath)) return Variant::None; - - ResourceTable table; - if (parseResources(img, table) != DllStatus::Ok) return Variant::None; - - Variant v = selectVariant(table, preferFp16); - if (v == Variant::None && hasBaseChain(table)) v = Variant::DxbcTranslated; - return v; -} - DllStatus buildCache(const std::string& dllPath, const std::string& cachePath, bool preferFp16) { if (dllPath.empty() || cachePath.empty()) return DllStatus::NotInstalled; @@ -547,22 +533,6 @@ DllStatus buildCache(const std::string& dllPath, const std::string& cachePath, b return DllStatus::Ok; } -DllStatus cacheMatchesSource(const std::string& cachePath, const std::string& dllPath, - bool& outMatches) { - outMatches = false; - if (cachePath.empty() || dllPath.empty()) return DllStatus::CacheUnusable; - - CacheHeader header{}; - if (!readCacheHeader(cachePath, header)) return DllStatus::CacheUnusable; - - PeImage img; - if (!img.open(dllPath)) return DllStatus::NotInstalled; - - outMatches = header.sourceSize == (uint64_t)img.size() - && header.sourceHash == fnv1a64(img.data(), img.size()); - return DllStatus::Ok; -} - DllStatus cacheVariant(const std::string& cachePath, Variant& outVariant) { outVariant = Variant::None; CacheHeader header{}; diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_dll.h b/app/src/main/cpp/framegen/lsfg/lsfg_dll.h index 72a862b58..74d6ca83d 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_dll.h +++ b/app/src/main/cpp/framegen/lsfg/lsfg_dll.h @@ -7,7 +7,7 @@ // ship as RCDATA resources inside Lossless.dll from the user's own paid copy // of Lossless Scaling (Steam app 993090). Every implementation - upstream // lsfg-vk, LSFG-Android, eden, WinNative - requires the user to supply their -// own DLL and extracts the resources on device. Bannerlator does the same, and +// own DLL and extracts the resources on device. DroidDeck does the same, and // bundles nothing. // // The DLL is mmap'd READ-ONLY and parsed as data. It is never loaded as a @@ -26,9 +26,9 @@ // Both producers fill the same shader-id -> SPIR-V words map, so everything // downstream of this file is source-agnostic. // -// Derived from WinNative's lsfg_dll.c (GPL-3.0-or-later), whose LSFG port is -// credited to Camille LaVey / the Eden Emulator Project, and which follows -// upstream lsfg-vk (PancakeTAS). Bannerlator is GPL-3.0; see THIRD-PARTY-LICENSES.md. +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk (PancakeTAS). Ported to WinNative (lsfg_dll.c) and DroidDeck +// by @maxjivi05. GPL-3.0-or-later. // ============================================================================ #include @@ -98,18 +98,11 @@ const char* variantName(Variant v); // reported as valid - the translator handles it. DllStatus validateDll(const std::string& dllPath); -// Which producer would be used for this DLL. -Variant dllVariant(const std::string& dllPath, bool preferFp16); - // Parse the DLL, produce all 25 SPIR-V modules, and write them to cachePath // (via temp file + rename, so a failed build cannot leave a half-written // cache behind). Records which producer ran in the cache header. DllStatus buildCache(const std::string& dllPath, const std::string& cachePath, bool preferFp16); -// Is the cache current for this DLL? Compares source size + content hash. -DllStatus cacheMatchesSource(const std::string& cachePath, const std::string& dllPath, - bool& outMatches); - // Load a previously built cache. DllStatus loadModules(const std::string& cachePath, ModuleSet& outSet); diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_dxbc.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_dxbc.cpp index db23e3686..c8084119f 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_dxbc.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_dxbc.cpp @@ -1,9 +1,10 @@ // See lsfg_dxbc.h. DXBC -> SPIR-V via DXVK's vendored translator. // // Follows upstream lsfg-vk's src/extract/trans.cpp, including its -// encounter-order binding renumber. Derived from WinNative's lsfg_dxbc.cpp -// (GPL-3.0-or-later); the translator itself is DXVK's, zlib licensed, vendored -// under cpp/thirdparty/dxbc. +// encounter-order binding renumber. Ported to WinNative (lsfg_dxbc.cpp) and +// DroidDeck by @maxjivi05 from the work of Camille LaVey / the Eden Emulator +// Project (GPL-3.0-or-later); the translator itself is DXVK's, zlib licensed, +// vendored under cpp/thirdparty/dxbc. #include "lsfg_dxbc.h" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_engine.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_engine.cpp index 4f1482eb7..ba9e8a021 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_engine.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_engine.cpp @@ -1,7 +1,8 @@ // See lsfg_engine.h. // -// Ported from WinNative's vkr_lsfg.cpp (GPL-3.0-or-later), LSFG port credited -// to Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk. +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative (vkr_lsfg.cpp) and DroidDeck by +// @maxjivi05, where it runs on gamescope's output in the compositor. #include "lsfg_engine.h" @@ -269,7 +270,7 @@ void Engine::process(VkCommandBuffer cmd, VkImage source, uint32_t width, uint32 // nothing. Copy only when generating, on the one priming frame that // precedes generation, or while the governor is warming up towards a // probe - so the ring is populated by the time it is needed. - const bool needHistory = generations > 0 || primeHistory_ + const bool needHistory = generations > 0 || primeHistory_ || followEveryFrame() || (governorEnabled_ && governor_.wantsHistory()); if (needHistory) { copyPresentedFrame(cmd, source, chain_->Input(count), VkExtent2D{width, height}); @@ -284,7 +285,7 @@ void Engine::process(VkCommandBuffer cmd, VkImage source, uint32_t width, uint32 // regardless of the game's own settings, and it fed straight back into the // governor: the chain made the source rate collapse, the governor saw the // collapse and refused to generate, and refusing did not stop the chain. - if (warm_ && generations > 0) chain_->DispatchShared(cmd, count); + if (warm_ && (generations > 0 || followEveryFrame())) chain_->DispatchShared(cmd, count); } void Engine::generateInto(VkCommandBuffer cmd, uint32_t generation, uint32_t targetIndex, diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_engine.h b/app/src/main/cpp/framegen/lsfg/lsfg_engine.h index 20489e652..c8a5028d0 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_engine.h +++ b/app/src/main/cpp/framegen/lsfg/lsfg_engine.h @@ -16,8 +16,9 @@ // unavoidable cost of interpolating rather than extrapolating; no placement of // this code changes it. // -// Ported from WinNative's vkr_lsfg.cpp (GPL-3.0-or-later), LSFG port credited -// to Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk. +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative (vkr_lsfg.cpp) and DroidDeck by +// @maxjivi05, where it runs on gamescope's output in the compositor. // ============================================================================ #include @@ -109,6 +110,10 @@ private: // generation last stopped. bool historyFresh() const { return haveCopied_ && lastCopiedCount_ + 1 == frameCount_; } + // With a target rate the pacer plans 0..3 generations frame by frame, so the ring and the + // shared chain have to follow every frame it keeps warm, not just the ones that generate. + bool followEveryFrame() const { return warm_ && pacer_.Config().target_rate != 0; } + Device device_{}; std::string cachePath_; std::unique_ptr shaders_; diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_gamma.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_gamma.cpp index 392930b61..574382ed7 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_gamma.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_gamma.cpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_gamma.hpp" #include "lsfg_shaders.hpp" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_gamma.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_gamma.hpp index 8210dd259..d1cd38486 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_gamma.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_gamma.hpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_generate.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_generate.cpp index 1c84cb186..7be96561c 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_generate.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_generate.cpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_generate.hpp" #include "lsfg_dll.h" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_generate.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_generate.hpp index 68e23967b..0612b7422 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_generate.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_generate.hpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_jni.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_jni.cpp index ba8447313..ab13096d6 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_jni.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_jni.cpp @@ -27,12 +27,6 @@ Java_com_droiddeck_launcher_gpu_LsfgNative_nativeValidateDll(JNIEnv* env, jclass return (jint)lsfg::validateDll(toStdString(env, dllPath)); } -extern "C" JNIEXPORT jint JNICALL -Java_com_droiddeck_launcher_gpu_LsfgNative_nativeDllVariant(JNIEnv* env, jclass, jstring dllPath, - jboolean preferFp16) { - return (jint)lsfg::dllVariant(toStdString(env, dllPath), preferFp16 == JNI_TRUE); -} - extern "C" JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_gpu_LsfgNative_nativeBuildCache(JNIEnv* env, jclass, jstring dllPath, jstring cachePath, jboolean preferFp16) { @@ -40,16 +34,6 @@ Java_com_droiddeck_launcher_gpu_LsfgNative_nativeBuildCache(JNIEnv* env, jclass, preferFp16 == JNI_TRUE); } -extern "C" JNIEXPORT jboolean JNICALL -Java_com_droiddeck_launcher_gpu_LsfgNative_nativeCacheMatchesSource(JNIEnv* env, jclass, - jstring cachePath, - jstring dllPath) { - bool matches = false; - const lsfg::DllStatus status = lsfg::cacheMatchesSource(toStdString(env, cachePath), - toStdString(env, dllPath), matches); - return (jboolean)(status == lsfg::DllStatus::Ok && matches); -} - extern "C" JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_gpu_LsfgNative_nativeCacheVariant(JNIEnv* env, jclass, jstring cachePath) { lsfg::Variant variant = lsfg::Variant::None; diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_mipmaps.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_mipmaps.cpp index 4d1762555..ef1e11318 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_mipmaps.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_mipmaps.cpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_mipmaps.hpp" #include "lsfg_dll.h" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_mipmaps.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_mipmaps.hpp index 4ce06b0f5..d301c26ef 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_mipmaps.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_mipmaps.hpp @@ -4,10 +4,9 @@ // SPDX-FileCopyrightText: Copyright 2025 lsfg-vk // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_pacer.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_pacer.cpp index 29da8729d..8ddf453c2 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_pacer.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_pacer.cpp @@ -1,10 +1,9 @@ // SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_pacer.hpp" @@ -22,6 +21,8 @@ constexpr float SOURCE_SMOOTHING = 0.15f; constexpr float SOURCE_STALE_SECONDS = 0.5f; constexpr float DISCONTINUITY_SECONDS = 0.25f; constexpr float HEADROOM_EPSILON = 0.02f; +// A target is aimed just under, so rounding never puts output past the panel's refresh rate. +constexpr float TARGET_MARGIN = 0.1f; constexpr float CREDIT_EPSILON = 1.0e-4f; constexpr float SOURCE_ACCUM_FLOOR = 0.01f; constexpr uint32_t MIN_RATE_SAMPLES = 12; @@ -117,6 +118,7 @@ LsfgPlan LsfgPacer::Plan(size_t capacity, uint64_t source_frames) { if (target_rate > 0.0f && config.refresh_rate > 0.0f) { target_rate = std::min(target_rate, config.refresh_rate); } + if (target_rate > 0.0f) target_rate -= TARGET_MARGIN; if (target_rate == 0.0f) { // No explicit target rate: the multiplier is the multiplier, full stop. diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_pacer.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_pacer.hpp index 5613c4c30..fe4a43ee5 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_pacer.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_pacer.hpp @@ -1,10 +1,9 @@ // SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_shaders.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_shaders.cpp index 96fb7bfdc..d3266d173 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_shaders.cpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_shaders.cpp @@ -1,10 +1,9 @@ // SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #include "lsfg_shaders.hpp" #include "lsfg_common.hpp" diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_shaders.hpp b/app/src/main/cpp/framegen/lsfg/lsfg_shaders.hpp index ba7854da4..d91b00c18 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_shaders.hpp +++ b/app/src/main/cpp/framegen/lsfg/lsfg_shaders.hpp @@ -1,10 +1,9 @@ // SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-License-Identifier: GPL-3.0-or-later // -// Ported into Bannerlator's compositor from WinNative (GPL-3.0-or-later), -// whose LSFG port is credited to Camille LaVey / the Eden Emulator Project and -// follows upstream lsfg-vk. Only the Vulkan dispatch differs: Bannerlator -// resolves entry points through the renderer's own table (see lsfg_vkd.h). +// LSFG from the work of Camille LaVey / the Eden Emulator Project, following +// upstream lsfg-vk. Ported to WinNative and DroidDeck by @maxjivi05; only the +// Vulkan dispatch differs here (see lsfg_vkd.h). #pragma once diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_vkd.h b/app/src/main/cpp/framegen/lsfg/lsfg_vkd.h index 0657ac975..c86d2224f 100644 --- a/app/src/main/cpp/framegen/lsfg/lsfg_vkd.h +++ b/app/src/main/cpp/framegen/lsfg/lsfg_vkd.h @@ -2,10 +2,10 @@ // ============================================================================ // lsfg_vkd - the Vulkan entry points the LSFG chain calls, as a single global. // -// Two dispatch styles meet here. Bannerlator's compositor resolves Vulkan +// Two dispatch styles meet here. DroidDeck's compositor resolves Vulkan // through a per-context VkTable (`vk_`), because an adrenotools-loaded driver // lives in an isolated linker namespace and shares no global symbols with the -// system loader. The LSFG chain, ported from eden by way of WinNative, calls +// system loader. The LSFG chain, ported from Eden by way of WinNative, calls // through a file-scope `vkd`. Rather than rewrite ~2,300 lines of proven chain // code to thread a table through every call, this shim exposes exactly the 34 // entry points the chain uses and is filled from the renderer's own table when diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index 5f6733571..d942fd686 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -19,6 +19,7 @@ add_library(bannerwayland SHARED src/wl_toplevel_icon.c src/wl_color_mgmt.c src/hdr_compose.c + src/blend_pass.c generated/color-management-v1-protocol.c generated/xdg-shell-protocol.c generated/linux-dmabuf-v1-protocol.c diff --git a/app/src/main/cpp/waylandcomp/src/blend.frag b/app/src/main/cpp/waylandcomp/src/blend.frag new file mode 100644 index 000000000..88739de25 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/blend.frag @@ -0,0 +1,9 @@ +#version 450 +// Wayland buffers carry premultiplied alpha; the pipeline blends ONE, ONE_MINUS_SRC_ALPHA. +layout(binding = 0) uniform sampler2D Surface; +layout(location = 0) in vec2 uv; +layout(location = 0) out vec4 outColor; + +void main() { + outColor = texture(Surface, uv); +} diff --git a/app/src/main/cpp/waylandcomp/src/blend.vert b/app/src/main/cpp/waylandcomp/src/blend.vert new file mode 100644 index 000000000..5c87cc352 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/blend.vert @@ -0,0 +1,10 @@ +#version 450 +// One surface as a quad: dst = the target rectangle in NDC, src = the buffer rectangle in UV. +layout(push_constant) uniform PC { vec4 dst; vec4 src; } pc; +layout(location = 0) out vec2 uv; + +void main() { + vec2 t = vec2(gl_VertexIndex & 1, gl_VertexIndex >> 1); + gl_Position = vec4(mix(pc.dst.xy, pc.dst.zw, t), 0.0, 1.0); + uv = mix(pc.src.xy, pc.src.zw, t); +} diff --git a/app/src/main/cpp/waylandcomp/src/blend_frag.h b/app/src/main/cpp/waylandcomp/src/blend_frag.h new file mode 100644 index 000000000..9d2af54a3 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/blend_frag.h @@ -0,0 +1,22 @@ + // 1115.1.0 + #pragma once +const uint32_t blend_frag_code[] = { + 0x07230203,0x00010000,0x0008000b,0x00000014,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, + 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x00000011,0x00030010, + 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, + 0x00000000,0x00050005,0x00000009,0x4374756f,0x726f6c6f,0x00000000,0x00040005,0x0000000d, + 0x66727553,0x00656361,0x00030005,0x00000011,0x00007675,0x00040047,0x00000009,0x0000001e, + 0x00000000,0x00040047,0x0000000d,0x00000021,0x00000000,0x00040047,0x0000000d,0x00000022, + 0x00000000,0x00040047,0x00000011,0x0000001e,0x00000000,0x00020013,0x00000002,0x00030021, + 0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006, + 0x00000004,0x00040020,0x00000008,0x00000003,0x00000007,0x0004003b,0x00000008,0x00000009, + 0x00000003,0x00090019,0x0000000a,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000, + 0x00000001,0x00000000,0x0003001b,0x0000000b,0x0000000a,0x00040020,0x0000000c,0x00000000, + 0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000000,0x00040017,0x0000000f,0x00000006, + 0x00000002,0x00040020,0x00000010,0x00000001,0x0000000f,0x0004003b,0x00000010,0x00000011, + 0x00000001,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005, + 0x0004003d,0x0000000b,0x0000000e,0x0000000d,0x0004003d,0x0000000f,0x00000012,0x00000011, + 0x00050057,0x00000007,0x00000013,0x0000000e,0x00000012,0x0003003e,0x00000009,0x00000013, + 0x000100fd,0x00010038 +}; diff --git a/app/src/main/cpp/waylandcomp/src/blend_pass.c b/app/src/main/cpp/waylandcomp/src/blend_pass.c new file mode 100644 index 000000000..471eedc9a --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/blend_pass.c @@ -0,0 +1,315 @@ +/* Alpha composition: one surface drawn source-over onto the scene - see blend_pass.h. Compositor thread. */ +#define _POSIX_C_SOURCE 200809L +#include "blend_pass.h" +#include "vk_loader.h" +#include "vk_present.h" /* banner_log, vkp_gpu_name */ +#include + +/* SPIR-V, pre-compiled (glslangValidator -V blend.vert --vn blend_vert_code, the same for blend.frag) + * and committed next to the GLSL: the NDK build compiles no shaders. */ +#include "blend_vert.h" +#include "blend_frag.h" + +struct pc_blend { float dst[4]; float src[4]; }; + +static VkDevice g_dev; +static int g_ready; /* 0 = not built, 1 = ok, -1 = unavailable (said once) */ +static VkSampler g_sampler; +static VkDescriptorSetLayout g_dsl; +static VkPipelineLayout g_pl; +static VkDescriptorPool g_dpool; +static VkShaderModule g_vert, g_frag; +static unsigned g_frame = 1; + +/* One render pass + pipeline per target format: the screen swapchain's, the scene image's, the HDR + * composition's. */ +#define NFMT 4 +static struct { VkFormat fmt; VkRenderPass rp; VkPipeline pipe; } g_out[NFMT]; + +#define NSRC 32 +static struct { VkImage img; VkImageView view; VkDescriptorSet ds; unsigned frame; } g_src[NSRC]; +#define NDST 12 +static struct { VkImage img; VkFormat fmt; int w, h; VkImageView view; VkFramebuffer fb; unsigned frame; } g_dst[NDST]; + +void blendp_bind_device(VkDevice dev) { g_dev = dev; } + +void blendp_begin_frame(void) { g_frame++; } + +static void src_release(int i) { + if (g_src[i].ds) g_vk.FreeDescriptorSets(g_dev, g_dpool, 1, &g_src[i].ds); + if (g_src[i].view) g_vk.DestroyImageView(g_dev, g_src[i].view, NULL); + memset(&g_src[i], 0, sizeof(g_src[i])); +} + +static void dst_release(int i) { + if (g_dst[i].fb) g_vk.DestroyFramebuffer(g_dev, g_dst[i].fb, NULL); + if (g_dst[i].view) g_vk.DestroyImageView(g_dev, g_dst[i].view, NULL); + memset(&g_dst[i], 0, sizeof(g_dst[i])); +} + +void blendp_forget_image(VkImage img) { + if (!g_dev || !img) return; + for (int i = 0; i < NSRC; i++) if (g_src[i].img == img) src_release(i); + for (int i = 0; i < NDST; i++) if (g_dst[i].img == img) dst_release(i); +} + +static VkShaderModule shader(const uint32_t *code, size_t size) { + VkShaderModule m = VK_NULL_HANDLE; + VkShaderModuleCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = size, .pCode = code}; + if (g_vk.CreateShaderModule(g_dev, &ci, NULL, &m) != VK_SUCCESS) return VK_NULL_HANDLE; + return m; +} + +/* The target keeps what the blits put there (LOAD) and stays in TRANSFER_DST_OPTIMAL for the blits + * that follow. The dependencies order the pass between them. */ +static VkRenderPass make_rp(VkFormat fmt) { + VkAttachmentDescription att = {.format = fmt, .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .finalLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL}; + VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; + VkSubpassDescription sub = {.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .colorAttachmentCount = 1, + .pColorAttachments = &ref}; + VkSubpassDependency deps[2] = { + {.srcSubpass = VK_SUBPASS_EXTERNAL, .dstSubpass = 0, + .srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}, + {.srcSubpass = 0, .dstSubpass = VK_SUBPASS_EXTERNAL, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}}; + VkRenderPassCreateInfo rci = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .attachmentCount = 1, + .pAttachments = &att, .subpassCount = 1, .pSubpasses = &sub, + .dependencyCount = 2, .pDependencies = deps}; + VkRenderPass rp = VK_NULL_HANDLE; + if (g_vk.CreateRenderPass(g_dev, &rci, NULL, &rp) != VK_SUCCESS) return VK_NULL_HANDLE; + return rp; +} + +static VkPipeline make_pipe(VkRenderPass rp) { + VkPipelineShaderStageCreateInfo st[2] = { + {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, + .module = g_vert, .pName = "main"}, + {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .module = g_frag, .pName = "main"}}; + VkPipelineVertexInputStateCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + VkPipelineInputAssemblyStateCreateInfo ia = {.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, + .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP}; + VkDynamicState dyn[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo ds = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, + .dynamicStateCount = 2, .pDynamicStates = dyn}; + VkPipelineViewportStateCreateInfo vp = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, + .viewportCount = 1, .scissorCount = 1}; + VkPipelineRasterizationStateCreateInfo rs = {.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, + .polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_NONE, + .frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, .lineWidth = 1.0f}; + VkPipelineMultisampleStateCreateInfo ms = {.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, + .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}; + /* The target's alpha is left alone: the screen is opaque whatever is drawn onto it. */ + VkPipelineColorBlendAttachmentState ba = { + .blendEnable = VK_TRUE, .srcColorBlendFactor = VK_BLEND_FACTOR_ONE, + .dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, .colorBlendOp = VK_BLEND_OP_ADD, + .srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE, .dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + .alphaBlendOp = VK_BLEND_OP_ADD, + .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT}; + VkPipelineColorBlendStateCreateInfo cb = {.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, + .attachmentCount = 1, .pAttachments = &ba}; + VkGraphicsPipelineCreateInfo pi = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2, + .pStages = st, .pVertexInputState = &vi, .pInputAssemblyState = &ia, + .pViewportState = &vp, .pRasterizationState = &rs, .pMultisampleState = &ms, + .pColorBlendState = &cb, .pDynamicState = &ds, .layout = g_pl, + .renderPass = rp, .subpass = 0}; + VkPipeline p = VK_NULL_HANDLE; + if (g_vk.CreateGraphicsPipelines(g_dev, VK_NULL_HANDLE, 1, &pi, NULL, &p) != VK_SUCCESS) return VK_NULL_HANDLE; + return p; +} + +static void objects_destroy(void) { + if (g_vert) g_vk.DestroyShaderModule(g_dev, g_vert, NULL); + if (g_frag) g_vk.DestroyShaderModule(g_dev, g_frag, NULL); + if (g_dpool) g_vk.DestroyDescriptorPool(g_dev, g_dpool, NULL); + if (g_pl) g_vk.DestroyPipelineLayout(g_dev, g_pl, NULL); + if (g_dsl) g_vk.DestroyDescriptorSetLayout(g_dev, g_dsl, NULL); + if (g_sampler) g_vk.DestroySampler(g_dev, g_sampler, NULL); + g_vert = g_frag = VK_NULL_HANDLE; g_dpool = VK_NULL_HANDLE; g_pl = VK_NULL_HANDLE; + g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE; +} + +static int objects_ensure(void) { + if (g_ready) return g_ready == 1 ? 0 : -1; + g_ready = -1; + if (!g_dev || !g_vk.CreateGraphicsPipelines) goto fail; + VkSamplerCreateInfo sci = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_LINEAR, + .minFilter = VK_FILTER_LINEAR, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, + .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE}; + if (g_vk.CreateSampler(g_dev, &sci, NULL, &g_sampler) != VK_SUCCESS) goto fail; + VkDescriptorSetLayoutBinding b = {.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT}; + VkDescriptorSetLayoutCreateInfo dli = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .bindingCount = 1, .pBindings = &b}; + if (g_vk.CreateDescriptorSetLayout(g_dev, &dli, NULL, &g_dsl) != VK_SUCCESS) goto fail; + VkPushConstantRange pcr = {.stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .offset = 0, .size = sizeof(struct pc_blend)}; + VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, + .pSetLayouts = &g_dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pcr}; + if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl) != VK_SUCCESS) goto fail; + VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, NSRC}; + VkDescriptorPoolCreateInfo dpi = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, + .flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = NSRC, + .poolSizeCount = 1, .pPoolSizes = &ps}; + if (g_vk.CreateDescriptorPool(g_dev, &dpi, NULL, &g_dpool) != VK_SUCCESS) goto fail; + if (!(g_vert = shader(blend_vert_code, sizeof(blend_vert_code)))) goto fail; + if (!(g_frag = shader(blend_frag_code, sizeof(blend_frag_code)))) goto fail; + g_ready = 1; + banner_log("gpu", "alpha composition ready on %s: translucent surfaces are blended over what is under them", + vkp_gpu_name()); + return 0; +fail: + objects_destroy(); + banner_log("error", "gpu: the alpha composition pass could not be built on this driver; translucent surfaces " + "are drawn opaque this session"); + return -1; +} + +static int out_slot(VkFormat fmt) { + int i; + for (i = 0; i < NFMT && g_out[i].pipe; i++) if (g_out[i].fmt == fmt) return i; + if (i == NFMT) return -1; + VkRenderPass rp = make_rp(fmt); + VkPipeline pipe = rp ? make_pipe(rp) : VK_NULL_HANDLE; + if (!pipe) { + if (rp) g_vk.DestroyRenderPass(g_dev, rp, NULL); + return -1; + } + g_out[i].fmt = fmt; g_out[i].rp = rp; g_out[i].pipe = pipe; + return i; +} + +static VkImageView make_view(VkImage img, VkFormat fmt) { + VkImageView v = VK_NULL_HANDLE; + VkImageViewCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = img, + .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = fmt, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + if (g_vk.CreateImageView(g_dev, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE; + return v; +} + +/* The slot to recycle: a free one, else the one unused for longest - never one this command buffer + * already refers to. -1 = every slot is in this frame. */ +#define OLDEST(arr, n, out) do { \ + unsigned age_ = 0; \ + (out) = -1; \ + for (int k_ = 0; k_ < (n); k_++) { \ + if (!(arr)[k_].img) { (out) = k_; break; } \ + if ((arr)[k_].frame != g_frame && g_frame - (arr)[k_].frame > age_) { age_ = g_frame - (arr)[k_].frame; (out) = k_; } \ + } \ + } while (0) + +static VkDescriptorSet src_ensure(VkImage img, VkFormat fmt, VkImageLayout layout) { + int i; + for (i = 0; i < NSRC; i++) + if (g_src[i].img == img) { g_src[i].frame = g_frame; return g_src[i].ds; } + OLDEST(g_src, NSRC, i); + if (i < 0) return VK_NULL_HANDLE; + src_release(i); + if (!(g_src[i].view = make_view(img, fmt))) return VK_NULL_HANDLE; + VkDescriptorSetAllocateInfo ai = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + .descriptorPool = g_dpool, .descriptorSetCount = 1, .pSetLayouts = &g_dsl}; + if (g_vk.AllocateDescriptorSets(g_dev, &ai, &g_src[i].ds) != VK_SUCCESS) { + g_src[i].ds = VK_NULL_HANDLE; + src_release(i); + return VK_NULL_HANDLE; + } + VkDescriptorImageInfo ii = {.sampler = g_sampler, .imageView = g_src[i].view, .imageLayout = layout}; + VkWriteDescriptorSet wr = {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g_src[i].ds, .dstBinding = 0, + .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .pImageInfo = &ii}; + g_vk.UpdateDescriptorSets(g_dev, 1, &wr, 0, NULL); + g_src[i].img = img; g_src[i].frame = g_frame; + return g_src[i].ds; +} + +static VkFramebuffer dst_ensure(VkImage img, VkFormat fmt, int w, int h, VkRenderPass rp) { + int i; + for (i = 0; i < NDST; i++) { + if (g_dst[i].img != img) continue; + if (g_dst[i].fmt == fmt && g_dst[i].w == w && g_dst[i].h == h) { g_dst[i].frame = g_frame; return g_dst[i].fb; } + if (g_dst[i].frame == g_frame) return VK_NULL_HANDLE; + break; + } + if (i == NDST) OLDEST(g_dst, NDST, i); + if (i < 0) return VK_NULL_HANDLE; + dst_release(i); + if (!(g_dst[i].view = make_view(img, fmt))) return VK_NULL_HANDLE; + VkFramebufferCreateInfo fi = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .renderPass = rp, + .attachmentCount = 1, .pAttachments = &g_dst[i].view, .width = (uint32_t)w, + .height = (uint32_t)h, .layers = 1}; + if (g_vk.CreateFramebuffer(g_dev, &fi, NULL, &g_dst[i].fb) != VK_SUCCESS) { + g_dst[i].fb = VK_NULL_HANDLE; + dst_release(i); + return VK_NULL_HANDLE; + } + g_dst[i].img = img; g_dst[i].fmt = fmt; g_dst[i].w = w; g_dst[i].h = h; g_dst[i].frame = g_frame; + return g_dst[i].fb; +} + +static void src_layout(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to) { + int sampling = to == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + VkImageMemoryBarrier b = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = from, .newLayout = to, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = img, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, + .srcAccessMask = sampling ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_SHADER_READ_BIT, + .dstAccessMask = sampling ? VK_ACCESS_SHADER_READ_BIT : VK_ACCESS_TRANSFER_READ_BIT}; + g_vk.CmdPipelineBarrier(cmd, sampling ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + sampling ? VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT : VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &b); +} + +int blendp_draw(VkCommandBuffer cmd, VkImage src, VkFormat src_fmt, int src_w, int src_h, int src_general, + VkImage dst, VkFormat dst_fmt, int dst_w, int dst_h, const VkImageBlit *blit) { + if (!src || !dst || src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0 || objects_ensure() != 0) return -1; + int slot = out_slot(dst_fmt); + if (slot < 0) return -1; + VkImageLayout sampled = src_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + VkDescriptorSet ds = src_ensure(src, src_fmt, sampled); + if (!ds) return -1; + VkFramebuffer fb = dst_ensure(dst, dst_fmt, dst_w, dst_h, g_out[slot].rp); + if (!fb) return -1; + + const VkOffset3D *d = blit->dstOffsets, *s = blit->srcOffsets; + int x0 = d[0].x < d[1].x ? d[0].x : d[1].x, x1 = d[0].x < d[1].x ? d[1].x : d[0].x; + int y0 = d[0].y < d[1].y ? d[0].y : d[1].y, y1 = d[0].y < d[1].y ? d[1].y : d[0].y; + if (x0 < 0) x0 = 0; + if (y0 < 0) y0 = 0; + if (x1 > dst_w) x1 = dst_w; + if (y1 > dst_h) y1 = dst_h; + if (x1 <= x0 || y1 <= y0) return 0; + + struct pc_blend pc = { + .dst = {2.0f * d[0].x / dst_w - 1.0f, 2.0f * d[0].y / dst_h - 1.0f, + 2.0f * d[1].x / dst_w - 1.0f, 2.0f * d[1].y / dst_h - 1.0f}, + .src = {(float)s[0].x / src_w, (float)s[0].y / src_h, (float)s[1].x / src_w, (float)s[1].y / src_h}}; + + if (!src_general) src_layout(cmd, src, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, sampled); + VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_out[slot].rp, + .framebuffer = fb, + .renderArea = {{x0, y0}, {(uint32_t)(x1 - x0), (uint32_t)(y1 - y0)}}}; + VkViewport vp = {0, 0, (float)dst_w, (float)dst_h, 0, 1}; + g_vk.CmdBeginRenderPass(cmd, &rpi, VK_SUBPASS_CONTENTS_INLINE); + g_vk.CmdSetViewport(cmd, 0, 1, &vp); + g_vk.CmdSetScissor(cmd, 0, 1, &rpi.renderArea); + g_vk.CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_out[slot].pipe); + g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl, 0, 1, &ds, 0, NULL); + g_vk.CmdPushConstants(cmd, g_pl, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(pc), &pc); + g_vk.CmdDraw(cmd, 4, 1, 0, 0); + g_vk.CmdEndRenderPass(cmd); + if (!src_general) src_layout(cmd, src, sampled, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + return 0; +} diff --git a/app/src/main/cpp/waylandcomp/src/blend_pass.h b/app/src/main/cpp/waylandcomp/src/blend_pass.h new file mode 100644 index 000000000..2faade252 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/blend_pass.h @@ -0,0 +1,28 @@ +#ifndef BLEND_PASS_H +#define BLEND_PASS_H +/* + * Alpha composition. The scene is composed with blits, which replace what is under them; a surface + * with translucent pixels (gamescope's overlay and notification planes over a game, a toolkit's + * shadowed popup) is drawn through this pass instead, source-over with premultiplied alpha. + * + * Compositor thread. Objects are built on the first use; if the driver refuses them the pass is + * unavailable for the session (logged once) and the caller keeps blitting. + */ +#define VK_USE_PLATFORM_ANDROID_KHR +#include + +/* Called from dev_init (device up). */ +void blendp_bind_device(VkDevice dev); +/* A source or target image is about to be destroyed: drop what is cached for it. Frames are fenced, + * so nothing submitted still uses it. */ +void blendp_forget_image(VkImage img); +/* A new command buffer is being recorded: what the previous one used may be recycled again. */ +void blendp_begin_frame(void); + +/* Record one surface over `dst`. `dst` is in TRANSFER_DST_OPTIMAL before and after. `src` was created + * with SAMPLED usage and is in GENERAL (src_general) or TRANSFER_SRC_OPTIMAL, and is left there. + * `blit` is the draw as the blit path maps it. 0 = recorded, -1 = unavailable (nothing recorded). */ +int blendp_draw(VkCommandBuffer cmd, VkImage src, VkFormat src_fmt, int src_w, int src_h, int src_general, + VkImage dst, VkFormat dst_fmt, int dst_w, int dst_h, const VkImageBlit *blit); + +#endif diff --git a/app/src/main/cpp/waylandcomp/src/blend_vert.h b/app/src/main/cpp/waylandcomp/src/blend_vert.h new file mode 100644 index 000000000..f402c6a92 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/blend_vert.h @@ -0,0 +1,55 @@ + // 1115.1.0 + #pragma once +const uint32_t blend_vert_code[] = { + 0x07230203,0x00010000,0x0008000b,0x0000003a,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, + 0x0008000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000c,0x0000001b,0x00000031, + 0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,0x00000000,0x00030005, + 0x00000009,0x00000074,0x00060005,0x0000000c,0x565f6c67,0x65747265,0x646e4978,0x00007865, + 0x00060005,0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019, + 0x00000000,0x505f6c67,0x7469736f,0x006e6f69,0x00070006,0x00000019,0x00000001,0x505f6c67, + 0x746e696f,0x657a6953,0x00000000,0x00070006,0x00000019,0x00000002,0x435f6c67,0x4470696c, + 0x61747369,0x0065636e,0x00070006,0x00000019,0x00000003,0x435f6c67,0x446c6c75,0x61747369, + 0x0065636e,0x00030005,0x0000001b,0x00000000,0x00030005,0x0000001d,0x00004350,0x00040006, + 0x0000001d,0x00000000,0x00747364,0x00040006,0x0000001d,0x00000001,0x00637273,0x00030005, + 0x0000001f,0x00006370,0x00030005,0x00000031,0x00007675,0x00040047,0x0000000c,0x0000000b, + 0x0000002a,0x00030047,0x00000019,0x00000002,0x00050048,0x00000019,0x00000000,0x0000000b, + 0x00000000,0x00050048,0x00000019,0x00000001,0x0000000b,0x00000001,0x00050048,0x00000019, + 0x00000002,0x0000000b,0x00000003,0x00050048,0x00000019,0x00000003,0x0000000b,0x00000004, + 0x00030047,0x0000001d,0x00000002,0x00050048,0x0000001d,0x00000000,0x00000023,0x00000000, + 0x00050048,0x0000001d,0x00000001,0x00000023,0x00000010,0x00040047,0x00000031,0x0000001e, + 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006, + 0x00000020,0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000007, + 0x00000007,0x00040015,0x0000000a,0x00000020,0x00000001,0x00040020,0x0000000b,0x00000001, + 0x0000000a,0x0004003b,0x0000000b,0x0000000c,0x00000001,0x0004002b,0x0000000a,0x0000000e, + 0x00000001,0x00040017,0x00000015,0x00000006,0x00000004,0x00040015,0x00000016,0x00000020, + 0x00000000,0x0004002b,0x00000016,0x00000017,0x00000001,0x0004001c,0x00000018,0x00000006, + 0x00000017,0x0006001e,0x00000019,0x00000015,0x00000006,0x00000018,0x00000018,0x00040020, + 0x0000001a,0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004002b, + 0x0000000a,0x0000001c,0x00000000,0x0004001e,0x0000001d,0x00000015,0x00000015,0x00040020, + 0x0000001e,0x00000009,0x0000001d,0x0004003b,0x0000001e,0x0000001f,0x00000009,0x00040020, + 0x00000020,0x00000009,0x00000015,0x0004002b,0x00000006,0x00000029,0x00000000,0x0004002b, + 0x00000006,0x0000002a,0x3f800000,0x00040020,0x0000002e,0x00000003,0x00000015,0x00040020, + 0x00000030,0x00000003,0x00000007,0x0004003b,0x00000030,0x00000031,0x00000003,0x00050036, + 0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000008, + 0x00000009,0x00000007,0x0004003d,0x0000000a,0x0000000d,0x0000000c,0x000500c7,0x0000000a, + 0x0000000f,0x0000000d,0x0000000e,0x0004006f,0x00000006,0x00000010,0x0000000f,0x0004003d, + 0x0000000a,0x00000011,0x0000000c,0x000500c3,0x0000000a,0x00000012,0x00000011,0x0000000e, + 0x0004006f,0x00000006,0x00000013,0x00000012,0x00050050,0x00000007,0x00000014,0x00000010, + 0x00000013,0x0003003e,0x00000009,0x00000014,0x00050041,0x00000020,0x00000021,0x0000001f, + 0x0000001c,0x0004003d,0x00000015,0x00000022,0x00000021,0x0007004f,0x00000007,0x00000023, + 0x00000022,0x00000022,0x00000000,0x00000001,0x00050041,0x00000020,0x00000024,0x0000001f, + 0x0000001c,0x0004003d,0x00000015,0x00000025,0x00000024,0x0007004f,0x00000007,0x00000026, + 0x00000025,0x00000025,0x00000002,0x00000003,0x0004003d,0x00000007,0x00000027,0x00000009, + 0x0008000c,0x00000007,0x00000028,0x00000001,0x0000002e,0x00000023,0x00000026,0x00000027, + 0x00050051,0x00000006,0x0000002b,0x00000028,0x00000000,0x00050051,0x00000006,0x0000002c, + 0x00000028,0x00000001,0x00070050,0x00000015,0x0000002d,0x0000002b,0x0000002c,0x00000029, + 0x0000002a,0x00050041,0x0000002e,0x0000002f,0x0000001b,0x0000001c,0x0003003e,0x0000002f, + 0x0000002d,0x00050041,0x00000020,0x00000032,0x0000001f,0x0000000e,0x0004003d,0x00000015, + 0x00000033,0x00000032,0x0007004f,0x00000007,0x00000034,0x00000033,0x00000033,0x00000000, + 0x00000001,0x00050041,0x00000020,0x00000035,0x0000001f,0x0000000e,0x0004003d,0x00000015, + 0x00000036,0x00000035,0x0007004f,0x00000007,0x00000037,0x00000036,0x00000036,0x00000002, + 0x00000003,0x0004003d,0x00000007,0x00000038,0x00000009,0x0008000c,0x00000007,0x00000039, + 0x00000001,0x0000002e,0x00000034,0x00000037,0x00000038,0x0003003e,0x00000031,0x00000039, + 0x000100fd,0x00010038 +}; diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index c206dfb2c..63f0eed8a 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -237,6 +238,8 @@ struct surface { struct dmabuf_buffer *dmabuf_buf; /* its imported image, kept until replaced or the surface goes */ struct wl_listener dmabuf_destroy; int buf_w, buf_h, has_content; + int buf_alpha; + int opaque[4], pending_opaque[4], pending_opaque_set; /* x, y, w, h; w = 0: none */ int src_set, dst_set; float src[4]; int dst[2]; @@ -247,6 +250,10 @@ struct surface { int releases_pending; /* FPS limiter: buffers of this surface still to be released */ enum surface_role role; + /* A role-less surface's last buffer, held unreleased: it may become the pointer's image + * (wl_pointer.set_cursor after the commit, which is wlroots' order). */ + struct wl_resource *idle_buffer; + struct wl_listener idle_buffer_destroy; struct wl_resource *xdg_surface, *xdg_toplevel; struct wl_resource *viewport; @@ -428,9 +435,16 @@ static int on_release_timer(int fd, uint32_t mask, void *data) { * delivered (a swapchain rebuild destroys buffers with queued releases) or that a coarser earlier * limit had spaced out, and the game's first frames after that waited on empty slots. */ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) { - int limit = g_fps_limit; - if (limit <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; } - int64_t interval = 1000000000LL / limit, now = now_ns(); + const int limit = g_fps_limit; + /* Without a limit of its own a game is paced to the screen. A swapchain that does not wait for + * frame callbacks (MAILBOX, IMMEDIATE) is held back by nothing else here, so handing a replaced + * buffer straight back let it draw as fast as the GPU allowed and everything above the refresh + * rate was thrown away - 178 frames a second for 91 on screen, measured (WinNative, maxjivi05). + * One release per refresh is the back-pressure X11 gives, and the screen shows the same frames + * either way. */ + const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns; + if (interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; } + int64_t now = now_ns(); int64_t at = s->next_release_ns + interval; int64_t latest = now + interval * (int64_t)(s->releases_pending + 1); if (at < now) at = now; @@ -461,6 +475,12 @@ static struct seat_pointer g_ptrs[MAX_PTRS]; static int g_nptrs; static struct seat_keyboard g_kbs[MAX_PTRS]; static int g_nkbs; +/* Modifier state in the keymap's real-modifier bits (Shift=0x1, Lock=0x2, Control=0x4, Mod1=0x8, + * Mod4=0x40). A client of the wayland backend - gamescope, labwc - takes modifiers only from + * wl_keyboard.modifiers and ignores what a Shift key event does to its xkb state, so without this + * every capital arrived lowercase. */ +static uint32_t g_mods_depressed, g_mods_locked; +static uint32_t g_mod_keys_held; /* one bit per modifier key below, so a repeat press is harmless */ static struct seat_touch g_touches[MAX_PTRS]; static int g_ntouches; @@ -475,6 +495,7 @@ static int g_ntouches; #define CURSOR_MAX_PX (256 * 256) static pthread_mutex_t g_cursor_lock = PTHREAD_MUTEX_INITIALIZER; static struct surface *g_cursor_surface; /* compositor thread only */ +static struct surface *g_cursor_shown; /* compositor thread: whose image g_cursor_px holds */ static int g_cursor_hx, g_cursor_hy; /* hotspot, surface-local */ static uint32_t g_cursor_px[CURSOR_MAX_PX]; /* guarded by g_cursor_lock: ARGB8888 snapshot */ static uint32_t g_cursor_rb[CURSOR_MAX_PX]; /* compositor thread: GPU readback staging */ @@ -482,6 +503,14 @@ static int g_cursor_w, g_cursor_h; /* 0 = nothing to draw */ static int g_cursor_hidden = 1; /* the client asked for no pointer */ static int g_cursor_serial; /* bumped on every change; the app polls it */ +/* The last image again, after a hide: the same surface set as the pointer once more with nothing + * newly committed to it (wlroots re-sets its cursor surface each time the pointer enters). */ +static void cursor_publish_shown(void) { + pthread_mutex_lock(&g_cursor_lock); + if (g_cursor_w > 0) { g_cursor_hidden = 0; g_cursor_serial++; } /* serial: the hotspot may be new */ + pthread_mutex_unlock(&g_cursor_lock); +} + static void cursor_publish_hidden(void) { pthread_mutex_lock(&g_cursor_lock); if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; } @@ -512,6 +541,13 @@ static void cursor_publish_shm(struct wl_shm_buffer *shm, int hx, int hy) { wl_shm_buffer_end_access(shm); } +/* The serial alone, without the lock: the app asks on every pointer move, and the snapshot below + * copies up to 256 KB of pixels across JNI and holds the lock the compositor thread takes to + * change the cursor. A torn read is only a missed or an extra snapshot. */ +int banner_cursor_serial(void) { + return __atomic_load_n(&g_cursor_serial, __ATOMIC_RELAXED); +} + /* Read by the app (UI thread). out = [serial, hidden, w, h, hotspotX, hotspotY, pixels...]. * Returns the number of ints written, or 0 if out is too small. */ int banner_cursor_snapshot(int *out, int cap) { @@ -702,6 +738,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res wl_buffer_send_release(buffer); s->buf_w = w; s->buf_h = h; + s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888; s->has_content = s->shm_img != NULL; g_stat_shm++; struct client_info *ci = client_info_of(wl_resource_get_client(s->resource)); @@ -753,6 +790,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re } s->buf_w = b->width; s->buf_h = b->height; + s->buf_alpha = (b->format & 0xff) == 'A'; s->has_content = b->img != NULL; g_stat_dmabuf++; const int announced_now = !s->announced_vulkan; @@ -924,13 +962,94 @@ static void surface_frame(struct wl_client *c, struct wl_resource *r, uint32_t c wl_resource_set_implementation(callback, NULL, NULL, frame_callback_destroy); wl_list_insert(s->pending_frames.prev, wl_resource_get_link(callback)); } +/* The bounding box serves pointer confinement. The exact flag also tells opaque-region handling + * whether the bounding box itself is the whole region. */ +struct region { int set, exact; int x, y, w, h; }; + +/* A wl_surface's opaque region is pending until its next commit. An exact region that covers + * the surface lets the blit path keep handling an otherwise alpha-capable buffer. */ static void surface_set_opaque(struct wl_client *c, struct wl_resource *r, - struct wl_resource *region) {} + struct wl_resource *region) { + struct surface *s = wl_resource_get_user_data(r); + struct region *rg = region ? wl_resource_get_user_data(region) : NULL; + memset(s->pending_opaque, 0, sizeof(s->pending_opaque)); + s->pending_opaque_set = 1; + if (rg && rg->set && rg->exact) { + s->pending_opaque[0] = rg->x; + s->pending_opaque[1] = rg->y; + s->pending_opaque[2] = rg->w; + s->pending_opaque[3] = rg->h; + } + struct client_info *ci = client_info_of(c); + if (ci) ci->declares_opaque = 1; +} static void surface_set_input(struct wl_client *c, struct wl_resource *r, struct wl_resource *region) {} static void send_toplevel_configure(struct surface *s); +/* The pointer image from a cursor surface's buffer: wl_shm is copied, a dma-buf (labwc on a GPU + * renderer) is read back once the client's render into it is done - its implicit fence, as the + * zero-copy path waits for it (ahb_swapchain_present). */ +static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer) { + struct dmabuf_buffer *db = get_dmabuf(buffer); + struct wl_shm_buffer *shm = db ? NULL : wl_shm_buffer_get(buffer); + if (shm) { + cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy); + } else if (db && db->n_planes >= 1 && db->width > 0 && db->height > 0 && + (int64_t)db->width * db->height <= CURSOR_MAX_PX) { + if (!db->img && !db->import_failed) { + db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height, + db->stride[0], db->offset[0]); + if (!db->img) db->import_failed = 1; + } + if (!db->img) return; + struct pollfd p = {.fd = db->fd[0], .events = POLLIN}; + int r; + do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); + if (vkp_image_readback(db->img, g_cursor_rb, CURSOR_MAX_PX) != 0) return; + cursor_publish_pixels((const uint8_t *)g_cursor_rb, db->width, db->height, + (size_t)db->width * 4, g_cursor_hx, g_cursor_hy); + } else { + return; + } + g_cursor_shown = s; +} + +static void on_idle_buffer_destroyed(struct wl_listener *l, void *data) { + struct surface *s = wl_container_of(l, s, idle_buffer_destroy); + wl_list_remove(&s->idle_buffer_destroy.link); + wl_list_init(&s->idle_buffer_destroy.link); + s->idle_buffer = NULL; +} + +/* Only what could be a pointer image is held; anything larger goes straight back. */ +static void surface_hold_idle(struct surface *s, struct wl_resource *buffer) { + struct dmabuf_buffer *db = get_dmabuf(buffer); + struct wl_shm_buffer *shm = db ? NULL : wl_shm_buffer_get(buffer); + int64_t px = db ? (int64_t)db->width * db->height + : shm ? (int64_t)wl_shm_buffer_get_width(shm) * wl_shm_buffer_get_height(shm) : 0; + if (px <= 0 || px > CURSOR_MAX_PX) { wl_buffer_send_release(buffer); return; } + s->idle_buffer = buffer; + s->idle_buffer_destroy.notify = on_idle_buffer_destroyed; + wl_resource_add_destroy_listener(buffer, &s->idle_buffer_destroy); +} + +/* Lets go of the held buffer; release = give it back to the client (not while it is going away). */ +static struct wl_resource *surface_take_idle(struct surface *s) { + struct wl_resource *buffer = s->idle_buffer; + if (!buffer) return NULL; + wl_list_remove(&s->idle_buffer_destroy.link); + wl_list_init(&s->idle_buffer_destroy.link); + s->idle_buffer = NULL; + return buffer; +} + +static void surface_drop_idle(struct surface *s) { + struct wl_resource *buffer = surface_take_idle(s); + if (buffer) wl_buffer_send_release(buffer); +} + static void surface_commit(struct wl_client *c, struct wl_resource *r) { struct surface *s = wl_resource_get_user_data(r); struct surface *child; @@ -954,6 +1073,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { memcpy(s->dst, s->pending_dst, sizeof(s->dst)); s->pending_dst_set = 0; } + if (s->pending_opaque_set) { + memcpy(s->opaque, s->pending_opaque, sizeof(s->opaque)); + s->pending_opaque_set = 0; + } if (s->pending_attach) { struct wl_resource *buffer = s->pending_buffer; @@ -970,28 +1093,19 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { s->pending_buffer = NULL; s->pending_attach = 0; + surface_drop_idle(s); /* replaced, whatever the surface is now */ if (s->role == ROLE_CURSOR) { /* The client's pointer image, copied out for the app's overlay (see cursor_publish_*) * 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 (shm) { - cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy); - } else if (db && db->n_planes >= 1 && db->width > 0 && db->height > 0 && - (int64_t)db->width * db->height <= CURSOR_MAX_PX) { - if (!db->img && !db->import_failed) { - db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height, - db->stride[0], db->offset[0]); - if (!db->img) db->import_failed = 1; - } - if (db->img && vkp_image_readback(db->img, g_cursor_rb, CURSOR_MAX_PX) == 0) - cursor_publish_pixels((const uint8_t *)g_cursor_rb, db->width, db->height, - (size_t)db->width * 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. */ - if (buffer) wl_buffer_send_release(buffer); + /* Role-less surface: never drawn, but its buffer is kept for a set_cursor to come. */ + if (buffer) surface_hold_idle(s, buffer); } else if (db) { take_dmabuf(s, db, buffer); } else if (shm) { @@ -1063,6 +1177,8 @@ static void surface_resource_destroy(struct wl_resource *r) { for (int i = 0; i < g_nkbs; i++) if (g_kbs[i].focus == r) g_kbs[i].focus = NULL; touch_cancel_surface(s); if (g_cursor_surface == s) { g_cursor_surface = NULL; cursor_publish_hidden(); } + if (g_cursor_shown == s) g_cursor_shown = NULL; + surface_take_idle(s); if (g_grab == s) g_grab = NULL; if (g_key_target == s) g_key_target = NULL; if (g_ime_click == s) g_ime_click = NULL; @@ -1099,24 +1215,29 @@ static void surface_resource_destroy(struct wl_resource *r) { /* ------------------------------------------------------------------ wl_region */ -/* A region is kept as the bounding box of its rectangles: enough for pointer confinement, - * where winewayland sends one rectangle (the ClipCursor area). Subtractions are ignored. */ -struct region { int set; int x, y, w, h; }; - static void region_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static void region_add(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y, int32_t w, int32_t h) { struct region *rg = wl_resource_get_user_data(r); if (!rg || w <= 0 || h <= 0) return; - if (!rg->set) { rg->x = x; rg->y = y; rg->w = w; rg->h = h; rg->set = 1; return; } - int x2 = rg->x + rg->w > x + w ? rg->x + rg->w : x + w; - int y2 = rg->y + rg->h > y + h ? rg->y + rg->h : y + h; + if (!rg->set) { rg->x = x; rg->y = y; rg->w = w; rg->h = h; rg->set = rg->exact = 1; return; } + long long x2 = (long long)rg->x + rg->w, y2 = (long long)rg->y + rg->h; + long long nx2 = (long long)x + w, ny2 = (long long)y + h; + int inside = x >= rg->x && y >= rg->y && nx2 <= x2 && ny2 <= y2; + int around = x <= rg->x && y <= rg->y && nx2 >= x2 && ny2 >= y2; + if (!inside && !around) rg->exact = 0; + if (nx2 > x2) x2 = nx2; + if (ny2 > y2) y2 = ny2; if (x < rg->x) rg->x = x; if (y < rg->y) rg->y = y; - rg->w = x2 - rg->x; rg->h = y2 - rg->y; + rg->w = (int)(x2 - rg->x > INT32_MAX ? INT32_MAX : x2 - rg->x); + rg->h = (int)(y2 - rg->y > INT32_MAX ? INT32_MAX : y2 - rg->y); } static void region_subtract(struct wl_client *c, struct wl_resource *r, - int32_t x, int32_t y, int32_t w, int32_t h) {} + int32_t x, int32_t y, int32_t w, int32_t h) { + struct region *rg = wl_resource_get_user_data(r); + if (rg && w > 0 && h > 0) rg->exact = 0; +} static void region_resource_destroy(struct wl_resource *r) { free(wl_resource_get_user_data(r)); } static const struct wl_region_interface region_impl = { .destroy = region_destroy, @@ -1139,6 +1260,7 @@ static void compositor_create_surface(struct wl_client *c, struct wl_resource *r wl_list_init(&s->child_link); wl_list_init(&s->toplevel_link); wl_list_init(&s->pending_buffer_destroy.link); + wl_list_init(&s->idle_buffer_destroy.link); wl_list_insert(&g_surfaces, &s->link); wl_resource_set_implementation(s->resource, &surface_impl, s, surface_resource_destroy); } @@ -1589,6 +1711,17 @@ static void note_hdr_unimported(const struct draw_list *dl, struct surface *s, i g_hdr_unimported_below = dl->n; } +/* A client that describes opaque regions can intentionally leave part of an alpha buffer see-through. + * Gamescope uses this for its full-size Steam notification and overlay planes. */ +static int surface_translucent(const struct surface *s, int w, int h) { + if (!s->buf_alpha) return 0; + const struct client_info *ci = client_info_of(wl_resource_get_client(s->resource)); + if (!ci || !ci->declares_opaque) return 0; + const int *o = s->opaque; + return !(o[2] > 0 && o[0] <= 0 && o[1] <= 0 && + (long long)o[0] + o[2] >= w && (long long)o[1] + o[3] >= h); +} + static void add_surface(struct draw_list *dl, struct surface *s, int ox, int oy) { struct vkp_image *img = surface_image(s); float sx = 0, sy = 0, sw = (float)s->buf_w, sh = (float)s->buf_h; @@ -1608,7 +1741,8 @@ static void add_surface(struct draw_list *dl, struct surface *s, int ox, int oy) dl->d = d; dl->cap = cap; } - dl->d[dl->n++] = (struct vkp_draw){img, sx, sy, sw, sh, ox, oy, dw, dh}; + dl->d[dl->n++] = (struct vkp_draw){img, sx, sy, sw, sh, ox, oy, dw, dh, + surface_translucent(s, dw, dh)}; s->drawn = 1; } @@ -1679,6 +1813,7 @@ static int on_frame_timer(void *data) { static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) { for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) { const struct vkp_draw *d = &dl->d[i]; + if (d->blend) continue; /* the translucent plane must not replace the opaque game layer */ if (!vkp_image_is_dmabuf(d->img)) continue; if (d->dx != 0 || d->dy != 0 || d->dw != scene_w || d->dh != scene_h) continue; if (d->sx != 0 || d->sy != 0 || (int)d->sw != vkp_image_width(d->img) || @@ -2017,7 +2152,7 @@ static void render_scene(void) { * its own layer, cropped and placed by the display. */ int go[8], ov = 0; if (over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go)) - ov = sc_layer_present_overlay(dl.d[li + 1].img, go) == 0 ? 1 : -1; + ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1; if (ov <= 0) sc_layer_hide_overlay(); if (ov < 0) { /* the overlay layer refused it: draw the whole scene the old way */ sc_layer_hide(); @@ -2143,6 +2278,16 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3 g_cursor_surface = s; g_cursor_hx = hx; g_cursor_hy = hy; + /* Its content may already be committed: wlroots' Wayland backend attaches and commits the + * cursor surface first and sets it as the pointer after, and sets it again with nothing new + * committed each time the pointer re-enters. */ + struct wl_resource *buffer = surface_take_idle(s); + if (buffer) { + cursor_publish_buffer(s, buffer); + wl_buffer_send_release(buffer); + } else if (g_cursor_shown == s) { + cursor_publish_shown(); + } } static void pointer_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static const struct wl_pointer_interface pointer_impl = { @@ -2290,8 +2435,8 @@ static void keyboard_focus(struct wl_resource *target) { if (sk->focus == target) continue; sk->focus = target; wl_keyboard_send_enter(sk->kb, wl_display_next_serial(g_display), target, &keys); - /* Baseline modifiers = none; Shift/Ctrl arrive as their own key events. */ - wl_keyboard_send_modifiers(sk->kb, wl_display_next_serial(g_display), 0, 0, 0, 0); + wl_keyboard_send_modifiers(sk->kb, wl_display_next_serial(g_display), + g_mods_depressed, 0, g_mods_locked, 0); } wl_array_release(&keys); banner_clipboard_keyboard_focus(client); /* wl_data_device selection follows focus */ @@ -2988,7 +3133,34 @@ static void scroll_event(int steps) { wl_display_flush_clients(g_display); } +/* Folds a key into the modifier state; returns whether the state changed. */ +static int update_modifiers(uint32_t evdev, int pressed) { + static const struct { uint32_t evdev, mask; } mod_keys[] = { + { 42, 0x1 }, { 54, 0x1 }, /* Shift L/R */ + { 29, 0x4 }, { 97, 0x4 }, /* Control L/R */ + { 56, 0x8 }, { 100, 0x8 }, /* Alt L/R, both Mod1 in this keymap */ + { 125, 0x40 }, { 126, 0x40 }, /* Super L/R */ + }; + uint32_t depressed = g_mods_depressed, locked = g_mods_locked; + if (evdev == 58) { /* Caps Lock toggles on press */ + if (pressed) locked ^= 0x2; + } else { + int i, n = (int)(sizeof(mod_keys) / sizeof(mod_keys[0])); + for (i = 0; i < n && mod_keys[i].evdev != evdev; i++) {} + if (i == n) return 0; + if (pressed) g_mod_keys_held |= 1u << i; else g_mod_keys_held &= ~(1u << i); + depressed = 0; + for (int j = 0; j < n; j++) if (g_mod_keys_held & (1u << j)) depressed |= mod_keys[j].mask; + } + if (depressed == g_mods_depressed && locked == g_mods_locked) return 0; + g_mods_depressed = depressed; + g_mods_locked = locked; + return 1; +} + static void key_event(uint32_t evdev, int pressed) { + /* Tracked even with nothing to deliver to, so a Shift released unseen is not left held. */ + int mods_changed = update_modifiers(evdev, pressed); /* Keys go to the program window the user last clicked (else the topmost non-shell window), * never to Wine's desktop surface: winewayland hands each key to the hwnd of the surface that * holds keyboard focus, and a key handed to explorer's desktop hwnd is queued to explorer's @@ -3008,9 +3180,13 @@ static void key_event(uint32_t evdev, int pressed) { struct seat_keyboard *sk; if (!keyboard_for(client)) return; keyboard_focus(target->resource); - for_each_keyboard_of(client, sk) + for_each_keyboard_of(client, sk) { wl_keyboard_send_key(sk->kb, wl_display_next_serial(g_display), now_ms(), evdev, pressed ? WL_KEYBOARD_KEY_STATE_PRESSED : WL_KEYBOARD_KEY_STATE_RELEASED); + if (mods_changed) + wl_keyboard_send_modifiers(sk->kb, wl_display_next_serial(g_display), + g_mods_depressed, 0, g_mods_locked, 0); + } wl_display_flush_clients(g_display); } diff --git a/app/src/main/cpp/waylandcomp/src/compositor_internal.h b/app/src/main/cpp/waylandcomp/src/compositor_internal.h index d6e07c5f5..db739132a 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor_internal.h +++ b/app/src/main/cpp/waylandcomp/src/compositor_internal.h @@ -60,6 +60,9 @@ struct client_info { /* An OpenGL program whose EGL gave up on the GPU: it asked for dma-buf feedback (EGL's * Wayland GPU path always does), never made a dma-buf buffer, and draws wl_shm frames. */ unsigned asked_feedback : 1, shm_gl_said : 1; + /* Clients that describe opaque regions can use alpha outside those regions. Wine windows + * never describe them, and their unused alpha channel must not make them translucent. */ + unsigned declares_opaque : 1; unsigned dmabuf_buffers, shm_frames; struct client_info *next; }; diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c index 43b94987f..47a819bfd 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c @@ -19,6 +19,7 @@ void banner_log(const char *tag, const char *fmt, ...) __attribute__((format(pri static _Atomic int g_kind = VKP_FG_ENGINE_LSFG; static _Atomic int g_armed; static _Atomic int g_mult = 2; +static _Atomic int g_target; /* LSFG adaptive fps, 0 = fixed multiplier */ static _Atomic int g_model = 3; static _Atomic int g_preset = 2; static _Atomic int g_cfg_dirty = 1; @@ -51,6 +52,7 @@ static struct { /* ---- engine + generation ring (compositor thread) ------------------------------------ */ static int g_engine_kind = -1; /* kind of the running engine, -1 = none */ +static int g_engine_cache_gen = -1; /* the LSFG cache it loaded */ static int g_engine_ok; /* The engine of this kind (with this cache) could not start or build its chain; not retried * every frame - a new engine selection or a new cache clears it. */ @@ -92,15 +94,20 @@ static int64_t now_ns(void) { void vkp_framegen_set_engine(int kind) { if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_WINFG) kind = VKP_FG_ENGINE_LSFG; atomic_store(&g_kind, kind); + atomic_store(&g_failed_kind, -1); atomic_store(&g_cfg_dirty, 1); } -void vkp_framegen_set_armed(int armed, int multiplier) { +void vkp_framegen_set_armed(int armed, int multiplier, int target_fps) { + if (target_fps < 0) target_fps = 0; + /* Adaptive sizes the ring and the swapchain for the most it may ever generate. */ + if (target_fps) multiplier = VKP_FG_MAX_GENERATIONS + 1; if (multiplier < 2) multiplier = 2; if (multiplier > VKP_FG_MAX_GENERATIONS + 1) multiplier = VKP_FG_MAX_GENERATIONS + 1; if (atomic_exchange(&g_mult, multiplier) != multiplier) atomic_store(&g_cfg_dirty, 1); + if (atomic_exchange(&g_target, target_fps) != target_fps) atomic_store(&g_cfg_dirty, 1); atomic_store(&g_armed, armed ? 1 : 0); - LOGD("framegen: set_armed(%d, x%d)", armed, multiplier); + LOGD("framegen: set_armed(%d, x%d, target %d fps)", armed, multiplier, target_fps); } void vkp_framegen_set_lsfg_cache_path(const char *path) { @@ -285,7 +292,9 @@ int vkp_framegen_extra_images(void) { } static int ensure_engine(int kind) { - if (g_engine_ok && g_engine_kind == kind) return 1; + const int cache_gen = atomic_load(&g_cache_gen); + if (g_engine_ok && g_engine_kind == kind && (kind != VKP_FG_ENGINE_LSFG || g_engine_cache_gen == cache_gen)) + return 1; if (start_failed_for(kind)) return 0; if (g_engine_ok) { destroy_ring(); fge_stop(); g_engine_ok = 0; g_engine_kind = -1; } char *path = NULL; @@ -293,7 +302,7 @@ static int ensure_engine(int kind) { if (g_cache_path) path = strdup(g_cache_path); pthread_mutex_unlock(&g_lock); if (kind == VKP_FG_ENGINE_LSFG && !path) { - FGLOG("LSFG Native can't start: no shader cache (import Lossless.dll in Settings)"); + FGLOG("LSFG Native can't start: no shader cache from Lossless.dll"); mark_failed(kind); return 0; } @@ -305,29 +314,39 @@ static int ensure_engine(int kind) { mark_failed(kind); return 0; } - g_engine_ok = 1; g_engine_kind = kind; + g_engine_ok = 1; g_engine_kind = kind; g_engine_cache_gen = cache_gen; atomic_store(&g_cfg_dirty, 1); g_built_w = g_built_h = 0; FGLOG("%s engine ready (%s)", fge_engine_name(kind), fge_build_info()); return 1; } -static int g_logged_mult; +/* "x3 (2 interpolated frames per game frame)" or "adaptive to 90 fps (up to 3 ...)". */ +static const char *describe_mode(char *buf, size_t n, int mult, int target) { + if (target) snprintf(buf, n, "adaptive to %d fps (up to %d interpolated frames per game frame)", target, mult - 1); + else snprintf(buf, n, "x%d (%d interpolated frame%s per game frame)", mult, mult - 1, mult == 2 ? "" : "s"); + return buf; +} + +static int g_logged_mult, g_logged_target; static void log_arm_transition(int armed, int kind, int mult) { + const int target = atomic_load(&g_target); + char mode[96]; if (armed == g_was_armed) { - if (armed && mult != g_logged_mult) { - g_logged_mult = mult; - FGLOG("%s multiplier changed to x%d (%d interpolated frames per game frame)", fge_engine_name(kind), mult, mult - 1); + if (armed && (mult != g_logged_mult || target != g_logged_target)) { + g_logged_mult = mult; g_logged_target = target; + FGLOG("%s now %s", fge_engine_name(kind), describe_mode(mode, sizeof(mode), mult, target)); } return; } g_was_armed = armed; if (armed) { - g_logged_mult = mult; + g_logged_mult = mult; g_logged_target = target; float flow, hz; pthread_mutex_lock(&g_lock); flow = g_flow; hz = g_refresh_hz; pthread_mutex_unlock(&g_lock); - FGLOG("%s x%d armed (flow scale %.2f, panel %.0f Hz): real frames are presented one slot late " - "with the interpolated frames ahead of them", fge_engine_name(kind), mult, (double)flow, (double)hz); + FGLOG("%s %s armed (flow scale %.2f, panel %.0f Hz): real frames are presented one slot late " + "with the interpolated frames ahead of them", fge_engine_name(kind), + describe_mode(mode, sizeof(mode), mult, target), (double)flow, (double)hz); } else { FGLOG("frame generation off (%llu frames generated this session)", (unsigned long long)g_total_generated); g_generating_logged = 0; @@ -348,7 +367,8 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, if (atomic_exchange(&g_cfg_dirty, 0)) { float flow, hz; pthread_mutex_lock(&g_lock); flow = g_flow; hz = g_refresh_hz; pthread_mutex_unlock(&g_lock); - fge_configure((uint32_t)mult, flow, hz, atomic_load(&g_model), atomic_load(&g_preset)); + fge_configure((uint32_t)mult, (uint32_t)atomic_load(&g_target), flow, hz, + atomic_load(&g_model), atomic_load(&g_preset)); } if (!fge_prepare((uint32_t)w, (uint32_t)h, fmt)) { if (fmt != VK_FORMAT_R8G8B8A8_UNORM && fge_unavailable()) { @@ -426,8 +446,9 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, 0, 0, NULL, 0, NULL, nb, bars); if (!g_generating_logged) { g_generating_logged = 1; - FGLOG("generating: %s x%d at %dx%d (%u interpolated frame%s per game frame%s)", - fge_engine_name(kind), mult, w, h, n_gen, n_gen == 1 ? "" : "s", + char mode[96]; + FGLOG("generating: %s %s at %dx%d%s", fge_engine_name(kind), + describe_mode(mode, sizeof(mode), mult, atomic_load(&g_target)), w, h, fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? ", FP16: the HDR picture" : ""); } } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.h b/app/src/main/cpp/waylandcomp/src/framegen_bridge.h index 2d4d6d99a..b60229cdb 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.h +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.h @@ -34,9 +34,10 @@ enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_WINFG = 1 }; /* ---- app controls (any thread) ------------------------------------------------------- */ void vkp_framegen_set_engine(int kind); -/* multiplier 2..4; armed = 0 stops generating (the ring and the engine stay for a re-arm). */ -void vkp_framegen_set_armed(int armed, int multiplier); -/* LSFG Native: the SPIR-V cache built from the user's Lossless.dll (LsfgNative.ensureCache). */ +/* multiplier 2..4, or target_fps > 0 for LSFG's adaptive mode (up to 4x, as the target needs); + * armed = 0 stops generating (the ring and the engine stay for a re-arm). */ +void vkp_framegen_set_armed(int armed, int multiplier, int target_fps); +/* LSFG Native: the SPIR-V cache built from the user's Lossless.dll (Lossless.sync); a new path reloads the engine. */ void vkp_framegen_set_lsfg_cache_path(const char *path); /* Flow scale 0.25..1.0 and the panel's real refresh rate (the pacer never generates above it). */ void vkp_framegen_set_tuning(float flow_scale, float refresh_hz); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp index 1d9d29468..35e160edc 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp @@ -197,11 +197,11 @@ int fge_unavailable(void) { return g_lsfg && g_lsfg->unavailable() ? 1 : 0; } -void fge_configure(uint32_t multiplier, float flow_scale, float refresh_hz, int model, - int perf_preset) { +void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz, + int model, int perf_preset) { if (multiplier < 2) multiplier = 2; if (g_kind == 1 && g_winfg) g_winfg->configure(multiplier, model, perf_preset, flow_scale); - else if (g_lsfg) g_lsfg->configure(multiplier, 0, flow_scale, refresh_hz); + else if (g_lsfg) g_lsfg->configure(multiplier, target_fps, flow_scale, refresh_hz); } int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.h b/app/src/main/cpp/waylandcomp/src/framegen_engine.h index ecc9e30d1..b0deec70b 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.h +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.h @@ -45,8 +45,9 @@ int fge_start(int kind, const char *cache_path); void fge_stop(void); /* The engine came up but later found it cannot generate (chain build failed). */ int fge_unavailable(void); -void fge_configure(uint32_t multiplier, float flow_scale, float refresh_hz, int model, - int perf_preset); +/* target_fps > 0: LSFG picks 0..3 generations per frame to reach it (Win-FG ignores it). */ +void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz, + int model, int perf_preset); /* Build/rebuild the chain for this extent; the guest extent for the flow pyramid is the same * (the Wayland scene is the game's own size in fullscreen). 1 = chain valid. */ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c b/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c index 45bd27dff..dd4144d3e 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c @@ -17,8 +17,9 @@ int fge_format_ok(VkFormat fmt) { (void)fmt; return 0; } int fge_start(int kind, const char *cache_path) { (void)kind; (void)cache_path; return -1; } void fge_stop(void) {} int fge_unavailable(void) { return 1; } -void fge_configure(uint32_t multiplier, float flow_scale, float refresh_hz, int model, int perf_preset) { - (void)multiplier; (void)flow_scale; (void)refresh_hz; (void)model; (void)perf_preset; +void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz, int model, + int perf_preset) { + (void)multiplier; (void)target_fps; (void)flow_scale; (void)refresh_hz; (void)model; (void)perf_preset; } int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { (void)w; (void)h; (void)fmt; return 0; } uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) { diff --git a/app/src/main/cpp/waylandcomp/src/framegen_jni.c b/app/src/main/cpp/waylandcomp/src/framegen_jni.c index c693ad25c..8d5bad571 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_jni.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_jni.c @@ -14,9 +14,9 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenEngine(JN JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenArmed(JNIEnv *env, jclass clazz, - jboolean armed, jint multiplier) { + jboolean armed, jint multiplier, jint targetFps) { (void)env; (void)clazz; - vkp_framegen_set_armed(armed ? 1 : 0, (int)multiplier); + vkp_framegen_set_armed(armed ? 1 : 0, (int)multiplier, (int)targetFps); } JNIEXPORT void JNICALL diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index cd60fd351..1fcbf3357 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -85,6 +85,7 @@ static struct { #define ASC_VISIBILITY_HIDE 0 #define ASC_VISIBILITY_SHOW 1 +#define ASC_TRANSPARENCY_TRANSLUCENT 1 #define ASC_TRANSPARENCY_OPAQUE 2 static int load_api(void) { @@ -766,7 +767,8 @@ static ASurfaceControl *swap_sc_begin(struct layer *l) { /* The transaction that puts pool slot `idx` of layer `l` on screen at `r`, as `color` (NULL = no * description). 0 = applied. */ -static int present_slot(struct layer *l, int idx, const int r[8], const struct banner_color *color) { +static int present_slot(struct layer *l, int idx, const int r[8], const struct banner_color *color, + int translucent) { struct slot *s = &l->slots[idx]; ASurfaceTransaction *tx = api.txCreate(); if (!tx) return -1; @@ -774,9 +776,8 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct b if (old) api.setZOrder(tx, l->sc, l->z); /* The blit was waited for on the CPU, so no acquire fence is needed (-1). */ api.setBuffer(tx, l->sc, s->ahb, -1); - /* The compositor composes with blits, which overwrite: nothing is ever alpha-blended on the - * copy path either, so every layer is opaque and the picture matches it pixel for pixel. */ - api.setBufferTransparency(tx, l->sc, ASC_TRANSPARENCY_OPAQUE); + api.setBufferTransparency(tx, l->sc, + translucent ? ASC_TRANSPARENCY_TRANSLUCENT : ASC_TRANSPARENCY_OPAQUE); apply_geometry(tx, l, r); apply_frame_rate(tx, l); apply_colour(tx, l, color); @@ -883,7 +884,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd); if (idx < 0) { log_drop(l); return 0; } if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1; - if (present_slot(l, idx, r, color) != 0) return -1; + if (present_slot(l, idx, r, color, 0) != 0) return -1; if (color && color->dataspace) banner_color_frame_shown(color, BANNER_HDR_LAYER_COPY, AHB_RGBA8); if (!l->first_logged) { l->first_logged = 1; @@ -908,7 +909,7 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int int idx = take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd); if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; } if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1; - if (present_slot(l, idx, r, NULL) != 0) return -1; /* the effects chain's result is 8-bit sRGB */ + if (present_slot(l, idx, r, NULL, 0) != 0) return -1; /* the effects chain's result is 8-bit sRGB */ if (!l->first_logged) { l->first_logged = 1; banner_log("layer", "presenting %dx%d frames on their own SurfaceControl layer (%s pool, %d buffers); " @@ -950,7 +951,7 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct } if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; } if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1; - if (present_slot(l, idx, r, tm ? NULL : color) != 0) return -1; /* tone-mapped = plain sRGB: no tag */ + if (present_slot(l, idx, r, tm ? NULL : color, 0) != 0) return -1; /* tone-mapped = plain sRGB: no tag */ if (color && color->dataspace) banner_color_frame_shown(color, tm ? BANNER_HDR_TONEMAPPED : BANNER_HDR_COMPOSED, tm ? AHB_RGBA8 : g_hdr_pool_fmt); static int said = -1; @@ -1031,7 +1032,7 @@ int sc_layer_overlay_affordable(void) { return ok; } -int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]) { +int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) { struct layer *l = layer_of(SC_LAYER_OVERLAY); if (!src || !geo) return -1; /* The caller decides with sc_layer_overlay_affordable() BEFORE it commits the game to a layer; @@ -1046,7 +1047,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]) { /* The window is copied into the layer buffer 1:1; `geo` crops it and places it, so the layer * is exactly the window's rectangle on screen and nothing else is blended anywhere. */ if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1; - if (present_slot(l, idx, geo, NULL) != 0) return -1; + if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1; if (!l->first_logged) { l->first_logged = 1; log_layer_count(); diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.h b/app/src/main/cpp/waylandcomp/src/sc_layer.h index 94a6f9065..f2f12a704 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.h +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.h @@ -150,8 +150,9 @@ int sc_layer_overlay_affordable(void); /* OVERLAY layer: show `src` (one window's imported frame) above the game layer, at the placement * `geo` = {src x0,y0,x1,y1 in image pixels, dst x0,y0,x1,y1 in output pixels} from vkp_map_draw. + * `translucent` preserves a client's alpha over the game for Steam notifications and overlays. * 0 = shown or dropped, -1 = unavailable (the caller must fall back to the copy path). */ -int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]); +int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent); /* The scene is not a single fullscreen window this frame: hide every layer that is up. */ void sc_layer_hide(void); diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 8c1d897fc..7a2ecfd48 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -7,6 +7,7 @@ #include "effects_chain.h" #include "framegen_bridge.h" #include "hdr_compose.h" +#include "blend_pass.h" #include "banner_color.h" #include #include @@ -32,6 +33,8 @@ struct vkp_image { void *map; /* shm images: persistently mapped linear memory */ VkDeviceSize offset, row_pitch; int in_general; /* shm images: moved from PREINITIALIZED to GENERAL */ + VkFormat fmt; + int sampled; /* created with SAMPLED usage: the alpha pass can read it */ }; static ANativeWindow *g_window; /* the window frames go to; compositor thread only */ @@ -230,6 +233,7 @@ static void destroy_swapchain(void) { if (g_dev_state != 1) return; g_vk.DeviceWaitIdle(g_dev); reset_sync(); + for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]); if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL); g_swapchain = VK_NULL_HANDLE; g_swap_md_identity = 0; /* a new swapchain gets the metadata again */ @@ -525,6 +529,7 @@ static int dev_init(void) { vkp_effects_bind_device(g_dev, g_pd, &g_memprops); hdrc_bind_device(g_dev, &g_memprops); + blendp_bind_device(g_dev); g_dev_state = 1; reset_sync(); init_black_image(); @@ -873,9 +878,8 @@ const char *vkp_modifier_name(uint64_t modifier) { return other; } -/* Can the driver create the image vkp_image_import_dmabuf() creates for this format+modifier - * (2D, DRM_FORMAT_MODIFIER tiling, TRANSFER_SRC, dma-buf memory) - and import it? */ -static int modifier_importable(VkFormat fmt, uint64_t modifier) { +/* Can the driver create and import this format/modifier with the requested image usage? */ +static int modifier_importable(VkFormat fmt, uint64_t modifier, VkImageUsageFlags usage) { if (!g_vk.GetPhysicalDeviceImageFormatProperties2) return 1; /* can't ask; the create will tell */ VkPhysicalDeviceExternalImageFormatInfo ext = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO, @@ -886,7 +890,7 @@ static int modifier_importable(VkFormat fmt, uint64_t modifier) { VkPhysicalDeviceImageFormatInfo2 info = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, .pNext = &mod, .format = fmt, .type = VK_IMAGE_TYPE_2D, .tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT, - .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT}; + .usage = usage}; VkExternalImageFormatProperties extp = {.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES}; VkImageFormatProperties2 props = {.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2, .pNext = &extp}; if (g_vk.GetPhysicalDeviceImageFormatProperties2(g_pd, &info, &props) != VK_SUCCESS) return 0; @@ -914,7 +918,7 @@ int vkp_dmabuf_modifiers(uint32_t drm_format, uint64_t *out, int max) { if (m != VKP_MOD_LINEAR && m != VKP_MOD_QCOM_COMPRESSED) why = "unknown layout"; else if (props[i].drmFormatModifierPlaneCount != 1) why = "not single-plane"; else if (!(props[i].drmFormatModifierTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) why = "no blit source"; - else if (!modifier_importable(fmt, m)) why = "not importable as a dma-buf"; + else if (!modifier_importable(fmt, m, VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) why = "not importable as a dma-buf"; if (why) { LOGI("dmabuf: %c%c%c%c %s reported by the driver but not advertised: %s", drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, @@ -942,6 +946,10 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t struct vkp_image *img = calloc(1, sizeof(*img)); if (!img) return NULL; img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0; + img->fmt = drm_to_vk(drm_format); + const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 && + modifier_importable(img->fmt, modifier, sampled_usage); VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride}; VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = { @@ -952,10 +960,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT}; VkImageCreateInfo ici = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &extImg, - .imageType = VK_IMAGE_TYPE_2D, .format = drm_to_vk(drm_format), .extent = {w, h, 1}, + .imageType = VK_IMAGE_TYPE_2D, .format = img->fmt, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT, - .usage = as_blit_dst ? VK_IMAGE_USAGE_TRANSFER_DST_BIT : VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + .usage = as_blit_dst ? VK_IMAGE_USAGE_TRANSFER_DST_BIT + : img->sampled ? sampled_usage : VK_IMAGE_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED}; VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image); if (cr != VK_SUCCESS) { @@ -1008,18 +1017,35 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t return img; } +/* Linear wl_shm images can use the blend pass only if the driver samples them with a linear filter. */ +static int shm_sampled(void) { + static int known; + if (!known) { + const VkFormatFeatureFlags need = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | + VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; + VkFormatProperties2 fp = {.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2}; + if (g_vk.GetPhysicalDeviceFormatProperties2) + g_vk.GetPhysicalDeviceFormatProperties2(g_pd, VK_FORMAT_B8G8R8A8_UNORM, &fp); + known = (fp.formatProperties.linearTilingFeatures & need) == need ? 1 : -1; + } + return known == 1; +} + struct vkp_image *vkp_image_create_shm(int w, int h) { if (w <= 0 || h <= 0 || dev_init() != 0) return NULL; struct vkp_image *img = calloc(1, sizeof(*img)); if (!img) return NULL; img->w = w; img->h = h; + img->fmt = VK_FORMAT_B8G8R8A8_UNORM; + img->sampled = shm_sampled(); VkImageCreateInfo ici = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, - .format = VK_FORMAT_B8G8R8A8_UNORM, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1, + .format = img->fmt, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_LINEAR, - .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0), + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED}; if (g_vk.CreateImage(g_dev, &ici, NULL, &img->image) != VK_SUCCESS) { free(img); return NULL; } @@ -1062,6 +1088,7 @@ int vkp_image_height(const struct vkp_image *img) { return img ? img->h : 0; } void vkp_image_destroy(struct vkp_image *img) { if (!img) return; if (g_dev) { + blendp_forget_image(img->image); if (img->map) g_vk.UnmapMemory(g_dev, img->mem); if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL); if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL); @@ -1111,8 +1138,21 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h return map_draw(d, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, (float)scene_w, (float)scene_h, blit); } +/* A translucent draw needs source-over blending; every other draw keeps the existing blit path. */ +static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target, + VkFormat target_fmt, int target_w, int target_h, VkFilter filter) { + const struct vkp_image *im = d->img; + if (d->blend && im->sampled && + blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h, + blit) == 0) + return; + g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, + target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter); +} + static void destroy_scene_image(void) { if (g_scene.img) hdrc_forget_image(g_scene.img); /* the HDR pass may have drawn into it */ + if (g_scene.img) blendp_forget_image(g_scene.img); if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL); if (g_scene.mem) g_vk.FreeMemory(g_dev, g_scene.mem, NULL); memset(&g_scene, 0, sizeof(g_scene)); @@ -1150,6 +1190,7 @@ static int ensure_scene_image(int w, int h) { static int ensure_img(struct vkp_img_slot *s, int w, int h, VkFormat fmt, VkImageUsageFlags usage, const char *what) { if (s->img && s->w == w && s->h == h && s->fmt == fmt) return 0; if (s->img) hdrc_forget_image(s->img); + if (s->img) blendp_forget_image(s->img); if (s->img) g_vk.DestroyImage(g_dev, s->img, NULL); if (s->mem) g_vk.FreeMemory(g_dev, s->mem, NULL); memset(s, 0, sizeof(*s)); @@ -1190,7 +1231,8 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n, int scene_w, int scene_h, VkImage out, VkFormat out_fmt, enum hdrc_mode mode) { if (!hf || !hf->is_hdr || n <= 0) return -1; if (ensure_img(&g_mixed, scene_w, scene_h, HDR_FMT, - VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, "HDR composition (mixed)") != 0) return -1; VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; @@ -1214,9 +1256,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n, VkImageBlit blit; if (!draws[i].img || !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit)) continue; /* A blit converts UNORM to UNORM by value: 8-bit sRGB and 10-bit PQ both land unchanged. */ - g_vk.CmdBlitImage(cmd, draws[i].img->image, - draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, - g_mixed.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR); + record_draw(cmd, &draws[i], &blit, g_mixed.img, HDR_FMT, scene_w, scene_h, VK_FILTER_LINEAR); if (hf->is_hdr[i] && lowest_hdr < 0) lowest_hdr = i; } static int truncated_said; @@ -1249,6 +1289,7 @@ static void device_lost(const char *where) { vkp_framegen_device_lost(); banner_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; " "restart the session", where); + for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]); if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL); g_swapchain = VK_NULL_HANDLE; if (g_surface) g_vk.DestroySurfaceKHR(g_inst, g_surface, NULL); @@ -1547,6 +1588,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(cmd, &bi); + blendp_begin_frame(); VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; /* Source images: take dmabufs from the client's queue family, move shm images to @@ -1589,8 +1631,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i free(bars); /* Clear the composition target to black (the letterbox on the direct path, the desktop's - * background on the pass) before the draws land on it. A draw that covers the whole scene - * overwrites every pixel of its rectangle (blits never blend), so then only what lies outside it + * background on the pass) before the draws land on it. An opaque draw that covers the whole scene + * overwrites every pixel of its rectangle, so then only what lies outside it * needs black: the letterbox bars on the direct path, nothing at all on the pass (the scene image * is exactly the scene). Anything else - no such draw, the HDR composition - clears the whole * target as before. */ @@ -1600,7 +1642,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (!(hf && pass)) { for (int i = n - 1; i >= 0 && !covered; i--) { const struct vkp_draw *d = &draws[i]; - if (!d->img || d->dx > 0 || d->dy > 0 || d->dx + d->dw < scene_w || d->dy + d->dh < scene_h) continue; + if (!d->img || d->blend || d->dx > 0 || d->dy > 0 || d->dx + d->dw < scene_w || + d->dy + d->dh < scene_h) continue; covered = pass ? draw_to_scene_blit(d, scene_w, scene_h, &cover_blit) : draw_to_blit(d, &cover_blit); } } @@ -1633,10 +1676,9 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i VkImageBlit blit; if (!draws[i].img) continue; if (pass ? !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit) : !draw_to_blit(&draws[i], &blit)) continue; - g_vk.CmdBlitImage(cmd, draws[i].img->image, - draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, - target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, - pass ? VK_FILTER_LINEAR : blit_filter); + record_draw(cmd, &draws[i], &blit, target, pass ? scene_fmt : g_swap_fmt, + pass ? scene_w : (int)g_extent.width, pass ? scene_h : (int)g_extent.height, + pass ? VK_FILTER_LINEAR : blit_filter); drawn++; } @@ -2073,6 +2115,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(cmd, &bi); + blendp_begin_frame(); VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; /* Same acquisition as vkp_render's compositor pass: the sources come from the client's queue @@ -2132,9 +2175,8 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw for (int i = 0; i < n; i++) { VkImageBlit blit; if (!draws[i].img || !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit)) continue; - g_vk.CmdBlitImage(cmd, draws[i].img->image, - draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, - g_scene.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR); + record_draw(cmd, &draws[i], &blit, g_scene.img, SCENE_FMT, scene_w, scene_h, + VK_FILTER_LINEAR); } if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM); } diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.h b/app/src/main/cpp/waylandcomp/src/vk_present.h index 899736520..eef9c80cc 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.h +++ b/app/src/main/cpp/waylandcomp/src/vk_present.h @@ -79,6 +79,7 @@ struct vkp_draw { struct vkp_image *img; float sx, sy, sw, sh; int dx, dy, dw, dh; + int blend; /* translucent: composed over what is under it (blend_pass.h) */ }; // The GPU the renderer runs on ("Adreno (TM) 750"), empty before the device is up. diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 10283f570..414ca45b9 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -6,6 +6,7 @@ */ #include #include +#include #include #include #include @@ -25,6 +26,7 @@ extern int banner_wayland_run(void); extern void banner_wayland_send_pointer(int action, int x, int y); extern void banner_wayland_send_touch(int action, int pointer_id, int x, int y); extern int banner_cursor_snapshot(int *out, int cap); +extern int banner_cursor_serial(void); extern void banner_wayland_send_key(int evdev, int state); extern void banner_wayland_send_scene_input(int type, int a, int b); extern void banner_wayland_vsync(int64_t frame_time_ns); @@ -294,6 +296,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot( return n; } +/* The serial nativeCursorSnapshot would return, without copying anything. */ +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) { + (void)env; (void)clazz; + return banner_cursor_serial(); +} + /* Inject a key event. evdev = Linux input keycode (KEY_A=30…); state 1=down 0=up. */ JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey( @@ -670,3 +679,29 @@ JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIEnv *env, jclass clazz, jint before, jint after) { banner_host_text_delete(before, after); } + +/* KGSL's power control, off (the GPU held at its top clock) or back on. The property is the + * device's, not this process's: it outlives the fd and the app, so the caller clears it at stop + * and again at every app start. No root; the kernel's thermal limits still apply. */ +extern void adrenotools_set_turbo(bool turbo); +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) { + (void)env; (void)clazz; + adrenotools_set_turbo(on == JNI_TRUE); +} + +/* Raises one of our own processes or threads to `nice` with a bare setpriority(), never lowering + * it. android.os.Process.setThreadPriority is not used for this: it also moves the thread between + * scheduling groups by priority, and a guest process must stay where Android put the app. Returns + * the nice value it is left at, or 100 when it could not be read. */ +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeRaisePriority(JNIEnv *env, jclass clazz, jint tid, jint nice) { + (void)env; (void)clazz; + errno = 0; + int before = getpriority(PRIO_PROCESS, (id_t)tid); + if (before == -1 && errno != 0) return 100; + if (before > nice) setpriority(PRIO_PROCESS, (id_t)tid, nice); + errno = 0; + int after = getpriority(PRIO_PROCESS, (id_t)tid); + return after == -1 && errno != 0 ? 100 : after; +} diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index e1764bc57..7cc6db7d6 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -1,12 +1,23 @@ package com.droiddeck.launcher import android.app.Application +import com.droiddeck.launcher.runtime.BwrapSpawner import com.droiddeck.launcher.session.CrashHandler +import com.droiddeck.launcher.session.GpuClockPin -/** Process-wide setup: the crash handler, so a session's folder is finished even when we die. */ +/** + * Process-wide setup: the crash handler, so a session's folder is finished even when we die, and + * the GPU clock pin cleared in case a killed process left it set, and the socket Flatpak's + * sandboxes are started through (BwrapSpawner). + */ class App : Application() { override fun onCreate() { super.onCreate() CrashHandler.install(this) + // 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) + GpuClockPin.clearLeftover(this) + BwrapSpawner.start(this) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt index 3cbb18656..87c3f2790 100644 --- a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt @@ -16,7 +16,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat var compCatalog by mutableStateOf>(emptyList()) var compCatalogAt by mutableStateOf(0L) var compProton by mutableStateOf(null) - var compComp by mutableStateOf("dxvk") + var compComp by mutableStateOf(com.droiddeck.launcher.ui.GPU_TAB) var compChecking by mutableStateOf(false) var compBusy by mutableStateOf(null) var compDownloads by mutableStateOf>(emptyMap()) diff --git a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt index 88c2e8853..ff5ce18fe 100644 --- a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt +++ b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt @@ -10,6 +10,10 @@ import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.runtime.mutableIntStateOf +import com.droiddeck.launcher.gpu.DriverBundle +import com.droiddeck.launcher.gpu.DriverPairs +import com.droiddeck.launcher.gpu.GpuInfo import com.droiddeck.launcher.gpu.LinuxVulkanDriver import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager import com.droiddeck.launcher.gpu.TurnipDriver @@ -17,11 +21,16 @@ import com.droiddeck.launcher.gpu.TurnipReleases import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.ui.DriverRow +import com.droiddeck.launcher.ui.GpuDriversState +import com.droiddeck.launcher.ui.PairRow +import com.droiddeck.launcher.wayland.CompositorHost /** - * The Linux and Android driver menus: the drivers each can pick from, the release downloads the - * last check found, and what each mode is set to. The launcher screen keeps one and hands its - * rows to the mode settings dialog. + * The GPU drivers: what this GPU is, the matched driver pairs the release repos offer for it, and + * - in Auto, the default - keeping the recommended pair installed and set. Under Advanced, the + * Linux (runtime) and Android (display) lists as before, each picked on its own - except a + * bundle's two halves (DriverBundle), which are always picked, and deleted, together. The launcher + * screen keeps one and hands it to the Components page's GPU drivers tab. */ internal class DriverMenus(private val activity: Activity, private val ui: Handler) { var linuxRows by mutableStateOf>(emptyList()) @@ -33,17 +42,42 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl var canRestoreBundled by mutableStateOf(false) /** Asset name -> download percent, while it downloads. */ private val releaseProgress = HashMap() - var linuxSteam by mutableStateOf("") - var linuxDesktop by mutableStateOf("") + var linuxSelected by mutableStateOf("") + val gpu: GpuInfo = GpuInfo.detect() + // Read in refreshDrivers/ensureAuto: the activity has no context yet while its fields are made. + var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO) + var pairRows by mutableStateOf>(emptyList()) + /** The pair being installed, and how far along. */ + var pairBusy by mutableStateOf(null) + var pairPercent by mutableIntStateOf(-1) + /** What Auto last did or found, for the line under the pair in use. */ + var autoStatus by mutableStateOf("") + /** The bundle both drivers are set to, as "DD-Turnip 0.1.0", or null when they are not one. */ + var activeBundle by mutableStateOf(null) + private var autoCheckedThisProcess = false + + fun state() = GpuDriversState( + gpuName = gpu.name, gpuFamily = gpu.family.label, soc = gpu.soc, supportText = gpu.supportText, + supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED, + auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent, + autoStatus = autoStatus, releaseStatus = releaseStatus, checking = releaseChecking, + linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected, + linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled, + activeBundle = activeBundle, + ) var androidRows by mutableStateOf>(emptyList()) var androidSelected by mutableStateOf("") fun refreshDrivers() { val lm = LinuxVulkanDriverManager(activity) fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED + val bundles = DriverBundle.all(activity) + fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let { + DriverRow(id, it.label, "Android + Linux: sets the ${if (linux) "display" else "runtime"} driver with it", true, DriverRow.BUNDLE) + } linuxRows = LinuxVulkanDriver.optionValues(activity).map { id -> if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false) - else DriverRow( + else bundleRow(id, linux = true) ?: DriverRow( id, lm.getDriverName(id), listOfNotNull( lm.getDriverVersion(id).takeIf { it.isNotEmpty() }, @@ -52,8 +86,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl true, origin(id), ) } - linuxSteam = SessionPrefs.linuxDriver(activity, SessionService.MODE_STEAM) - linuxDesktop = SessionPrefs.linuxDriver(activity, SessionService.MODE_DESKTOP) + linuxSelected = SessionPrefs.linuxDriver(activity) + mode = SessionPrefs.gpuDriverMode(activity) val td = TurnipDriver(activity) val auto = td.autoId() androidRows = buildList { @@ -63,23 +97,211 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl false, )) for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED)) - for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id))) + for (id in td.enumerateImported()) add(bundleRow(id, linux = false) ?: DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id))) } canRestoreBundled = td.hiddenBundled().isNotEmpty() androidSelected = SessionPrefs.androidDriver(activity) + activeBundle = DriverBundle.active(activity)?.label refreshReleaseRows() + refreshPairs() + } + + /** One line for the settings row that opens this: "Auto · WinNative · Balanced". */ + fun summary(): String { + val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle + return (if (mode == SessionPrefs.GPU_DRIVERS_AUTO) "Auto" else "Manual") + (active?.let { " · $it" } ?: "") + } + + /** The pairs the last check found, with what is installed and in use; this GPU's first. */ + fun refreshPairs() { + val lm = LinuxVulkanDriverManager(activity) + val td = TurnipDriver(activity) + val pairs = DriverPairs.from(TurnipReleases.cached(activity)) + val recommended = DriverPairs.recommendedKey(gpu, pairs) + pairRows = pairs.map { p -> + val bundle = p.bundle?.let { installedBundle(it) } + val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) } + val linuxId = if (p.bundle != null) bundle?.linuxId else p.linux?.let { TurnipReleases.installedId(activity, it, lm::isInstalled) } + val mb = p.assets.sumOf { it.size } / 1_048_576.0 + PairRow( + key = p.key, name = p.name, version = p.version, + detail = if (!p.complete) "Only one half is published right now" else "%.0f MB for both".format(mb), + recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete, + installed = displayId != null && linuxId != null, + active = displayId != null && linuxId != null && + SessionPrefs.androidDriver(activity) == displayId && SessionPrefs.linuxDriver(activity) == linuxId, + ) + }.sortedByDescending { it.recommended } + } + + fun setMode(auto: Boolean) { + mode = if (auto) SessionPrefs.GPU_DRIVERS_AUTO else SessionPrefs.GPU_DRIVERS_MANUAL + SessionPrefs.setGpuDriverMode(activity, mode) + autoStatus = "" + if (auto) ensureAuto(force = false) + } + + /** + * Auto: make the recommended pair for this GPU the one installed and set. Looks online when + * [force]d (refresh), or when the last check is a day old - Banners-Turnip rebuilds hourly, and + * a new pair a day is plenty - otherwise works from the last check. Once per app start on its + * own; the pair it replaces is removed, anything the user imported or picked is left alone. + */ + fun ensureAuto(force: Boolean) { + mode = SessionPrefs.gpuDriverMode(activity) + if (mode != SessionPrefs.GPU_DRIVERS_AUTO || pairBusy != null || releaseChecking) return + if (!force && autoCheckedThisProcess) return + autoCheckedThisProcess = true + if (DriverPairs.recommendedKey(gpu, emptyList()) == null) { + autoStatus = "No drivers to set: ${gpu.supportText.lowercase()}" + return + } + releaseChecking = true + autoStatus = "Checking for the latest drivers…" + Thread({ + val cached = TurnipReleases.cached(activity) + val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L || + cached.assets.none { it.pair.isNotEmpty() } + val problem = if (force || stale) runCatching { TurnipReleases.refresh(activity) }.exceptionOrNull()?.message else null + ui.post { + releaseChecking = false + refreshReleaseRows() + refreshPairs() + val pairs = DriverPairs.from(TurnipReleases.cached(activity)) + val key = DriverPairs.recommendedKey(gpu, pairs) + val pair = pairs.firstOrNull { it.key == key } + val row = pairRows.firstOrNull { it.key == key } + when { + row?.active == true -> autoStatus = "Up to date" + (problem?.let { " (couldn't check: $it)" } ?: "") + pair == null || !pair.complete -> + autoStatus = problem?.let { "Couldn't check: $it" } ?: "The recommended drivers aren't published right now" + else -> installPair(pair, auto = true) + } + } + }, "gpu-driver-auto").start() + } + + /** Manual: install (if need be) and set both halves of a pair. */ + fun selectPair(key: String) { + if (pairBusy != null) return + val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return + installPair(pair, auto = false) + } + + /** + * Download what is missing of [pair], then set both halves - only once both are in, so a + * failed download never leaves a half-changed pair. Auto's own downloads are recorded, and the + * ones the new pair replaces are removed. + */ + private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean) { + if (!pair.complete) return + pairBusy = pair.key + pairPercent = 0 + if (auto) autoStatus = "Downloading ${pair.name} ${pair.version}…" + Thread({ + val lm = LinuxVulkanDriverManager(activity) + val td = TurnipDriver(activity) + var downloaded = false + val result = runCatching { + val zips = pair.assets + val ids = zips.mapIndexed { i, asset -> + installedIdOf(asset) + ?: installAsset(asset) { pct -> ui.post { pairPercent = (i * 100 + pct) / zips.size } }.also { downloaded = true } + } + if (pair.bundle != null) DriverBundle.get(activity, ids[0])!!.let { listOf(it.androidId, it.linuxId) } else ids + } + ui.post { + pairBusy = null + pairPercent = -1 + result.onSuccess { (displayId, linuxId) -> + val displayChanged = SessionPrefs.androidDriver(activity) != displayId + SessionPrefs.setAndroidDriver(activity, displayId) + SessionPrefs.setLinuxDriver(activity, linuxId) + val restart = if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else "" + if (auto) { + val previous = SessionPrefs.gpuAutoInstalled(activity) + for (id in previous - setOf(displayId, linuxId)) { + val bundle = DriverBundle.containing(activity, id, lm.isInstalled(id)) + when { + bundle != null -> { DriverBundle.remove(activity, bundle); TurnipReleases.forget(activity, bundle.id) } + lm.isInstalled(id) -> lm.removeDriver(id) + else -> td.remove(id) + } + TurnipReleases.forget(activity, id) + } + SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId)) + autoStatus = (if (downloaded) "Updated to" else "Switched to") + " ${pair.name} ${pair.version}.$restart" + } else { + android.widget.Toast.makeText(activity, "Using ${pair.name} ${pair.version}.$restart", android.widget.Toast.LENGTH_LONG).show() + } + }.onFailure { e -> + Log.w(TAG, "driver pair ${pair.key}", e) + val why = if (e is IllegalArgumentException) e.message else "Download failed: ${e.message}" + if (auto) autoStatus = why ?: "Download failed" + else android.widget.Toast.makeText(activity, why, android.widget.Toast.LENGTH_LONG).show() + } + refreshDrivers() + } + }, "gpu-driver-pair").start() + } + + /** The bundle a release bundle was downloaded as, while both its halves are installed. */ + private fun installedBundle(asset: TurnipReleases.Asset): DriverBundle.Bundle? = + TurnipReleases.installedId(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) } + + /** The id a release asset was installed as (a bundle's id for a bundle), or null when it is not installed. */ + private fun installedIdOf(asset: TurnipReleases.Asset): String? = when { + asset.bundle -> installedBundle(asset)?.id + asset.linux -> TurnipReleases.installedId(activity, asset, LinuxVulkanDriverManager(activity)::isInstalled) + else -> TurnipReleases.installedId(activity, asset, TurnipDriver(activity)::isInstalled) + } + + /** + * One release asset, downloaded, checked and installed through the importer; returns its id, + * a bundle's id for a bundle. + */ + private fun installAsset(asset: TurnipReleases.Asset, progress: (Int) -> Unit): String { + var file: File? = null + try { + file = TurnipReleases.download(activity, asset, progress) + val uri = Uri.fromFile(file) + val id = when { + asset.bundle -> DriverBundle.install(activity, uri).id + asset.linux -> LinuxVulkanDriverManager(activity).installDriver(uri, asset.name) + else -> TurnipDriver(activity).installFromZip(uri, asset.name) + } + TurnipReleases.recordDownload(activity, asset, id) + return id + } finally { + file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) } + } } /** * Import off the main thread - a driver zip is a few MB and the glibc check reads the whole - * library - then say what happened. A refusal's message is the user-facing reason. + * library - then say what happened. A refusal's message is the user-facing reason. A bundle, + * from any import, installs both halves and is set as both drivers at once. [linux] null (the + * tab's own Import .zip) takes a single driver to whichever list its libc belongs in. */ - fun importDriver(uri: Uri, linux: Boolean) { + fun importDriver(uri: Uri, linux: Boolean?) { val name = activity.displayNameOf(uri) Thread({ + var bundle: DriverBundle.Bundle? = null val problem = try { - if (linux) LinuxVulkanDriverManager(activity).installDriver(uri, name) - else TurnipDriver(activity).installFromZip(uri, name) + when { + DriverBundle.isBundle(activity, uri) -> bundle = DriverBundle.install(activity, uri) + linux == true -> LinuxVulkanDriverManager(activity).installDriver(uri, name) + linux == false -> TurnipDriver(activity).installFromZip(uri, name) + else -> try { + TurnipDriver(activity).installFromZip(uri, name) + } catch (display: IllegalArgumentException) { + try { + LinuxVulkanDriverManager(activity).installDriver(uri, name) + } catch (runtime: IllegalArgumentException) { + throw IllegalArgumentException("Not a driver zip: neither an AdrenoTools driver, a -Linux Turnip nor an Android + Linux bundle") + } + } + } null } catch (e: IllegalArgumentException) { e.message @@ -88,26 +310,57 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl "Import failed: ${e.message}" } ui.post { + val done = bundle?.let { useBundle(it) } ?: "Imported ${name ?: "driver"}" android.widget.Toast.makeText( - activity, problem ?: "Imported ${name ?: "driver"}", - if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT, + activity, problem ?: done, + if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT, ).show() refreshDrivers() } }, "import-driver").start() } + /** + * Pick one driver from a list, which is Manual (Auto would put its pair back). A bundle's half + * sets the bundle's other half in the other list as well. + */ + fun selectDriver(id: String, linux: Boolean) { + val bundle = DriverBundle.containing(activity, id, linux) + when { + bundle != null -> useBundle(bundle) + linux -> SessionPrefs.setLinuxDriver(activity, id) + else -> SessionPrefs.setAndroidDriver(activity, id) + } + setMode(false) + refreshDrivers() + } + + /** Set both halves of [bundle] as the drivers in use; returns what to tell the user. */ + private fun useBundle(bundle: DriverBundle.Bundle): String { + val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId + DriverBundle.select(activity, bundle) + if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false) + return "Using ${bundle.label} as both the runtime and display driver." + + if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else "" + } + /** * Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a * session never starts on a driver that is gone; a release download is forgotten, so the menu * offers it again. */ fun deleteDriver(id: String, linux: Boolean) { + val bundle = DriverBundle.containing(activity, id, linux) + if (bundle != null) { + DriverBundle.remove(activity, bundle) + TurnipReleases.forget(activity, bundle.id) + android.widget.Toast.makeText(activity, "Deleted ${bundle.label} (both drivers)", android.widget.Toast.LENGTH_SHORT).show() + refreshDrivers() + return + } if (linux) { LinuxVulkanDriverManager(activity).removeDriver(id) - for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) { - if (SessionPrefs.linuxDriver(activity, mode) == id) SessionPrefs.setLinuxDriver(activity, mode, "") - } + if (SessionPrefs.linuxDriver(activity) == id) SessionPrefs.setLinuxDriver(activity, "") } else { val td = TurnipDriver(activity) if (id in TurnipDriver.BUNDLED) td.hideBundled(id) else td.remove(id) @@ -121,11 +374,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl /** The download entries and the refresh line, from what the last check found. */ fun refreshReleaseRows() { val check = TurnipReleases.cached(activity) - val lm = LinuxVulkanDriverManager(activity) - val td = TurnipDriver(activity) fun rows(linux: Boolean) = check?.assets.orEmpty() - .filter { it.linux == linux } - .filter { a -> TurnipReleases.installedId(activity, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null } + .filter { it.bundle || it.linux == linux } + .filter { a -> installedIdOf(a) == null } .map { a -> val mb = "%.1f MB".format(a.size / 1_048_576.0) com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name]) @@ -154,7 +405,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl fun checkLatestTurnip() { if (releaseChecking) return releaseChecking = true - releaseStatus = "Checking Banners-Turnip and WinNative…" + releaseStatus = "Checking Banners-Turnip, WinNative and DroidDeck…" Thread({ val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) { Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed" @@ -162,6 +413,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl ui.post { releaseChecking = false refreshReleaseRows() + refreshPairs() if (problem != null) releaseStatus = "Couldn't check: $problem" } }, "turnip-release-check").start() @@ -174,28 +426,20 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl releaseProgress[assetName] = 0 refreshReleaseRows() Thread({ - var file: java.io.File? = null val problem = try { - file = TurnipReleases.download(activity, asset) { pct -> - ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() } - } - val uri = Uri.fromFile(file) - val id = if (asset.linux) LinuxVulkanDriverManager(activity).installDriver(uri, asset.name) - else TurnipDriver(activity).installFromZip(uri, asset.name) - TurnipReleases.recordDownload(activity, asset, id) + installAsset(asset) { pct -> ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() } } null } catch (e: IllegalArgumentException) { e.message } catch (e: Exception) { Log.w(TAG, "release driver download", e) "Download failed: ${e.message}" - } finally { - file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) } } ui.post { releaseProgress.remove(assetName) + val pick = if (asset.bundle) "pick it in either list to set both drivers" else "pick it in the menu" android.widget.Toast.makeText( - activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu", + activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - $pick", android.widget.Toast.LENGTH_LONG, ).show() refreshDrivers() diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index eaec48d8f..8c82ed818 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher +import androidx.compose.foundation.layout.fillMaxSize import android.Manifest import android.app.ActivityOptions import android.content.Intent @@ -27,7 +28,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.toArgb import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.gpu.TurnipDriver -import com.droiddeck.launcher.gpu.LsfgNative +import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.DesktopCatalog import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller @@ -38,6 +39,7 @@ import com.droiddeck.launcher.session.OfflineMode import com.droiddeck.launcher.session.ProtonExtras import com.droiddeck.launcher.session.ComponentsManager import com.droiddeck.launcher.ui.ComponentsPage +import com.droiddeck.launcher.session.GameSaves import com.droiddeck.launcher.session.SessionLogShare import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.ui.ProtonPage @@ -45,6 +47,7 @@ import com.droiddeck.launcher.core.CpuCores import com.droiddeck.launcher.core.PhantomProcessLimit import com.droiddeck.launcher.core.PhantomProcessStatus import com.droiddeck.launcher.core.WirelessAdbFix +import com.droiddeck.launcher.core.WirelessAdbPairingService import com.droiddeck.launcher.ui.CoreRow import com.droiddeck.launcher.ui.PerformancePage import com.droiddeck.launcher.ui.ModeSettingsPage @@ -55,7 +58,6 @@ import com.droiddeck.launcher.ui.ControllerActions import com.droiddeck.launcher.ui.ControllerMappingPage import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.ControllerEditorActivity -import com.droiddeck.launcher.ui.CreditsDialog import com.droiddeck.launcher.ui.FrontEndScreen import com.droiddeck.launcher.ui.FrontEndState import com.droiddeck.launcher.ui.FrontEndActions @@ -80,6 +82,7 @@ class MainActivity : ComponentActivity() { private val drivers = DriverMenus(this, ui) private val components = ComponentsMenu(this, ui) private val decky = DeckyMenu(this, ui) + private val updates = UpdatesMenu(this, ui) private val protons = ProtonMenu(this, ui) // The screen's state. Compose redraws whatever reads these when they change. @@ -88,6 +91,9 @@ class MainActivity : ComponentActivity() { private var flood by mutableStateOf(null) private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f) private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent) + /** A session stopped behind a flood: its blue, drawn back into the button it started from (FloodReturn). */ + private var returning by mutableStateOf(null) + private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?) private var ready by mutableStateOf(false) private var available by mutableStateOf(null) private var busy by mutableStateOf(false) @@ -95,17 +101,22 @@ class MainActivity : ComponentActivity() { private var percent by mutableIntStateOf(-1) private var failed by mutableStateOf(false) private var frameGenLabel by mutableStateOf("Off") + private var lossless by mutableStateOf(Lossless.State.NONE) private var showRemove by mutableStateOf(false) private var showNonAdreno by mutableStateOf(null) private var glThread by mutableStateOf(true) private var noGlError by mutableStateOf(true) private var steamDeckMode by mutableStateOf(false) - private var showCredits by mutableStateOf(false) + private var mangoapp by mutableStateOf(true) + private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK) private var showProtons by mutableStateOf(false) // Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager). private var showComponents by mutableStateOf(false) private var focusComponentsContent by mutableStateOf(true) private var showMapping by mutableStateOf(false) + private var saveBusy: String? = null + /** What to do with the zip or folder the file picker hands back after a game page's Manage saves. */ + private var onSavePicked: ((File) -> Unit)? = null private var controllerSettings by mutableStateOf(null) private var catalog by mutableStateOf?>(null) private var catalogLoading by mutableStateOf(false) @@ -122,8 +133,11 @@ class MainActivity : ComponentActivity() { private var gameCores by mutableStateOf>(emptySet()) private var tuSysmem by mutableStateOf(false) private var zinkLazy by mutableStateOf(false) - private var noXalia by mutableStateOf(false) + private var noXalia by mutableStateOf(true) + private var gamescopeRealtime by mutableStateOf(false) + private var gpuClockPin by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false) + private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME) private var phantomWarning by mutableStateOf(null) private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE) private var showPhantomGate by mutableStateOf(false) @@ -131,6 +145,8 @@ class MainActivity : ComponentActivity() { private var clientDirectAudio by mutableStateOf(false) private var forceFullscreen by mutableStateOf(true) private var launcherFullscreen by mutableStateOf(true) + private var storeEnabled by mutableStateOf(false) + private var appImagesEnabled by mutableStateOf(false) private var mic by mutableStateOf(false) // The app's own picker (files/), once per kind of pick: the two driver lists validate @@ -144,6 +160,68 @@ class MainActivity : ComponentActivity() { private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = false) } } + private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> + if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) } + } + private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> + if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } + } + private val pickSaveZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> + val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult + if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then) + } + private val pickSaveDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> + val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult + if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then) + } + + /** Takes a new or updated Lossless Scaling from Steam and shows what LSFG can use. */ + private fun syncLossless() { + Thread({ + Lossless.sync(this) + val state = Lossless.state(this) + ui.post { lossless = state } + }, "lossless-sync").start() + } + + private fun importLossless(dll: File) { + Thread({ + val message = Lossless.message(this, Lossless.import(this, dll)) + val state = Lossless.state(this) + ui.post { + lossless = state + android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show() + } + }, "lossless-import").start() + } + + /** Import a save zip into [game]: pick it in the app's file picker, then back up and unzip off the main thread. */ + private fun importSaves(name: String, game: () -> GameSaves.Game) { + if (SessionState.running) { + android.widget.Toast.makeText(this, "Close the Steam session first, so the game can't save over the import", android.widget.Toast.LENGTH_LONG).show() + return + } + onSavePicked = { zip -> + saveAction("Importing into $name") { + val (written, backup) = GameSaves.import(game(), zip) + val kind = GameSaves.layoutOf(zip)?.label ?: "zip" + "Imported $written files from the $kind into $name" + (backup?.let { ". Old saves backed up to Download/DroidDeck/Saves/backups" } ?: "") + } + } + pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), "Choose a save zip for $name", GameSaves.savesDir().parentFile?.parentFile?.path)) + } + + /** Export [game]'s saves in [layout] to a folder picked in the app's file picker. */ + private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) { + onSavePicked = { dir -> + saveAction("Exporting $name") { + val (zip, count) = GameSaves.export(game(), layout, dir) + "Exported $count files as a ${layout.label}: ${zip.path.removePrefix("/storage/emulated/0/")}" + } + } + GameSaves.savesDir().mkdirs() + pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, "Choose where to save $name (${layout.label})", GameSaves.savesDir().path)) + } private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs + path) @@ -167,6 +245,9 @@ class MainActivity : ComponentActivity() { private var addedGamesArt by mutableStateOf(true) @Volatile private var artFetchRunning = false private var addedGames by mutableStateOf>(emptyList()) + private val pickAppImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> + if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { com.droiddeck.launcher.store.AppImageState.import(this, it) } + } private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> SessionPrefs.setRomsDir(this, path) @@ -183,6 +264,7 @@ class MainActivity : ComponentActivity() { private var theme by mutableStateOf("graphite") private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO) private var hdrOn by mutableStateOf(false) + private var fpsLimit by mutableStateOf(0) private var hdrReason by mutableStateOf(null) private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) @@ -259,9 +341,13 @@ class MainActivity : ComponentActivity() { theme = SessionPrefs.theme(this) backActionsInverted = SessionPrefs.backActionsInverted(this) launcherFullscreen = SessionPrefs.launcherFullscreen(this) + storeEnabled = SessionPrefs.storeEnabled(this) + appImagesEnabled = SessionPrefs.appImagesEnabled(this) applyLauncherFullscreen() + updates.start() setContent { DroidDeckTheme(theme) { + com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { val sm = settingsMode val page: (@Composable () -> Unit)? = when { sm != null -> { { ModeSettingsHost(sm) } } @@ -280,8 +366,8 @@ class MainActivity : ComponentActivity() { offlineAccount = offlineAccount, offline = offline, frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, steamGames = steamGames, emulators = emulatorList, running = runningLabel, - frameGenEngine = FrameGen.engine(this), frameGenMultiplier = FrameGen.multiplier(this), - lsfgReady = LsfgNative.isInstalled(this), + frameGen = FrameGen.mode(this), + lossless = lossless, pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null, theme = theme, isHomeApp = homeAppSelected, @@ -299,9 +385,12 @@ class MainActivity : ComponentActivity() { buildLabel = BuildConfig.BUILD_LABEL, oscMode = oscMode, controller = controllerSettings, + updates = updates.state(), phantomProcessStatus = phantomProcessStatus, showPhantomGate = showPhantomGate, launcherFullscreen = launcherFullscreen, + storeEnabled = storeEnabled, + appImagesEnabled = appImagesEnabled, ), FrontEndActions( onPlay = { startSteamSession() }, @@ -321,6 +410,25 @@ class MainActivity : ComponentActivity() { .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)) }, onEmulator = { e -> launchProgram(e.program) }, + // A Flatpak app from the store, full screen under gamescope like an emulator. + onImportAppImage = { + pickAppImage.launch(InAppFilePicker.buildIntent(this, listOf("appimage"), "Choose an AppImage")) + }, + // An imported AppImage, full screen under gamescope like an emulator. + onAppImage = { dir, name -> + Library.flatpakNames[dir] = name + startActivity(Intent(this, SessionActivity::class.java) + .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN) + .putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER) + .putExtra(SessionService.EXTRA_PROGRAM_ARGS, arrayOf(dir))) + }, + onFlatpakApp = { id, name -> + Library.flatpakNames[id] = name + startActivity(Intent(this, SessionActivity::class.java) + .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN) + .putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.runtime.FlatpakManager.LAUNCHER) + .putExtra(SessionService.EXTRA_PROGRAM_ARGS, arrayOf(id))) + }, onRom = { g -> val e = emulatorList.first { it.id == g.emulatorId } startActivity(Intent(this, SessionActivity::class.java) @@ -335,12 +443,18 @@ class MainActivity : ComponentActivity() { onInstallPackage = { id -> installPackage(id) }, onRemovePackage = { id -> removePackage(id) }, onRuntime = { onRuntimeButton() }, - onFrameGenPick = { engine, multiplier -> - FrameGen.set(this, engine, multiplier) + onFrameGenPick = { mode -> + FrameGen.set(this, mode) frameGenLabel = FrameGen.label(this) }, + onImportLossless = { + pickLossless.launch(InAppFilePicker.buildIntent(this, listOf("dll"), getString(R.string.lsfg_pick_title))) + }, onProtons = { openProtons() }, onComponents = { focusContent -> openComponents(focusContent) }, + // A game page's Manage saves: the game's Proton and saves are read when the work runs, off the main thread. + onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } }, + onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } }, onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true }, onRoms = { showRoms = true }, onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) }, @@ -365,7 +479,6 @@ class MainActivity : ComponentActivity() { OfflineMode.setEnabled(this, !OfflineMode.enabled(this)) offline = OfflineMode.enabled(this) }, - onCredits = { showCredits = true }, onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = false }, onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id }, onLauncherFullscreen = { on -> @@ -373,6 +486,8 @@ class MainActivity : ComponentActivity() { launcherFullscreen = on applyLauncherFullscreen() }, + onStoreEnabled = { on -> SessionPrefs.setStoreEnabled(this, on); storeEnabled = on }, + onAppImagesEnabled = { on -> SessionPrefs.setAppImagesEnabled(this, on); appImagesEnabled = on }, onHomeApp = { manageHomeApp() }, onHomeScreen = { on -> HomeApp.setHomeScreenEnabled(this, on) @@ -383,9 +498,6 @@ class MainActivity : ComponentActivity() { SessionPrefs.setBackActionsInverted(this, inverted) backActionsInverted = inverted }, - onCheckLatestBuild = { - startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml"))) - }, onRefreshPhantomStatus = { refreshPhantomStatus() }, onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) }, onWirelessAdbPair = { host, port, code, complete -> @@ -430,6 +542,13 @@ class MainActivity : ComponentActivity() { android.widget.Toast.makeText(this, "ADB command copied", android.widget.Toast.LENGTH_SHORT).show() }, onDismissPhantomGate = { showPhantomGate = false }, + onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) }, + onOpenNotificationSettings = { + startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + }, + updates = updates.actions(), controller = ControllerActions( onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o }, onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() }, @@ -471,10 +590,17 @@ class MainActivity : ComponentActivity() { onConfirm = { Thread({ LinuxRuntimeInstaller.uninstall(this); ui.post { refresh() } }, "uninstall").start() }, onDismiss = { showRemove = false }, ) - if (showCredits) CreditsDialog { showCredits = false } flood?.let { f -> com.droiddeck.launcher.ui.LaunchFlood(f.from, onProgress = { floodProgress = it }) { launchFlooded(f) } } + returning?.let { r -> + com.droiddeck.launcher.ui.FloodReturn(androidx.compose.ui.graphics.Color(r.color), r.to, onProgress = { floodProgress = it }) { + returning = null + floodProgress = 0f + com.droiddeck.launcher.ui.LaunchOrigin.flooding = null + } + } } } + } if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() } @@ -485,8 +611,9 @@ class MainActivity : ComponentActivity() { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } - // The microphone is on by default; ask once, with the storage prompt, so voice chat works - // without a trip to the settings. A refusal is not asked again - the toggle asks when used. + // The microphone is off by default. Someone who turned it on before the permission was + // granted is asked once here, with the storage prompt; a refusal is not asked again - the + // toggle asks when used. if (SessionPrefs.micEnabled(this) && !SessionPrefs.micAsked(this) && checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { wanted.add(Manifest.permission.RECORD_AUDIO) @@ -533,11 +660,11 @@ class MainActivity : ComponentActivity() { } } - /** On the Components page the pad's LB / RB step through FEX, DXVK and VKD3D-Proton, wrapping around. */ + /** On the Components page the pad's LB / RB step through GPU drivers, FEX, DXVK and VKD3D-Proton, wrapping around. */ override fun dispatchKeyEvent(event: KeyEvent): Boolean { if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { - val all = ComponentsManager.COMPONENTS + val all = listOf(com.droiddeck.launcher.ui.GPU_TAB) + ComponentsManager.COMPONENTS val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1 components.compComp = all[(all.indexOf(components.compComp).coerceAtLeast(0) + step) % all.size] } @@ -549,7 +676,16 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() com.droiddeck.launcher.ui.Motion.refresh(this) + // Back from a session stopped behind a flood: open on its blue, before the first frame. + com.droiddeck.launcher.ui.QuitFlood.take()?.let { c -> + returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn()) + } refreshPhantomStatus() + syncLossless() + // Opening the app and coming back from a session both land here. + updates.onResume() + // Auto keeps this GPU's recommended driver pair installed and set: once per app start. + drivers.ensureAuto(force = false) // Swaps queued while a game ran on that Proton go in once nothing uses it (usually the // session has just ended). Cheap when nothing is queued. if (!SessionState.running) Thread({ @@ -580,10 +716,16 @@ class MainActivity : ComponentActivity() { refreshSecondScreenDisplays() } + override fun onDestroy() { + updates.unregister() + super.onDestroy() + } + override fun onStop() { displayManager.unregisterDisplayListener(secondScreenDisplayListener) // The session covers the page by now; coming back finds it as it was. flood = null + returning = null floodProgress = 0f com.droiddeck.launcher.ui.LaunchOrigin.flooding = null super.onStop() @@ -633,6 +775,19 @@ class MainActivity : ComponentActivity() { }, "catalog-desktop").start() } + /** Runs a save import or export off the main thread, one at a time, and says how it went. */ + private fun saveAction(label: String, work: () -> String) { + if (saveBusy != null) return + saveBusy = label + Thread({ + val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" } + ui.post { + saveBusy = null + android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show() + } + }, "game-saves-action").start() + } + private fun openProtons() { settingsMode = null showPerformance = false @@ -657,14 +812,16 @@ class MainActivity : ComponentActivity() { ) } - private fun openComponents(focusContent: Boolean = true) { + private fun openComponents(focusContent: Boolean = true, tab: String? = null) { focusComponentsContent = focusContent + if (tab != null) components.compComp = tab settingsMode = null showPerformance = false showProtons = false showMapping = false showComponents = true components.refreshComponents(snapshotFirst = true) + drivers.refreshDrivers() } private fun importComponent(uri: Uri) { @@ -699,6 +856,22 @@ class MainActivity : ComponentActivity() { onRefresh = { components.refreshComponentCatalog() }, onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) }, onBack = { showComponents = false }, + gpu = drivers.state(), + gpuActions = com.droiddeck.launcher.ui.GpuDriversActions( + onAuto = { on -> drivers.setMode(on) }, + onPair = { key -> drivers.selectPair(key) }, + onRefresh = { if (drivers.mode == SessionPrefs.GPU_DRIVERS_AUTO) drivers.ensureAuto(force = true) else drivers.checkLatestTurnip() }, + // Picking one driver on its own is Manual: Auto would put its pair back. + onSelectLinux = { id -> drivers.selectDriver(id, linux = true) }, + onSelectAndroid = { id -> drivers.selectDriver(id, linux = false) }, + onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) }, + onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) }, + onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) }, + onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip or Android + Linux bundle)")) }, + onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip or Android + Linux bundle)")) }, + onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a driver zip or an Android + Linux bundle")) }, + onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() }, + ), ) } @@ -765,10 +938,8 @@ class MainActivity : ComponentActivity() { ModeSettingsPage( ModeSettings( mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode, - hdr = hdrOn, hdrReason = hdrReason, - linuxRows = drivers.linuxRows, - linuxSelected = if (mode == SessionService.MODE_STEAM) drivers.linuxSteam else drivers.linuxDesktop, - androidRows = drivers.androidRows, androidSelected = drivers.androidSelected, + hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, + gpuDrivers = drivers.summary(), touchMode = touchMode, suspendPolicy = suspendPolicy, oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null, @@ -782,12 +953,13 @@ class MainActivity : ComponentActivity() { storageOptions = storageOptions, fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null, steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null, + steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode, + mangoapp = mangoapp, + steamController = if (mode == SessionService.MODE_STEAM) steamController else null, runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup, addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null, addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(), addedGamesArt = addedGamesArt, - linuxDownloads = drivers.linuxDownloads, androidDownloads = drivers.androidDownloads, releaseStatus = drivers.releaseStatus, - releaseChecking = drivers.releaseChecking, canRestoreBundled = drivers.canRestoreBundled, deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null, deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null, deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent, @@ -798,15 +970,8 @@ class MainActivity : ComponentActivity() { onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size }, onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape }, onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, - onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); drivers.refreshDrivers() }, - onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) }, - onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) }, - onRefreshReleases = { drivers.checkLatestTurnip() }, - onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) }, - onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() }, - onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); drivers.refreshDrivers() }, - onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) }, - onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) }, + onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, + onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps }, onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t }, onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy }, onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o }, @@ -833,6 +998,13 @@ class MainActivity : ComponentActivity() { }, onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id }, onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id }, + onSteamDeckMode = { on -> + SessionPrefs.setSteamDeckMode(this, on) + steamDeckMode = on + steamChannel = SessionPrefs.steamChannel(this) + }, + onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on }, + onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id }, onRunSteamAtStartup = { on -> SessionPrefs.setRunSteamAtStartup(this, on) runSteamAtStartup = on @@ -863,16 +1035,20 @@ class MainActivity : ComponentActivity() { PerformancePage( cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) }, clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, - tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, steamDeckMode = steamDeckMode, noXalia = noXalia, - prootNoSeccomp = prootNoSeccomp, phantomWarning = phantomWarning, + tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia, + gamescopeRealtime = gamescopeRealtime, + gpuClockPin = gpuClockPin, + 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 }, onGlThread = { on -> SessionPrefs.setGlThread(this, on); glThread = on }, onNoGlError = { on -> SessionPrefs.setNoGlError(this, on); noGlError = on }, - onSteamDeckMode = { on -> SessionPrefs.setSteamDeckMode(this, on); steamDeckMode = on }, onNoXalia = { on -> SessionPrefs.setNoXalia(this, on); noXalia = on }, + onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on }, + onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on }, onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on }, + onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) }, onClientCore = { core, on -> clientCores = if (on) clientCores + core else clientCores - core SessionPrefs.setClientCpus(this, CpuCores.format(clientCores)) @@ -915,11 +1091,15 @@ class MainActivity : ComponentActivity() { customResolution = SessionPrefs.customResolution(this, mode) fexPreset = SessionPrefs.fexPreset(this) steamChannel = SessionPrefs.steamChannel(this) + steamDeckMode = SessionPrefs.steamDeckMode(this) + mangoapp = SessionPrefs.mangoapp(this) + steamController = SessionPrefs.steamController(this) runSteamAtStartup = SessionPrefs.runSteamAtStartup(this) addedGamesDirs = SessionPrefs.addedGamesDirs(this) refreshAddedGames() shapeMode = SessionPrefs.shapeMode(this) hdrOn = SessionPrefs.hdr(this, mode) + fpsLimit = SessionPrefs.fpsLimit(this, mode) hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason touchMode = SessionPrefs.touchMode(this) suspendPolicy = SessionPrefs.suspendPolicy(this, mode) @@ -964,7 +1144,10 @@ class MainActivity : ComponentActivity() { tuSysmem = SessionPrefs.tuSysmem(this) zinkLazy = SessionPrefs.zinkLazy(this) noXalia = SessionPrefs.noXalia(this) + gamescopeRealtime = SessionPrefs.gamescopeRealtime(this) + gpuClockPin = SessionPrefs.gpuClockPin(this) prootNoSeccomp = SessionPrefs.prootNoSeccomp(this) + guestHostname = SessionPrefs.guestHostname(this) refreshPhantomStatus() } @@ -980,7 +1163,8 @@ class MainActivity : ComponentActivity() { logsEnabled = SessionPrefs.logsEnabled(this) runningLabel = if (SessionState.running) when (SessionState.mode) { SessionService.MODE_DESKTOP -> "Desktop" - SessionService.MODE_RUN -> SessionState.program?.substringAfterLast('/')?.substringBefore('.') ?: "Program" + SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program) + ?: SessionState.program?.substringAfterLast('/')?.substringBefore('.') ?: "Program" else -> "Steam" } else null // The libraries, off the main thread: manifests and a folder scan. @@ -988,14 +1172,14 @@ class MainActivity : ComponentActivity() { val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g -> com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art -> Library.SteamGame( - g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId, + g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, Library.ADDED, g.gameId, hero = art.hero ?: art.header, gameFiles = g.folder, - protonPrefix = Library.protonPrefix(this, g.appId), + protonPrefix = Library.protonPrefix(this, g.steamAppId?.toLong() ?: g.appId), ) } } else emptyList() val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null } - ui.post { steamGames = games; emulatorList = emus } + ui.post { steamGames = games.distinctBy { it.gameId }; emulatorList = emus } // Box art for the games that have none, fetched after the list is up; the list is // rebuilt once if any was found. if (!OfflineMode.enabled(this) && CoverArt.fetchMissing(this, emus.flatMap { it.games })) { @@ -1037,15 +1221,18 @@ class MainActivity : ComponentActivity() { } private fun refreshPhantomStatus() { - phantomProcessStatus = PhantomProcessLimit.read(contentResolver) + phantomProcessStatus = PhantomProcessLimit.read(this) phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { - "${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.ADB_COMMAND}" + "${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.adbCommand()}" } else null } private fun openDeveloperOptions(displayId: Int?) { + val highlight = if (PhantomProcessLimit.hasDeveloperToggle() && + WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) null else "toggle_adb_wireless" val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) } try { if (displayId == null) startActivity(intent) else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle()) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index ae6c63ec4..49160f70c 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher +import androidx.compose.foundation.layout.fillMaxSize import android.hardware.input.InputManager import android.hardware.display.DisplayManager import android.content.Intent @@ -23,16 +24,20 @@ import android.widget.FrameLayout import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.OnBackPressedCallback +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.unit.dp import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.files.InAppFilePicker import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.gpu.FrameGen -import com.droiddeck.launcher.gpu.LsfgNative +import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.gpu.TurnipDriver import com.droiddeck.launcher.input.EvdevKeys import com.droiddeck.launcher.input.KeyboardHost @@ -45,7 +50,6 @@ import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.input.TouchpadGestures import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.LoadingState -import com.droiddeck.launcher.session.PerfHints import com.droiddeck.launcher.session.PerfHud import com.droiddeck.launcher.session.PerfMode import com.droiddeck.launcher.session.SessionPrefs @@ -90,6 +94,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var loading: LoadingState private lateinit var hud: PerfHud private var padBridge: PadBridge? = null + /** The handheld's gyro and accelerometer, fed to the Deck controller while the session shows. */ + private var padMotion: com.droiddeck.launcher.input.PadMotion? = null + /** Between onResume and onPause. */ + private var resumed = false + 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). */ + private fun updatePadMotion() { + if (resumed && SessionState.deckPad) padMotion?.start() else padMotion?.stop() + } private var onScreenControls: OnScreenControls? = null private var keyboard: KeyboardHost? = null private var watching = true @@ -144,6 +159,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // Compose reads these; the activity writes them. private var drawerOpen by mutableStateOf(false) + /** A stop growing out of the dialog's Stop (overlay px); the session ends once it covers the screen. */ + private var quitFrom by mutableStateOf(null) + /** Left behind that flood: the front end opens on its blue, so no sink of our own. */ + private var quitFlooded = false /** The drawer's Components tab: the Protons as last read (ComponentsManager). */ private var drawerComponents by mutableStateOf(null) private var drawerPage by mutableIntStateOf(0) @@ -153,22 +172,43 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var pcKeyboardOpen by mutableStateOf(false) private var hudOn by mutableStateOf(true) private var fillScreen by mutableStateOf(true) - private var frameGenLabel by mutableStateOf("Off") - private var frameGenEngine by mutableStateOf(FrameGen.ENGINE_OFF) - private var frameGenMultiplier by mutableStateOf(2) + private var lossless by mutableStateOf(Lossless.State.NONE) + private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> + if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } + } + private var frameGen by mutableStateOf(FrameGen.Mode.OFF) private var fexPreset by mutableStateOf("") private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO) - private var secondScreenMode by mutableStateOf(SecondScreenMode.NONE) + private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode) private var secondScreenDisplays by mutableStateOf>(emptyList()) - private var selectedSecondScreenDisplay by mutableStateOf(-1) + private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay) + /** Between onStart and onStop: while stopped the second screen stays closed, its choice kept. */ + private var started = false private lateinit var displayManager: DisplayManager private var secondScreenPresentation: SecondScreenPresentation? = null private val displayListener = object : DisplayManager.DisplayListener { override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays() override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays() - override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays() + override fun onDisplayChanged(displayId: Int) { + followPanelRefresh(displayId) + refreshSecondScreenDisplays() + } + } + + /** + * The panel's rate, followed for the rest of the session. It is read once at start, and a + * panel that drops from 120 to 60 Hz later (battery saver, heat, a vendor overriding the mode + * asked for) left the compositor telling gamescope every frame took 8.3 ms, so the client and + * its games paced against a vblank that no longer came. (WinNative 53836ca9.) + */ + private fun followPanelRefresh(displayId: Int) { + if (!CompositorHost.isStarted) return + val display = (if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay) ?: return + if (display.displayId != displayId) return + val hz = display.refreshRate + if (hz > 1f) WaylandCompositor.nativeSetOutputRefreshRate(hz) } private var isHomeApp by mutableStateOf(false) private var androidApps by mutableStateOf>(emptyList()) @@ -197,9 +237,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { SessionEvents.record("agent.start_requested", mapOf("mode" to SessionState.mode)) } window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) - // Game-tier power policy for the whole session: a sustained clock floor, the panel's - // fastest mode, and the OS told it is in gameplay. Logged so a slow device says why. - Log.i(TAG, "perf: " + PerfMode.apply(this)) + // Game-tier power policy for the whole session: the panel's fastest mode (one the frame cap + // divides, when there is a cap), and the OS told it is in gameplay. Logged so a slow device + // says why. The cap is the session's: an activity re-created mid-session keeps it. + if (!SessionState.running) { + SessionState.fpsLimit = SessionPrefs.fpsLimit( + this, SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM), + ) + } + Log.i(TAG, "perf: " + PerfMode.apply(this, SessionState.fpsLimit)) goFullscreen() // The device's volume keys change the stream the session plays on (the relay and // PulseAudio are media playback); they are never forwarded to the guest. @@ -218,6 +264,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { val bridge = PadBridge(File(LinuxRuntime.sessionRoot(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 // 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 { @@ -292,6 +343,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { isFocusableInTouchMode = true setContent { DroidDeckTheme { + com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density, cursorImage, cursorHotX, cursorHotY, cursorImageScale) if (hud.text.isNotEmpty()) HudText(hud.text) @@ -313,6 +365,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // Opening the drawer takes the controller away from the game: release its pad. androidx.compose.runtime.LaunchedEffect(drawerOpen) { if (drawerOpen) { + syncLossless() padBridge?.releaseAll() androidx.compose.runtime.withFrameNanos { } val requested = sessionOverlay.requestFocus() @@ -336,8 +389,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { androidApps = androidApps, hudOn = hudOn, fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null, - frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier, - lsfgReady = LsfgNative.isInstalled(this@SessionActivity), + frameGen = frameGen, + lossless = lossless, oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode, touchAuto = if (usingTouchpad()) "touchpad" else "direct", shapeMode = shapeMode, fexPreset = fexPreset, @@ -346,11 +399,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { selectedSecondScreenDisplay = selectedSecondScreenDisplay, onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() }, onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on }, - onFrameGenPick = { engine, multiplier -> - FrameGen.set(this@SessionActivity, engine, multiplier) + onFrameGenPick = { mode -> + FrameGen.set(this@SessionActivity, mode) readPrefs() applyFrameGen() }, + onImportLossless = { + pickLossless.launch(InAppFilePicker.buildIntent( + this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title))) + }, onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() }, onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen }, onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null, @@ -394,6 +451,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onBackground = { drawerOpen = false; moveTaskToBack(true) }, onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() }, onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() }, + onStopFrom = { onScreen -> + drawerOpen = false + if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) { + if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() } + } else { + val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) } + quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat()) + } + }, onClose = { drawerOpen = false }, components = drawerComponents, onComponentsRefresh = { refreshDrawerComponents() }, @@ -403,8 +469,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { title = pausedTitle(), onResume = { SessionService.resume(this@SessionActivity) }, ) + quitFrom?.let { from -> + val error = androidx.compose.material3.MaterialTheme.colorScheme.error + com.droiddeck.launcher.ui.LaunchFlood( + from, onProgress = {}, + fromColors = error to androidx.compose.ui.graphics.lerp(error, androidx.compose.ui.graphics.Color.Black, 0.12f), + cornerAtRest = 20.dp, + ) { finishFlooded() } + } } } + } } private fun refreshHomeApp() { @@ -437,7 +512,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { performBackAction(double = false) } pendingBackAction = pending - uiHandler.postDelayed(pending, BACK_DOUBLE_PRESS_TIMEOUT_MS) + // Android's own double-tap window (300 ms): the single action waits it out, so it is felt. + uiHandler.postDelayed(pending, android.view.ViewConfiguration.getDoubleTapTimeout().toLong()) } private fun performBackAction(double: Boolean) { @@ -537,9 +613,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { hudOn = SessionPrefs.hudEnabled(this) fillScreen = SessionPrefs.forceFullscreen(this) touchMode = SessionPrefs.touchMode(this) - frameGenLabel = FrameGen.label(this) - frameGenEngine = FrameGen.engine(this) - frameGenMultiplier = FrameGen.multiplier(this) + frameGen = FrameGen.mode(this) fexPreset = SessionPrefs.fexPreset(this) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) oscMode = SessionPrefs.oscMode(this) @@ -734,12 +808,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { CompositorHost.startOrAttach( holder.surface, runtimeDir.path, driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, - applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), + applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), SessionState.fpsLimit, ) if (!SessionState.running) SessionEvents.record("compositor.started") - // ADPF: the compositor thread's frame intervals go to the power HAL against the panel's - // period, so a long frame raises CPU clocks now rather than after the load averages up. - PerfHints.arm(this, refreshHz()) // The service owns everything below the compositor. It is started whenever no session is // running - NOT only when the compositor was just started: the compositor lives for the // whole process, so the second Play after a session ended used to re-attach the Surface, @@ -825,9 +896,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return Pair(width and 1.inv(), height and 1.inv()) } + /** + * The rate of the mode PerfMode asked for, not the one the panel is still in: the switch lands + * some frames after onCreate, and read too early it gave gamescope `-r 60` on a 120 Hz panel - + * the client and every game then paced themselves to 60. (WinNative's requestedPanelRefreshRate.) + */ private fun refreshHz(): Float { val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay - val hz = display?.refreshRate ?: 60f + val wanted = window.attributes.preferredDisplayModeId + val hz = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted }?.refreshRate + ?: display?.refreshRate ?: 60f return if (hz > 1f) hz else 60f } @@ -839,10 +917,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { val hz = refreshHz() Thread({ val problem = FrameGen.apply(this, hz) - if (problem != null) runOnUiThread { Toast.makeText(this, problem, Toast.LENGTH_LONG).show() } + val state = Lossless.state(this) + runOnUiThread { + lossless = state + if (problem != null) Toast.makeText(this, problem, Toast.LENGTH_LONG).show() + } }, "frame-gen").start() } + /** A Lossless Scaling installed or updated in Steam during the session is taken when the drawer opens. */ + private fun syncLossless() { + Thread({ + Lossless.sync(this) + val state = Lossless.state(this) + runOnUiThread { lossless = state } + }, "lossless-sync").start() + } + + private fun importLossless(dll: File) { + Thread({ + val message = Lossless.message(this, Lossless.import(this, dll)) + val state = Lossless.state(this) + runOnUiThread { + lossless = state + Toast.makeText(this, message, Toast.LENGTH_LONG).show() + if (FrameGen.engine(this) == FrameGen.ENGINE_LSFG) applyFrameGen() + } + }, "lossless-import").start() + } + // ── Session state ─────────────────────────────────────────────────────────────────────── /** Keeps the loading overlay current from the session log, and its clock moving. */ @@ -904,8 +1007,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return } // It stays until the user leaves: a failure read against a timer is a failure not read. + val what = when (SessionState.mode) { + SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "The program" + SessionService.MODE_DESKTOP -> "The desktop" + else -> "Steam" + } loading.showEnded( - hint ?: "Steam stopped unexpectedly. Share the logs with a bug report, or try again.", + hint ?: "$what stopped unexpectedly. Share the logs with a bug report, or try again.", "Exit status $status · ${SessionState.logFile?.path ?: "no log"}", ) focusEndedScreen() @@ -1206,6 +1314,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { */ private fun syncClientCursor(): Boolean { if (!CompositorHost.isStarted) return false + // Asked on every pointer move; the image is copied only when the client has changed it. + if (WaylandCompositor.nativeCursorSerial() == cursorSerial) return false val n = WaylandCompositor.nativeCursorSnapshot(cursorBuf) if (n < 6) return false val serial = cursorBuf[0] @@ -1247,11 +1357,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } 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) } private fun selectSecondScreenDisplay(displayId: Int) { if (secondScreenDisplays.none { it.id == displayId }) return selectedSecondScreenDisplay = displayId + SessionState.secondScreenDisplay = displayId if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode) } @@ -1273,8 +1386,9 @@ 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) { - closeSecondScreen(reset = true) - refreshSecondScreenDisplays() + // 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) return } var presentation = secondScreenPresentation @@ -1306,6 +1420,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (!presentation.isShowing) presentation.show() presentation.showMode(mode) secondScreenMode = mode + SessionState.secondScreenMode = mode + SessionState.secondScreenDisplay = selectedSecondScreenDisplay } catch (e: Exception) { Log.w(TAG, "could not show second-screen controls on ${target.name}", e) closeSecondScreen(reset = true) @@ -1325,7 +1441,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun closeSecondScreen(reset: Boolean) { secondScreenPresentation?.closeControls() secondScreenPresentation = null - if (reset) secondScreenMode = SecondScreenMode.NONE + if (reset) { + secondScreenMode = SecondScreenMode.NONE + SessionState.secondScreenMode = SecondScreenMode.NONE + } } /** Touchpad on the desktop, direct in Steam, unless the drawer says otherwise. */ @@ -1438,15 +1557,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onStart() { super.onStart() + started = true displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) refreshSecondScreenDisplays() - if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode) + if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) SessionService.setActivityVisible(this, true) } override fun onStop() { + started = false displayManager.unregisterDisplayListener(displayListener) - closeSecondScreen(reset = true) + // Closed while the session is out of sight (sleep, a closed lid, another app), and kept: + // onStart puts it back. + closeSecondScreen(reset = false) SessionService.setActivityVisible(this, false) super.onStop() } @@ -1483,6 +1606,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { ?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper())) onScreenControls?.reload() updateOnScreenControls() + resumed = true + updatePadMotion() readPrefs() if (CompositorHost.isStarted) applyFrameGen() } @@ -1496,6 +1621,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { releaseDrawerDirection() // A button held when the app goes away would stay held in the ring for the whole session. onScreenControls?.releaseAll() + resumed = false + updatePadMotion() keyboard?.takeIf { it.shown }?.hide() super.onPause() } @@ -1549,21 +1676,34 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { closeSecondScreen(reset = true) if (::hud.isInitialized) hud.stop() padBridge?.stop() + padMotion?.stop() + if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null if (SessionState.endListener === endListener) SessionState.endListener = null WaylandCompositor.clearFirstFrameListener(firstFrameListener) super.onDestroy() } + /** The screen is all blue: the session stops and the front end opens on the same blue (FloodReturn). */ + private fun finishFlooded() { + if (isFinishing) return + val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal + com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb()) + window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb())) + quitFlooded = true + SessionService.stop(this) + finish() + } + /** Leaving the session sinks its surface back down onto the front end. */ override fun finish() { super.finish() - overridePendingTransition(R.anim.session_hold, R.anim.session_sink) + if (quitFlooded) overridePendingTransition(0, 0) + else overridePendingTransition(R.anim.session_hold, R.anim.session_sink) } companion object { private const val TAG = "SessionActivity" private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION - private const val BACK_DOUBLE_PRESS_TIMEOUT_MS = 500L private const val CURSOR_PAD_HOLD_MS = 1200L private const val DRAWER_HAT_THRESHOLD = 0.5f private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f diff --git a/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt b/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt new file mode 100644 index 000000000..e93b9f62a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/UpdatesMenu.kt @@ -0,0 +1,141 @@ +package com.droiddeck.launcher + +import android.app.Activity +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.pm.PackageInstaller +import android.os.Build +import android.os.Handler +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.ui.UpdatesActions +import com.droiddeck.launcher.ui.UpdatesState +import com.droiddeck.launcher.update.AppUpdates +import com.droiddeck.launcher.update.SelfInstaller + +/** + * The Updates page's state: the channels' latest builds, the one followed, and an update being + * downloaded or installed. Checked when the launcher comes to the front - opening the app, and + * coming back from a session - at most once a minute. + */ +internal class UpdatesMenu(private val activity: Activity, private val ui: Handler) { + // Read in start(): the activity has no context yet while its fields are made. + var catalog by mutableStateOf(null) + var follow by mutableStateOf(AppUpdates.Follow(AppUpdates.Channel.STABLE)) + var checking by mutableStateOf(false) + var error by mutableStateOf(null) + var stage by mutableStateOf(null) + var percent by mutableIntStateOf(-1) + var askPermission by mutableStateOf(false) + // An install waiting for the user to allow "Install unknown apps"; it goes on when they come back. + private var pending: AppUpdates.Release? = null + private var lastCheck = 0L + private var request = 0 + + fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission) + + fun actions() = UpdatesActions( + onCheck = { check(force = true) }, + onFollow = ::choose, + onInstall = ::install, + onAllowInstalls = { + askPermission = false + runCatching { activity.startActivity(SelfInstaller.permissionIntent(activity)) } + .onFailure { error = "Couldn't open Android's \"Install unknown apps\" setting"; pending = null } + }, + onDismissPermission = { askPermission = false; pending = null }, + ) + + val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow) + + /** On every return to the launcher: go on with an install the user just allowed, and check if due. */ + fun onResume() { + pending?.let { r -> + if (SelfInstaller.canInstall(activity)) { pending = null; install(r) } + } + if (!SessionState.running) check(force = false) + } + + fun check(force: Boolean) { + if (checking || stage != null) return + val now = System.currentTimeMillis() + if (!force && now - lastCheck < 60_000) return + lastCheck = now + val id = ++request + checking = true + Thread({ + val result = runCatching { AppUpdates.refresh(activity) } + ui.post { + if (id != request) return@post + checking = false + result.onSuccess { + catalog = it + follow = AppUpdates.follow(activity, it) + error = null + }.onFailure { if (force) error = "Couldn't check: ${it.message ?: it.javaClass.simpleName}" } + } + }, "app-updates").start() + } + + private fun choose(f: AppUpdates.Follow) { + AppUpdates.setFollow(activity, f) + follow = f + error = null + } + + private fun install(r: AppUpdates.Release) { + if (stage != null) return + val apk = r.apk ?: run { error = "This build has no download for this copy of DroidDeck"; return } + if (SessionState.running) { error = "Stop the running session first, then update"; return } + if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return } + error = null + stage = "Downloading" + percent = 0 + Thread({ + val result = runCatching { + val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } } + ui.post { stage = "Installing"; percent = -1 } + SelfInstaller.install(activity, file) + } + result.onFailure { e -> ui.post { stage = null; error = e.message ?: "The update failed" } } + }, "app-update-install").start() + } + + /** PackageInstaller's answer: Android's confirm prompt to show, or why it failed. Success restarts the app. */ + private val receiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) { + PackageInstaller.STATUS_PENDING_USER_ACTION -> { + val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java) + else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT) + if (confirm == null) { stage = null; error = "Android didn't offer to install the update"; return } + stage = "Waiting for you to confirm" + activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + PackageInstaller.STATUS_SUCCESS -> stage = null + else -> { + stage = null + error = SelfInstaller.describeFailure(status, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)) + } + } + } + } + + /** From onCreate: the last check, the channel followed, and PackageInstaller's answers. */ + fun start() { + catalog = AppUpdates.cached(activity) + follow = AppUpdates.follow(activity, catalog) + val filter = IntentFilter(SelfInstaller.ACTION_STATUS) + if (Build.VERSION.SDK_INT >= 33) activity.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) + else activity.registerReceiver(receiver, filter) + } + + fun unregister() { + runCatching { activity.unregisterReceiver(receiver) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index 9ff0c002a..96e495b53 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -113,19 +113,24 @@ object DeviceReport { k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) h("Drivers") + val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect() + k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "") + k("Driver mode", SessionPrefs.gpuDriverMode(context) + + (com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from( + com.droiddeck.launcher.gpu.TurnipReleases.cached(context)))?.let { " (recommended pair: $it)" } ?: "")) val turnip = TurnipDriver(context) val androidChoice = SessionPrefs.androidDriver(context) k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice) k(" name / version", "${turnip.displayName(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)} ${turnip.driverVersion(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)}".trim()) k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", ")) val lm = LinuxVulkanDriverManager(context) - for (m in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) { - val id = SessionPrefs.linuxDriver(context, m) + run { + val id = SessionPrefs.linuxDriver(context) val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)" else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() + lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } + if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]" - k("Linux driver ($m)", label) + k("Linux driver", label) } k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path) @@ -144,9 +149,12 @@ object DeviceReport { k("Threaded GL (glthread)", SessionPrefs.glThread(context)) k("No GL error checks", SessionPrefs.noGlError(context)) k("Steam Deck mode", SessionPrefs.steamDeckMode(context)) + k("Steam controller", SessionPrefs.steamController(context)) k("FEX preset", SessionPrefs.fexPreset(context).ifEmpty { "FEX defaults" }) k("Skip xalia", SessionPrefs.noXalia(context)) + k("gamescope realtime", SessionPrefs.gamescopeRealtime(context)) k("proot without seccomp", SessionPrefs.prootNoSeccomp(context)) + k("Guest host name", SessionPrefs.guestHostname(context)) k("DirectAudio for games", SessionPrefs.directAudio(context)) k("Stretch games to fill", SessionPrefs.forceFullscreen(context)) k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic") @@ -161,7 +169,7 @@ object DeviceReport { }) h("Android process limits") - k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context.contentResolver))) + k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context))) h("Device switch files in Download") for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver", diff --git a/app/src/main/java/com/droiddeck/launcher/core/FexPreset.kt b/app/src/main/java/com/droiddeck/launcher/core/FexPreset.kt index e76d02d7b..f0c0feb3f 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/FexPreset.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/FexPreset.kt @@ -1,42 +1,33 @@ package com.droiddeck.launcher.core -/** - * FEXCore presets for the x86 games the Steam client launches, Bannerlator's table carried over - * so a preset means the same thing in both apps. Each is a set of FEX_* variables put into the - * session's environment; the games under FEX inherit them from the client. The default is FEX's - * own defaults - no variables at all - which is what every session has run on so far. - * - * TSO = x86's total store ordering emulated on ARM: safest, slowest. MULTIBLOCK compiles more per - * block. X87REDUCEDPRECISION trades x87 exactness for speed. SMCCHECKS=none is the risky one - - * anything that writes its own code at runtime (JIT, .NET, DRM) can misbehave. DENUVO keeps the - * checks at full and hides the hypervisor bit, which its anti-tamper looks for. - */ +import com.droiddeck.launcher.R + object FexPreset { - class Preset(val id: String, val label: String, val detail: String, val env: List) + class Preset(val id: String, val label: Int, val detail: Int, val env: List) private fun tso(main: Int, vector: Int, memcpy: Int, halfBarrier: Int) = listOf( "FEX_TSOENABLED=$main", "FEX_VECTORTSOENABLED=$vector", "FEX_MEMCPYSETTSOENABLED=$memcpy", "FEX_HALFBARRIERTSOENABLED=$halfBarrier", ) val all: List = listOf( - Preset("", "FEX defaults", "Uses FEX defaults.", emptyList()), - Preset("STABILITY", "Stability", "Safest, slowest settings.", tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=0")), - Preset("COMPATIBILITY", "Compatibility", "Full TSO with multiblock.", tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=1")), - Preset("INTERMEDIATE", "Intermediate", "Balanced TSO with reduced x87 precision.", tso(1, 0, 0, 1) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")), - Preset("PERFORMANCE", "Performance", "All TSO disabled; multiblock.", tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")), - Preset("PERFORMANCE_TSO", "Performance + TSO", "Performance settings with main TSO enabled.", tso(1, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")), - Preset("EXTREME", "Extreme", "Disables self-modifying-code checks. JIT games and DRM may break.", + Preset("", R.string.fex_default_label, R.string.fex_default_detail, emptyList()), + Preset("STABILITY", R.string.fex_stability_label, R.string.fex_stability_detail, tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=0")), + Preset("COMPATIBILITY", R.string.fex_compatibility_label, R.string.fex_compatibility_detail, tso(1, 1, 1, 1) + listOf("FEX_X87REDUCEDPRECISION=0", "FEX_MULTIBLOCK=1")), + Preset("INTERMEDIATE", R.string.fex_intermediate_label, R.string.fex_intermediate_detail, tso(1, 0, 0, 1) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")), + Preset("PERFORMANCE", R.string.fex_performance_label, R.string.fex_performance_detail, tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")), + Preset("PERFORMANCE_TSO", R.string.fex_performance_tso_label, R.string.fex_performance_tso_detail, tso(1, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1")), + Preset("EXTREME", R.string.fex_extreme_label, R.string.fex_extreme_detail, tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=none", "FEX_DISABLEL2CACHE=1", "FEX_DYNAMICL1CACHE=1", "FEX_DYNAMICL1CACHEINCREASECOUNTHEURISTIC=250", "FEX_DYNAMICL1CACHEDECREASECOUNTHEURISTIC=50")), - Preset("EXTREME_TSO", "Extreme + TSO", "Extreme settings with main TSO enabled.", + Preset("EXTREME_TSO", R.string.fex_extreme_tso_label, R.string.fex_extreme_tso_detail, tso(1, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=none", "FEX_DISABLEL2CACHE=1", "FEX_DYNAMICL1CACHE=1", "FEX_DYNAMICL1CACHEINCREASECOUNTHEURISTIC=250", "FEX_DYNAMICL1CACHEDECREASECOUNTHEURISTIC=50")), - Preset("EXTREME_GN", "Extreme-gn", "Performance with TSC and metadata hints. Try before Extreme.", + Preset("EXTREME_GN", R.string.fex_extreme_gn_label, R.string.fex_extreme_gn_detail, tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMALLTSCSCALE=1", "FEX_VOLATILEMETADATA=1")), - Preset("DENUVO", "Denuvo", "Performance with full code checks and the hypervisor bit hidden.", + Preset("DENUVO", R.string.fex_denuvo_label, R.string.fex_denuvo_detail, tso(0, 0, 0, 0) + listOf("FEX_X87REDUCEDPRECISION=1", "FEX_MULTIBLOCK=1", "FEX_SMCCHECKS=full", "FEX_HIDEHYPERVISORBIT=1")), ) fun byId(id: String): Preset = all.firstOrNull { it.id == id } ?: all[0] - /** The variables for the session's environment, in KEY=VALUE form; empty for the default. */ + /** Game-launch variables in KEY=VALUE form. */ fun env(id: String): List = byId(id).env } diff --git a/app/src/main/java/com/droiddeck/launcher/core/FileUtils.java b/app/src/main/java/com/droiddeck/launcher/core/FileUtils.java index 42008fb97..8190e2877 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/FileUtils.java +++ b/app/src/main/java/com/droiddeck/launcher/core/FileUtils.java @@ -104,6 +104,7 @@ public final class FileUtils { public static String sizeToString(long bytes) { if (bytes >= 1L << 30) return String.format(java.util.Locale.US, "%.1f GB", bytes / (float) (1L << 30)); if (bytes >= 1L << 20) return String.format(java.util.Locale.US, "%.0f MB", bytes / (float) (1L << 20)); + if (bytes >= 1L << 10) return String.format(java.util.Locale.US, "%.0f KB", bytes / (float) (1L << 10)); return bytes + " B"; } } diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt new file mode 100644 index 000000000..11975edd3 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt @@ -0,0 +1,38 @@ +package com.droiddeck.launcher.core + +object GameEnvironment { + data class Config( + val shared: Map = emptyMap(), + val games: Map> = emptyMap(), + ) { + fun entries(scope: String) = if (scope.isEmpty()) shared else games[scope].orEmpty() + + fun withEntries(scope: String, entries: Map): Config = + if (scope.isEmpty()) copy(shared = entries.toMap()) + else copy(games = if (entries.isEmpty()) games - scope else games + (scope to entries.toMap())) + } + + private val namePattern = Regex("[A-Za-z_][A-Za-z0-9_]*") + private val unused = setOf( + "WINEESYNC", "WINENTSYNC", "WINE_FAST_YIELD", "WINE_DO_NOT_CREATE_DXGI_DEVICE_MANAGER", + "WINE_NEW_MEDIASOURCE", "WRAPPER_MAX_IMAGE_COUNT", "WRAPPER_DMAHEAP_CACHED", + "ALSA_LATENCY_MS", "ALSA_VOLUME", "ALSA_BASS_BOOST", "ALSA_PERFORMANCE_MODE", + "DXVK_ASYNC", "DXVK_GPLASYNCCACHE", + ) + + fun validName(name: String) = namePattern.matches(name) + fun supported(name: String) = name !in unused && !name.startsWith("BOX64_") && !name.startsWith("BOX86_") + fun validValue(value: String) = '\u0000' !in value && value.length <= 8192 + fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true) + + fun defaults(preset: String): Map = linkedMapOf( + "MESA_SHADER_CACHE_DISABLE" to "false", + "VKD3D_FEATURE_LEVEL" to "12_2", + "VKD3D_SHADER_MODEL" to "6_9", + ).apply { + FexPreset.env(preset).forEach { put(it.substringBefore('='), it.substringAfter('=')) } + } + + fun effective(config: Config, preset: String, scope: String): Map = + defaults(preset) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty() +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt new file mode 100644 index 000000000..0904c5b2a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt @@ -0,0 +1,43 @@ +package com.droiddeck.launcher.core + +import com.droiddeck.launcher.R + +object GameEnvironmentOptions { + enum class Type { TOGGLE, CHOICE, MULTIPLE, NUMBER, TEXT } + data class Option(val name: String, val value: String, val detail: Int, val type: Type, val choices: List = emptyList()) + + val all = listOf( + Option("MESA_SHADER_CACHE_DISABLE", "false", R.string.game_env_cache, Type.TOGGLE, listOf("false", "true")), + Option("VKD3D_FEATURE_LEVEL", "12_2", R.string.game_env_feature, Type.CHOICE, listOf("12_2", "12_1", "12_0", "11_1", "11_0")), + Option("VKD3D_SHADER_MODEL", "6_9", R.string.game_env_shader, Type.CHOICE, listOf("6_9", "6_8", "6_7", "6_6", "6_5", "6_4", "6_3", "6_2", "6_1", "6_0", "5_1")), + Option("VKD3D_CONFIG", "nodxr", R.string.game_env_vkd3d_config, Type.MULTIPLE, listOf("nodxr", "single_queue", "no_upload_hvv")), + Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")), + Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")), + Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")), + Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")), + Option("DXVK_HUD", "fps", R.string.game_env_hud, Type.MULTIPLE, listOf("scale=0.5", "scale=0.7", "opacity=0.5", "opacity=0.7", "devinfo", "fps", "frametimes", "submissions", "drawcalls", "pipelines", "descriptors", "memory", "gpuload", "version", "api", "cs", "compiler", "samplers")), + Option("DXVK_CONFIG", "dxvk.maxFrameRate = 60", R.string.game_env_dxvk_config, Type.TEXT), + Option("VKD3D_FRAME_RATE", "60", R.string.game_env_vkd3d_limit, Type.NUMBER), + Option("mesa_glthread", "true", R.string.game_env_glthread, Type.TOGGLE, listOf("false", "true")), + Option("ZINK_DESCRIPTORS", "auto", 0, Type.CHOICE, listOf("auto", "lazy", "cached", "notemplates")), + Option("ZINK_DEBUG", "nir", 0, Type.MULTIPLE, listOf("nir", "spirv", "tgsi", "validation", "sync", "compact", "noreorder")), + Option("SteamDeck", "0", 0, Type.TOGGLE, listOf("0", "1")), + Option("FD_DEV_FEATURES", "enable_tp_ubwc_flag_hint=1", 0, Type.MULTIPLE, listOf("enable_tp_ubwc_flag_hint=1", "storage_8bit=1")), + Option("TU_DEBUG", "forcecb", 0, Type.MULTIPLE, listOf("forcecb", "nocb", "startup", "deck_emu", "nir", "nobin", "sysmem", "gmem", "forcebin", "layout", "noubwc", "nomultipos", "nolrz", "nolrzfc", "perf", "perfc", "flushall", "syncdraw", "push_consts_per_stage", "rast_order", "unaligned_store", "log_skip_gmem_ops", "dynamic", "bos", "3d_load", "fdm", "noconform", "rd")), + Option("IR3_SHADER_DEBUG", "nouboopt", 0, Type.MULTIPLE, listOf("nouboopt", "nopreamble", "noearlypreamble")), + Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT), + Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT), + Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER), + Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")), + Option("WINEDLLOVERRIDES", "", 0, Type.TEXT), + Option("GALLIUM_HUD", "simple", 0, Type.MULTIPLE, listOf("simple", "fps", "frametime")), + ) + + fun find(name: String): Option? = all.firstOrNull { it.name == name } + + fun toggle(value: String, choice: String): String { + val selected = value.split(',').filter { it.isNotEmpty() }.toMutableSet() + if (!selected.remove(choice)) selected.add(choice) + return selected.joinToString(",") + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt index d73352af7..79334af3b 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt @@ -64,7 +64,8 @@ object HostProcess { } } - private fun pidOf(process: Process): Int = try { + @JvmStatic + fun pidOf(process: Process): Int = try { val field = process.javaClass.getDeclaredField("pid") field.isAccessible = true val pid = field.getInt(process) diff --git a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt index 103bf0556..4155a29dd 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -1,6 +1,6 @@ package com.droiddeck.launcher.core -import android.content.ContentResolver +import android.content.Context import android.os.Build import android.provider.Settings @@ -14,17 +14,53 @@ enum class PhantomProcessStatus { } object PhantomProcessLimit { - const val ADB_COMMAND = "adb shell settings put global settings_enable_monitor_phantom_procs false" - const val SHELL_COMMAND = "settings put global settings_enable_monitor_phantom_procs false" private const val SETTING = "settings_enable_monitor_phantom_procs" - fun adbCommand(enabled: Boolean): String = - "adb shell settings put global $SETTING ${if (enabled) "true" else "false"}" + private const val MAX_PHANTOM = "2147483647" + private const val PREFS = "phantom-process-limit" + private const val PREF_ANDROID_12_OFF = "android12-off" - fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus { + fun usesDeviceConfig(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk == Build.VERSION_CODES.S + + fun shellCommands(enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): List = when { + usesDeviceConfig(sdk) && enabled -> listOf( + "device_config delete activity_manager max_phantom_processes", + "device_config set_sync_disabled_for_tests none", + ) + usesDeviceConfig(sdk) -> listOf( + "device_config set_sync_disabled_for_tests persistent", + "device_config put activity_manager max_phantom_processes $MAX_PHANTOM", + ) + else -> listOf("settings put global $SETTING ${if (enabled) "true" else "false"}") + } + + fun verifyCommand(sdk: Int = Build.VERSION.SDK_INT): String = + if (usesDeviceConfig(sdk)) "device_config get activity_manager max_phantom_processes" + else "settings get global $SETTING" + + fun verified(output: String, enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): Boolean { + val value = output.trim() + return if (usesDeviceConfig(sdk)) (value == MAX_PHANTOM) != enabled + else value == if (enabled) "true" else "false" + } + + fun adbCommand(enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): String = + shellCommands(enabled, sdk).joinToString(" && ") { "adb shell $it" } + + fun adbCommand(): String = adbCommand(false) + + fun rememberAndroid12(context: Context, off: Boolean) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(PREF_ANDROID_12_OFF, off).apply() + } + + fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus { if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE + if (usesDeviceConfig(sdk)) { + val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false) + return if (off) PhantomProcessStatus.DISABLED else PhantomProcessStatus.UNREADABLE + } val global = try { - Settings.Global.getString(resolver, SETTING) + Settings.Global.getString(context.contentResolver, SETTING) } catch (_: Exception) { return PhantomProcessStatus.UNREADABLE } @@ -57,6 +93,8 @@ object PhantomProcessLimit { null } + fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE + fun blocksSteam(status: PhantomProcessStatus): Boolean = status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED @@ -69,20 +107,20 @@ object PhantomProcessLimit { } fun instructions(status: PhantomProcessStatus): String = when (status) { - PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again." - PhantomProcessStatus.UNSET -> "This setting is unset, so the ROM default applies and may enforce the limit. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again." - PhantomProcessStatus.UNREADABLE -> "DroidDeck could not read the setting. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again." + PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence() + " If that is not possible, connect this device to a computer with ADB and run the command below. Return here and check again." PhantomProcessStatus.DISABLED -> "Steam sessions can start." PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit." } fun gateInstructions(status: PhantomProcessStatus): String = when (status) { - PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options." - PhantomProcessStatus.UNSET -> "The ROM default may enforce this limit. Explicitly turn off “Restrict child processes” in Developer options." - PhantomProcessStatus.UNREADABLE -> "DroidDeck could not check this setting. Turn off “Restrict child processes” in Developer options." + PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence() else -> instructions(status) } + fun fixSentence(sdk: Int = Build.VERSION.SDK_INT): String = + if (hasDeveloperToggle(sdk)) "Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards." + else "This Android version has no switch for it. Use Wireless debugging to change it from this device." + fun reportValue(status: PhantomProcessStatus): String = when (status) { PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)" PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)" diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt index 82b6e4d63..c97ba3a86 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt @@ -6,7 +6,9 @@ import android.net.nsd.NsdServiceInfo import com.flyfishxu.kadb.Kadb import com.flyfishxu.kadb.cert.KadbCert import java.io.File +import java.net.Inet4Address import java.net.InetAddress +import java.net.NetworkInterface import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean @@ -19,6 +21,7 @@ object WirelessAdbFix { private const val KEY_FILE = "wireless-adb-key.pem" private const val HOST_FILE = "wireless-adb-host.txt" private const val CONNECTION_FILE = "wireless-adb-connection.txt" + const val LOOPBACK = "127.0.0.1" private data class SavedConnection(val host: String, val port: Int?) @@ -76,9 +79,27 @@ object WirelessAdbFix { } /** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */ + fun isLocalAddress(address: InetAddress): Boolean = runCatching { + if (address.isLoopbackAddress) return true + NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().any { network -> + network.inetAddresses.toList().any { it.address.contentEquals(address.address) } + } + }.getOrDefault(address is Inet4Address) + + fun localConnectPort(context: Context): Int? = + tlsPortProperty() + ?: findConnectPort(context, LOOPBACK) + + private fun tlsPortProperty(): Int? = runCatching { + Class.forName("android.os.SystemProperties").getMethod("get", String::class.java) + .invoke(null, "service.adb.tls.port") as? String + }.getOrNull()?.trim()?.toIntOrNull()?.takeIf { it in 1..65535 } + fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12): Int? { val manager = context.applicationContext.getSystemService(Context.NSD_SERVICE) as NsdManager - val expectedAddress = runCatching { InetAddress.getByName(pairedHost).address }.getOrNull() ?: return null + val paired = runCatching { InetAddress.getByName(pairedHost) }.getOrNull() ?: return null + val matches: (InetAddress) -> Boolean = + if (paired.isLoopbackAddress) ::isLocalAddress else { address -> address.address.contentEquals(paired.address) } val resolvedPort = AtomicInteger(-1) val finished = AtomicBoolean(false) val latch = CountDownLatch(1) @@ -101,8 +122,8 @@ object WirelessAdbFix { } override fun onServiceResolved(serviceInfo: NsdServiceInfo) { - val address = serviceInfo.host?.address - if (address != null && address.contentEquals(expectedAddress) && finished.compareAndSet(false, true)) { + val address = serviceInfo.host + if (address != null && matches(address) && finished.compareAndSet(false, true)) { resolvedPort.set(serviceInfo.port) latch.countDown() } else { @@ -148,14 +169,16 @@ object WirelessAdbFix { fun setChildProcessLimit(context: Context, host: String, port: Int, enabled: Boolean) { loadOrCreateIdentity(context.applicationContext) Kadb.create(host, port).use { adb -> - val value = if (enabled) "true" else "false" - val change = adb.shell("settings put global settings_enable_monitor_phantom_procs $value") - check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } } - val result = adb.shell("settings get global settings_enable_monitor_phantom_procs") - check(result.exitCode == 0 && result.output.trim() == value) { + PhantomProcessLimit.shellCommands(enabled).forEach { command -> + val change = adb.shell(command) + check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } } + } + val result = adb.shell(PhantomProcessLimit.verifyCommand()) + check(result.exitCode == 0 && PhantomProcessLimit.verified(result.output, enabled)) { "Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}" } } + if (PhantomProcessLimit.usesDeviceConfig()) PhantomProcessLimit.rememberAndroid12(context, !enabled) saveConnection(context, host, port) } diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt new file mode 100644 index 000000000..d4645962a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt @@ -0,0 +1,270 @@ +package com.droiddeck.launcher.core + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.RemoteInput +import android.app.Service +import android.content.Context +import android.content.Intent +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo +import android.os.Build +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import com.droiddeck.launcher.MainActivity +import com.droiddeck.launcher.R +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +class WirelessAdbPairingService : Service() { + sealed interface Stage { + data object Idle : Stage + data object Waiting : Stage + data class CodeNeeded(val error: String? = null) : Stage + data class Working(val step: String) : Stage + data object Done : Stage + data class Failed(val error: String) : Stage + } + + private val main = Handler(Looper.getMainLooper()) + private var nsd: NsdManager? = null + private var discovery: NsdManager.DiscoveryListener? = null + private var pairingHost: String? = null + private var pairingPort: Int? = null + @Volatile private var working = false + private val timeout = Runnable { finish(Stage.Failed("Timed out waiting for the pairing pop-up. Try again from DroidDeck.")) } + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_CODE -> { + val code = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_CODE) + ?.filter(Char::isDigit)?.toString().orEmpty() + onCode(code) + } + ACTION_CANCEL -> finish(Stage.Idle) + else -> begin() + } + return START_NOT_STICKY + } + + private fun begin() { + pairingHost = null + pairingPort = null + working = false + publish(Stage.Waiting) + startForeground(NOTIFICATION_ID, notification(Stage.Waiting)) + startDiscovery() + main.removeCallbacks(timeout) + main.postDelayed(timeout, TIMEOUT_MS) + } + + private fun startDiscovery() { + stopDiscovery() + val manager = getSystemService(Context.NSD_SERVICE) as NsdManager + val listener = object : NsdManager.DiscoveryListener { + override fun onDiscoveryStarted(serviceType: String) = Unit + override fun onServiceFound(serviceInfo: NsdServiceInfo) { + if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return + runCatching { manager.resolveService(serviceInfo, resolveListener()) } + } + override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit + override fun onDiscoveryStopped(serviceType: String) = Unit + override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { + main.post { finish(Stage.Failed("Could not look for the pairing pop-up ($errorCode). Check that Wi-Fi is on.")) } + } + override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit + } + runCatching { manager.discoverServices("$PAIRING_TYPE.", NsdManager.PROTOCOL_DNS_SD, listener) } + .onSuccess { nsd = manager; discovery = listener } + .onFailure { finish(Stage.Failed("Could not look for the pairing pop-up: ${it.localizedMessage}")) } + } + + private fun resolveListener() = object : NsdManager.ResolveListener { + override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit + override fun onServiceResolved(serviceInfo: NsdServiceInfo) { + val address = serviceInfo.host ?: return + if (!WirelessAdbFix.isLocalAddress(address)) return + main.post { + if (working || current.value == Stage.Done) return@post + pairingHost = address.hostAddress + pairingPort = serviceInfo.port + if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded()) + } + } + } + + private fun onCode(code: String) { + val host = pairingHost + val port = pairingPort + if (working) return + if (host == null || port == null) { + show(Stage.Waiting) + return + } + if (code.length != 6) { + show(Stage.CodeNeeded("Enter all 6 digits of the code")) + return + } + working = true + show(Stage.Working("Pairing…")) + Thread({ + val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } } + if (paired.isFailure) { + main.post { + working = false + pairingPort = null + show(Stage.CodeNeeded("That code didn't work. Open the pairing pop-up again and enter its new code.")) + } + return@Thread + } + main.post { + stopDiscovery() + show(Stage.Working("Paired. Connecting…")) + } + val result = runCatching { + val connectPort = WirelessAdbFix.localConnectPort(this) + ?: error("Paired, but the Wireless debugging port was not found. Keep Wireless debugging on and try again.") + main.post { show(Stage.Working("Applying the setting…")) } + WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false) + } + main.post { + working = false + finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: "Wireless debugging command failed") } ?: Stage.Done) + } + }, "wireless-adb-pairing").start() + } + + private fun show(stage: Stage) { + publish(stage) + getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, notification(stage)) + } + + private fun finish(stage: Stage) { + main.removeCallbacks(timeout) + stopDiscovery() + publish(stage) + val manager = getSystemService(NotificationManager::class.java) + if (stage is Stage.Done || stage is Stage.Failed) { + manager?.notify(NOTIFICATION_ID, notification(stage)) + stopForeground(STOP_FOREGROUND_DETACH) + } else { + stopForeground(STOP_FOREGROUND_REMOVE) + manager?.cancel(NOTIFICATION_ID) + } + stopSelf() + } + + private fun stopDiscovery() { + val listener = discovery ?: return + runCatching { nsd?.stopServiceDiscovery(listener) } + discovery = null + } + + override fun onDestroy() { + main.removeCallbacks(timeout) + stopDiscovery() + if (current.value.let { it is Stage.Waiting || it is Stage.CodeNeeded || it is Stage.Working }) publish(Stage.Idle) + super.onDestroy() + } + + private fun notification(stage: Stage): Notification { + val manager = getSystemService(NotificationManager::class.java) + manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Wireless debugging setup", + NotificationManager.IMPORTANCE_HIGH).apply { + description = "Asks for the Wireless debugging pairing code while Settings is open" + 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, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE) + val builder = Notification.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_stat_session) + .setContentIntent(open) + .setShowWhen(false) + .setCategory(Notification.CATEGORY_STATUS) + when (stage) { + Stage.Waiting, Stage.Idle -> builder + .setContentTitle("Pair Wireless debugging") + .setContentText("Turn on Wireless debugging, then tap “Pair device with pairing code”.") + .setStyle(Notification.BigTextStyle().bigText( + "Turn on Wireless debugging, then tap “Pair device with pairing code”. Stay in Settings: the code goes in this notification.")) + .setOngoing(true) + .setOnlyAlertOnce(true) + .addAction(Notification.Action.Builder(null, "Cancel", cancel).build()) + is Stage.CodeNeeded -> { + val reply = PendingIntent.getService(this, 2, + Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CODE), + if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + else PendingIntent.FLAG_UPDATE_CURRENT) + val input = RemoteInput.Builder(KEY_CODE).setLabel("6-digit pairing code").build() + val text = stage.error ?: "Tap Enter code and type the 6 digits shown in Settings." + builder + .setContentTitle(if (stage.error == null) "Enter the Wi-Fi pairing code" else "Try the code again") + .setContentText(text) + .setStyle(Notification.BigTextStyle().bigText(text)) + .setOngoing(true) + .addAction(Notification.Action.Builder(null, "Enter code", reply).addRemoteInput(input).build()) + .addAction(Notification.Action.Builder(null, "Cancel", cancel).build()) + } + is Stage.Working -> builder + .setContentTitle("Setting up Steam") + .setContentText(stage.step) + .setProgress(0, 0, true) + .setOngoing(true) + .setOnlyAlertOnce(true) + Stage.Done -> builder + .setContentTitle("Steam is ready") + .setContentText("Tap to go back to DroidDeck. You can turn Wireless debugging off now.") + .setStyle(Notification.BigTextStyle().bigText("Tap to go back to DroidDeck. You can turn Wireless debugging off now.")) + .setAutoCancel(true) + is Stage.Failed -> builder + .setContentTitle("Wireless debugging setup stopped") + .setContentText(stage.error) + .setStyle(Notification.BigTextStyle().bigText(stage.error)) + .setAutoCancel(true) + } + return builder.build() + } + + companion object { + private const val CHANNEL_ID = "wireless-adb-pairing" + private const val NOTIFICATION_ID = 3 + private const val PAIRING_TYPE = "_adb-tls-pairing._tcp" + private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE" + private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL" + private const val KEY_CODE = "code" + private const val TIMEOUT_MS = 5 * 60_000L + + private val current = MutableStateFlow(Stage.Idle) + val stage: StateFlow = current + + private fun publish(stage: Stage) { current.value = stage } + + fun start(context: Context) { + context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID) + publish(Stage.Waiting) + val intent = Intent(context, WirelessAdbPairingService::class.java) + if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent) + } + + fun cancel(context: Context) { + if (current.value.let { it is Stage.Done || it is Stage.Failed || it is Stage.Idle }) { + publish(Stage.Idle) + return + } + context.startService(Intent(context, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL)) + } + + fun notificationsEnabled(context: Context): Boolean = + context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt index bd5a75983..3a1510402 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -1,26 +1,19 @@ package com.droiddeck.launcher.frontend import android.content.Context -import android.os.Environment import android.util.Log +import com.droiddeck.launcher.runtime.LinuxRuntime +import org.json.JSONObject import com.droiddeck.launcher.session.GameStorage import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.util.zip.CRC32 -/** - * The user's own Windows games, added to the Steam client's library. - * - * A Games folder is scanned one level deep: each subfolder is one game, and the program to launch - * is the .exe in it that looks most like the game - the one named after the folder, else the - * largest, never an installer, redistributable or crash reporter - unless the user picked one - * for that game. Each game becomes a non-Steam shortcut in the client, under the ARM64 Proton, - * with the appid the client itself would derive, so launching from the rail and from the - * client's own library are the same thing. Any number of Games folders, from anywhere on the - * device: each is bound into the session under /root/Games on its own. - */ +/** Windows game folders shared with the Steam session. */ object AddedGames { private const val TAG = "AddedGames" + private const val LIBRARY = "/mnt/droiddeck-sd" + private const val LEGACY_LIBRARY = "/mnt/bannerlator-sd" class Game( val folder: File, val name: String, val exe: File, val guestExe: String, val guestDir: String, @@ -29,6 +22,7 @@ object AddedGames { /** What steam://rungameid/ takes for a shortcut. */ val gameId: Long, val candidates: List, + val steamAppId: Int? = null, ) { fun folderName(): String = folder.name } @@ -73,7 +67,7 @@ object AddedGames { if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/") } GameStorage.effective(context)?.let { lib -> - if (path.startsWith("${lib.path}/")) return "/mnt/bannerlator-sd/" + path.removePrefix("${lib.path}/") + if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/") } return null } @@ -96,12 +90,15 @@ object AddedGames { fun scan(context: Context): List { val out = ArrayList() - for (root in roots(context)) { - val dir = root.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") }, + ) + 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()) scanGame(context, folder, out) } - return out + return out.distinctBy { it.folder.canonicalPath } } private fun scanGame(context: Context, folder: File, out: MutableList) { @@ -113,12 +110,26 @@ object AddedGames { if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return } val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return val name = folder.name - val crc = CRC32().apply { update(("\"$guestExe\"" + name).toByteArray()) }.value + // Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put. + val crc = CRC32().apply { update(("\"${guestExe.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value val appId = crc or 0x80000000L - out.add(Game(folder, name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, candidates)) + 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)) } } + private fun steamRoute(root: File, appId: Long): Int? = runCatching { + val users = File(root, "config/loginusers.vdf").readText() + val blocks = Regex(""""(\d{5,})"\s*\{([^}]*)\}""") + val recent = blocks.findAll(users).firstOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) } + ?: return@runCatching null + val account = recent.groupValues[1].toLong() - 76561197960265728L + JSONObject(File(root, "userdata/$account/config/.droiddeck-routes.json").readText()) + .optInt(appId.toString()).takeIf { it > 0 } + }.getOrNull() + /** The list the session hands the runtime's shortcuts writer; one file per session start. */ fun writeListing(context: Context, games: List): File { val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() } @@ -126,6 +137,7 @@ object AddedGames { games.forEachIndexed { i, g -> if (i > 0) json.append(',') 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) // 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. @@ -145,5 +157,5 @@ object AddedGames { return guestPath(context, file) } - private fun quote(s: String) = "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + private fun quote(s: String): String = JSONObject.quote(s) } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt index 29191c37e..80b8091be 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -23,6 +23,9 @@ object Library { val hero: File? = null, val lastPlayed: Long = 0L, val gameFiles: File? = null, val protonPrefix: File? = null, ) + /** The [SteamGame.library] of a game added to the library rather than installed by Steam. */ + const val ADDED = "added" + class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null) class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List) { /** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */ @@ -163,7 +166,13 @@ object Library { ) /** The emulator's name for a program path from the rail ("ARMSX2"), or null. */ - fun nameForProgram(program: String?): String? = specs.firstOrNull { it.program == program }?.name + fun nameForProgram(program: String?): String? = + if (program == com.droiddeck.launcher.runtime.FlatpakManager.LAUNCHER || program == com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER) { + com.droiddeck.launcher.session.SessionState.programArgs.firstOrNull()?.let { flatpakNames[it] ?: it.substringAfterLast('.') } + } else specs.firstOrNull { it.program == program }?.name + + /** Flatpak apps' and AppImages' names by id or directory, as launched: the session only knows that. */ + val flatpakNames = java.util.concurrent.ConcurrentHashMap() /** * Whether a program from the rail runs at the panel's own resolution rather than the session's diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/DriverBundle.kt b/app/src/main/java/com/droiddeck/launcher/gpu/DriverBundle.kt new file mode 100644 index 000000000..169682101 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/gpu/DriverBundle.kt @@ -0,0 +1,196 @@ +package com.droiddeck.launcher.gpu + +import android.content.Context +import android.net.Uri +import android.util.Log +import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.session.SessionPrefs +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.util.zip.ZipInputStream + +/** + * An all-in-one driver package: one zip carrying both halves of a matched pair, the display + * (Android, bionic) driver in one directory and the runtime (Linux, glibc) driver in another, + * indexed by a root `manifest.json` - DroidDeck's own DD-Turnip releases (Droid-Deck/Drivers): + * + * ``` + * manifest.json {"package", "version", "drivers": {"android": {"path"}, "linux": {"path"}}} + * android/ meta.json (AdrenoTools) + libvulkan_freedreno.so + * linux/ meta.json + libvulkan_freedreno.so + * ``` + * + * Installing one puts each half through its own importer, with that importer's checks, and + * remembers the two as one bundle: picking either half sets both, and deleting either deletes both, + * so a bundle is always used whole. Zips of the older kind, one driver each, never reach this. + */ +object DriverBundle { + private const val TAG = "DriverBundle" + private const val PREFS = "driver_bundles" + private const val MANIFEST = "manifest.json" + /** Refuses a zip that unpacks to more than this: both halves together are about 30 MB. */ + private const val MAX_BYTES = 512L shl 20 + + class Manifest(val name: String, val version: String, val tag: String, val androidPath: String, val linuxPath: String) + + /** An installed bundle: [androidId] in TurnipDriver's list, [linuxId] in LinuxVulkanDriverManager's. */ + class Bundle(val id: String, val name: String, val version: String, val androidId: String, val linuxId: String) { + /** "DD-Turnip 0.1.0". */ + val label: String get() = if (version.isEmpty()) name else "$name $version" + } + + /** The manifest of a bundle, or null when [json] is not one (both halves, in two directories). */ + fun parseManifest(json: JSONObject): Manifest? { + val drivers = json.optJSONObject("drivers") ?: return null + val android = cleanPath(drivers.optJSONObject("android")?.optString("path").orEmpty()) ?: return null + val linux = cleanPath(drivers.optJSONObject("linux")?.optString("path").orEmpty()) ?: return null + if (android == linux) return null + return Manifest( + json.optString("package").ifEmpty { "Driver bundle" }, json.optString("version"), + json.optString("tag"), android, linux, + ) + } + + private fun cleanPath(path: String): String? { + val p = path.trim().trim('/') + return p.takeIf { it.isNotEmpty() && it.split('/').none { part -> part.isEmpty() || part == "." || part == ".." } } + } + + /** True when the zip at [uri] is a bundle rather than a single driver. */ + fun isBundle(context: Context, uri: Uri): Boolean = try { + context.contentResolver.openInputStream(uri)?.use { input -> + ZipInputStream(input).use { zip -> + generateSequence { zip.nextEntry }.firstOrNull { !it.isDirectory && it.name == MANIFEST } + ?.let { parseManifest(JSONObject(zip.readBytes().toString(Charsets.UTF_8))) } != null + } + } ?: false + } catch (e: Exception) { + Log.w(TAG, "reading $uri as a bundle", e) + false + } + + /** + * Install both halves of the bundle at [uri]. Both or neither: a half that is refused removes + * the one already in. Throws [IllegalArgumentException] with a user-facing reason when the zip + * is not a usable bundle, [IOException] on read failures. + */ + fun install(context: Context, uri: Uri): Bundle { + val work = File(context.cacheDir, "bundle-${System.nanoTime()}") + val td = TurnipDriver(context) + val lm = LinuxVulkanDriverManager(context) + var androidId: String? = null + try { + unzip(context, uri, work) + val manifest = File(work, MANIFEST).takeIf { it.isFile } + ?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() } + ?: throw IllegalArgumentException("Not a driver bundle: no manifest.json naming an android and a linux driver") + val androidDir = File(work, manifest.androidPath) + val linuxDir = File(work, manifest.linuxPath) + + val androidStage = td.newStagingDir() + androidId = try { + androidDir.listFiles()?.filter { it.isFile }?.forEach { it.copyTo(File(androidStage, it.name)) } + td.adopt(androidStage, manifest.name) + } catch (e: Exception) { + FileUtils.delete(androidStage) + throw e + } + + val linuxStage = lm.newStagingDir() + val linuxId = try { + val library = linuxDir.listFiles()?.firstOrNull { it.isFile && it.name.startsWith("libvulkan_freedreno") && it.name.endsWith(".so") } + library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.LIB_NAME)) + val meta = File(linuxDir, LinuxVulkanDriverManager.META_NAME).takeIf { it.isFile } + ?.let { runCatching { JSONObject(FileUtils.readString(it)) }.getOrNull() } + lm.adopt(linuxStage, library?.name, meta, manifest.name) + } catch (e: Exception) { + FileUtils.delete(linuxStage) + throw e + } + + val base = LinuxVulkanDriverManager.sanitizeId(manifest.tag.ifEmpty { "${manifest.name}-${manifest.version}" }) + val saved = registry(context) + var id = base + var n = 2 + while (saved.contains(id)) id = "$base-${n++}" + val bundle = Bundle(id, manifest.name, manifest.version, androidId, linuxId) + saved.edit().putString(id, JSONObject().put("name", bundle.name).put("version", bundle.version) + .put("android", androidId).put("linux", linuxId).toString()).apply() + Log.i(TAG, "installed bundle $id: display $androidId, runtime $linuxId") + return bundle + } catch (e: Exception) { + androidId?.let { td.remove(it) } + throw e + } finally { + FileUtils.delete(work) + } + } + + private fun unzip(context: Context, uri: Uri, dest: File) { + val root = dest.canonicalFile + var total = 0L + context.contentResolver.openInputStream(uri)?.use { input -> + ZipInputStream(input).use { zip -> + for (entry in generateSequence { zip.nextEntry }) { + if (entry.isDirectory) continue + val out = File(root, entry.name).canonicalFile + if (!out.path.startsWith(root.path + File.separator)) throw IllegalArgumentException("Not a driver bundle: ${entry.name} points outside it") + out.parentFile?.mkdirs() + out.outputStream().use { sink -> + val buf = ByteArray(1 shl 16) + while (true) { + val r = zip.read(buf) + if (r <= 0) break + total += r + if (total > MAX_BYTES) throw IllegalArgumentException("Not a driver bundle: it unpacks to more than ${MAX_BYTES shr 20} MB") + sink.write(buf, 0, r) + } + } + } + } + } ?: throw IOException("cannot open $uri") + } + + /** Every installed bundle whose two halves are both still there. */ + fun all(context: Context): List { + val td = TurnipDriver(context) + val lm = LinuxVulkanDriverManager(context) + return registry(context).all.mapNotNull { (id, raw) -> + runCatching { + val j = JSONObject(raw as String) + Bundle(id, j.getString("name"), j.optString("version"), j.getString("android"), j.getString("linux")) + }.getOrNull() + }.filter { td.isInstalled(it.androidId) && lm.isInstalled(it.linuxId) }.sortedBy { it.id } + } + + fun get(context: Context, id: String): Bundle? = all(context).firstOrNull { it.id == id } + + /** The bundle [driverId] is a half of, in the runtime list when [linux], else the display list. */ + fun containing(context: Context, driverId: String, linux: Boolean): Bundle? = + all(context).firstOrNull { (if (linux) it.linuxId else it.androidId) == driverId } + + /** The bundle both drivers are set to right now, if they are one. */ + fun active(context: Context): Bundle? { + val android = SessionPrefs.androidDriver(context) + val linux = SessionPrefs.linuxDriver(context) + return all(context).firstOrNull { it.androidId == android && it.linuxId == linux } + } + + /** Set both halves as the drivers in use. */ + fun select(context: Context, bundle: Bundle) { + SessionPrefs.setAndroidDriver(context, bundle.androidId) + SessionPrefs.setLinuxDriver(context, bundle.linuxId) + } + + /** Delete both halves; a driver still set to either goes back to its default. */ + fun remove(context: Context, bundle: Bundle) { + TurnipDriver(context).remove(bundle.androidId) + LinuxVulkanDriverManager(context).removeDriver(bundle.linuxId) + if (SessionPrefs.linuxDriver(context) == bundle.linuxId) SessionPrefs.setLinuxDriver(context, "") + registry(context).edit().remove(bundle.id).apply() + Log.i(TAG, "removed bundle ${bundle.id}") + } + + private fun registry(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) +} diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt b/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt new file mode 100644 index 000000000..f3b28fe38 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt @@ -0,0 +1,112 @@ +package com.droiddeck.launcher.gpu + +import com.droiddeck.launcher.gpu.GpuInfo.Family + +/** + * The release drivers as matched pairs: a display build (the app's compositor, bionic) and a Linux + * build (the runtime, glibc) that were made to run together. Mixing a runtime driver carrying a + * patch with a display driver that lacks it is where the hard-to-read bugs come from, so the app + * installs and selects both halves of one pair at once. + * + * - Banners-Turnip publishes each variant as a set in every release (`Turnip-.zip` + * and `...-Linux.zip`), rebuilt from upstream Mesa as it moves: the pair is one variant of the + * newest release that carries both halves. + * - WinNative ships its display (`v1.x`) and Linux (`linux-v0.x`) builds as two release lines with + * their own numbers: the pair is the newest of each, of one flavour (Balanced or Performance). + * - DroidDeck's DD-Turnip ships both halves in one zip per release (DriverBundle): the pair is the + * newest bundle, and it can never be mixed. + */ +object DriverPairs { + const val BANNER = "banner" + const val BANNER_A8XX = "banner-a8xx" + const val BANNER_710 = "banner-710-720-test" + const val BANNER_ONEUI = "banner-8g2-oneui" + const val WN_BALANCED = "wn-b" + const val WN_PERFORMANCE = "wn-p" + const val DD_TURNIP = "dd-turnip" + /** Each DD-Turnip release is its own pair: "dd-turnip:DD-Turnip-v0.1.0". */ + fun ddTurnip(tag: String) = "$DD_TURNIP:$tag" + + class DriverPair( + val key: String, + /** "Banners-Turnip · Adreno 6xx/7xx", "WinNative · Balanced". */ + val name: String, + /** The families the pair is built for; the list only offers it on those unless asked. */ + val families: Set, + val display: TurnipReleases.Asset?, + val linux: TurnipReleases.Asset?, + /** Both halves in one zip, instead of [display] and [linux]. */ + val bundle: TurnipReleases.Asset? = null, + ) { + val complete: Boolean get() = bundle != null || (display != null && linux != null) + /** The zips to download for the pair: the bundle, or the two halves. */ + val assets: List get() = listOfNotNull(bundle ?: display, if (bundle == null) linux else null) + /** "r4 · 1.19 + 0.1.2": the build of each half. */ + val version: String + get() = listOfNotNull(bundle?.tag, display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-").removePrefix("DD-Turnip-") } + fun suits(gpu: GpuInfo) = gpu.family in families || + (gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families)) + } + + private val ALL_ADRENO = setOf(Family.A6XX, Family.A7XX, Family.A7XX_LOW, Family.A8XX, Family.ADRENO_UNKNOWN) + + private fun describe(key: String): Pair> = when { + key.startsWith(DD_TURNIP) -> "DroidDeck · DD-Turnip" to ALL_ADRENO + else -> describeFixed(key) + } + + private fun describeFixed(key: String): Pair> = when (key) { + BANNER -> "Banners-Turnip · Adreno 6xx/7xx" to setOf(Family.A6XX, Family.A7XX) + BANNER_A8XX -> "Banners-Turnip · Adreno 8xx" to setOf(Family.A8XX) + BANNER_710 -> "Banners-Turnip · Adreno 710/720/722 (test)" to setOf(Family.A7XX_LOW) + BANNER_ONEUI -> "Banners-Turnip · 8 Gen 2 on One UI" to setOf(Family.A7XX) + WN_BALANCED -> "WinNative · Balanced" to ALL_ADRENO + WN_PERFORMANCE -> "WinNative · Performance" to ALL_ADRENO + else -> key to ALL_ADRENO + } + + /** Every pair the last release check found, in the order the list shows them. */ + fun from(check: TurnipReleases.Check?): List { + val assets = check?.assets.orEmpty().filter { it.pair.isNotEmpty() } + val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE) + return assets.map { it.pair }.distinct() + .sortedBy { key -> order.indexOf(key.substringBefore(':')).let { i -> if (i < 0) order.size else i } } + .map { key -> + val (name, families) = describe(key) + val halves = assets.filter { it.pair == key } + halves.firstOrNull { it.bundle }?.let { return@map DriverPair(key, name, families, null, null, it) } + // The list keeps the newest release of each half; for Banners-Turnip the two halves + // must come from the same release, so a set missing one half in its newest release + // is offered incomplete rather than mixed with an older one. + val display = halves.firstOrNull { !it.linux } + val linux = halves.firstOrNull { it.linux } + val sameRelease = !key.startsWith(BANNER) || display?.tag == linux?.tag + DriverPair(key, name, families, display, if (sameRelease) linux else null) + } + } + + /** + * The pair Auto sets for [gpu], among the [pairs] the last release check found: the newest + * official DD-Turnip release on the Adreno 840 (840 and 840v2), WinNative Balanced on the other + * 8xx (Banners' A8xx builds still break on some first boots) and on an 840 while no DD-Turnip + * release is listed, the OneUI build for an 8 Gen 2 under One UI, the patched test builds for + * the 710/720/722, and upstream Banners-Turnip for the rest. Null when nothing fits (not Adreno). + */ + fun recommendedKey(gpu: GpuInfo, pairs: List): String? = when (gpu.family) { + Family.NOT_ADRENO -> null + Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED + Family.A7XX_LOW -> BANNER_710 + Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER + Family.A6XX -> BANNER + // KGSL gave no model: Android 16 arrived with the 8xx, so a device that new is taken as one. + Family.ADRENO_UNKNOWN -> if (android.os.Build.VERSION.SDK_INT >= 36) WN_BALANCED else BANNER + } + + /** The complete DD-Turnip pair with the highest version, or null when none is listed. */ + fun newestDdTurnip(pairs: List): String? = pairs + .filter { it.key.startsWith("$DD_TURNIP:") && it.complete } + .maxByOrNull { p -> + Regex("""(\d+)\.(\d+)\.(\d+)$""").find(p.key)?.destructured + ?.let { (major, minor, patch) -> major.toLong() * 1_000_000_000_000 + minor.toLong() * 1_000_000 + patch.toLong() } ?: -1L + }?.key +} diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt index 236c17a00..b864e837b 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.gpu import android.content.Context import android.util.Log +import com.droiddeck.launcher.R import com.droiddeck.launcher.wayland.WaylandCompositor /** @@ -9,7 +10,7 @@ import com.droiddeck.launcher.wayland.WaylandCompositor * * Both engines generate on gamescope's final output inside our compositor, so they work for any * game with nothing changed in the runtime. Win-FG is our own and needs nothing; LSFG needs the - * shader chain from the user's copy of Lossless Scaling (see [LsfgNative]). Every compositor + * shader chain from the user's copy of Lossless Scaling (see [Lossless]). Every compositor * setter is a value store on the native side, so this can be applied before the compositor is * up and changed live from the main screen while a session runs. */ @@ -26,62 +27,77 @@ object FrameGen { private const val FLOW_SCALE_WINFG = 0.60f private const val FLOW_SCALE_LSFG = 0.80f + /** LSFG's adaptive targets: it generates as many frames as it takes to reach one. */ + val ADAPTIVE_TARGETS = listOf(120, 90, 60) + private const val PREFS = "frame_gen" - fun engine(context: Context): String = - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("engine", ENGINE_OFF) ?: ENGINE_OFF - - fun multiplier(context: Context): Int = - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getInt("multiplier", 2).coerceIn(2, 4) - - fun set(context: Context, engine: String, multiplier: Int) { - context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() - .putString("engine", engine).putInt("multiplier", multiplier).apply() + /** A fixed [multiplier] (2..4), or for LSFG a [target] frame rate (0 = fixed). */ + data class Mode(val engine: String, val multiplier: Int = 2, val target: Int = 0) { + companion object { + val OFF = Mode(ENGINE_OFF) + } } - /** "Off", "Win-FG 2×", "LSFG 3×" - for the main screen. */ - fun label(context: Context): String = label(engine(context), multiplier(context)) + fun engine(context: Context): String = mode(context).engine - fun label(engine: String, multiplier: Int): String = when (engine) { - ENGINE_WINFG -> "Win-FG $multiplier×" - ENGINE_LSFG -> "LSFG $multiplier×" - else -> "Off" + fun mode(context: Context): Mode { + val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val engine = prefs.getString("engine", ENGINE_OFF) ?: ENGINE_OFF + val target = prefs.getInt("target", 0) + if (engine == ENGINE_LSFG && target in ADAPTIVE_TARGETS) return Mode(engine, target = target) + return Mode(engine, prefs.getInt("multiplier", 2).coerceIn(2, 4)) + } + + fun set(context: Context, mode: Mode) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply() + } + + /** "Off", "Win-FG 2×", "LSFG 3×", "LSFG Adaptive 90". */ + fun label(context: Context): String = label(context, mode(context)) + + fun label(context: Context, mode: Mode): String = when { + mode.engine == ENGINE_WINFG -> context.getString(R.string.frame_gen_winfg, mode.multiplier) + mode.engine == ENGINE_LSFG && mode.target > 0 -> context.getString(R.string.frame_gen_lsfg_adaptive, mode.target) + mode.engine == ENGINE_LSFG -> context.getString(R.string.frame_gen_lsfg, mode.multiplier) + else -> context.getString(R.string.frame_gen_off) } /** * Pushes the saved setting into the compositor. Returns a message for the user when the - * engine cannot run (LSFG without Lossless Scaling), or null. + * engine cannot run (LSFG without Lossless Scaling), or null. Blocks while a new or updated + * Lossless.dll is prepared. */ fun apply(context: Context, refreshHz: Float): String? { - val engine = engine(context) - val multiplier = multiplier(context) - var problem: String? = null - when (engine) { + val mode = mode(context) + when (mode.engine) { ENGINE_LSFG -> { - val status = LsfgNative.ensureCache(context) - if (status != LsfgNative.STATUS_OK) { - problem = if (status == LsfgNative.STATUS_NOT_INSTALLED) - "LSFG needs Lossless Scaling installed from the Steam client" - else "LSFG: " + LsfgNative.statusName(status) - Log.w(TAG, problem) - WaylandCompositor.nativeSetFrameGenArmed(false, 0) + val status = Lossless.sync(context) + val cache = Lossless.cacheFile(context) + if (status != LsfgNative.STATUS_OK || cache == null) { + WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) + val problem = context.getString( + if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed, + ) + Log.w(TAG, "$problem (status $status)") return problem } WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_LSFG) - WaylandCompositor.nativeSetLsfgCachePath(LsfgNative.cacheFile(context).absolutePath) + WaylandCompositor.nativeSetLsfgCachePath(cache.absolutePath) WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_LSFG, refreshHz) - WaylandCompositor.nativeSetFrameGenArmed(true, multiplier) + WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, mode.target) } ENGINE_WINFG -> { WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_WINFG) WaylandCompositor.nativeSetWinFgTuning(WINFG_MODEL, WINFG_PERF_PRESET) WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_WINFG, refreshHz) - WaylandCompositor.nativeSetFrameGenArmed(true, multiplier) + WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0) } - else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0) + else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) } - Log.i(TAG, "frame generation: $engine x$multiplier at ${refreshHz}Hz") - return problem + Log.i(TAG, "frame generation: $mode at ${refreshHz}Hz") + return null } private const val TAG = "FrameGen" diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt new file mode 100644 index 000000000..3054f0733 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt @@ -0,0 +1,80 @@ +package com.droiddeck.launcher.gpu + +import android.os.Build +import com.droiddeck.launcher.core.FileUtils +import java.io.File + +/** + * What GPU this is, in the terms the driver lists are sorted by. KGSL names the model + * ("Adreno740v2", "Adreno825"); the family decides which Turnip builds run on it at all, and the + * support level is what the app has actually been tested on (Adreno 725 and up) - an Adreno 610 + * may start, but it is not "supported" just because it is a Qualcomm chip. + */ +data class GpuInfo( + /** "Adreno 740", or the vendor's own name when this is not an Adreno. */ + val name: String, + /** The three-digit Adreno model (740, 825), or 0 when KGSL does not say. */ + val model: Int, + val family: Family, + /** The SoC as the device reports it ("SM8550", "QCS8550"), or "" when it does not. */ + val soc: String, + /** Samsung's One UI on an 8 Gen 2: its Turnip needs the OneUI build, or frames tear and flicker. */ + val oneUi8Gen2: Boolean, +) { + enum class Family(val label: String) { + A8XX("Adreno 8xx"), + /** Adreno 710/720/722: gen 7 cores cut down enough to need their own patches. */ + A7XX_LOW("Adreno 710/720/722"), + A7XX("Adreno 7xx"), + A6XX("Adreno 6xx"), + /** An Adreno whose model KGSL does not give: treated as the newest family it could be. */ + ADRENO_UNKNOWN("Adreno"), + NOT_ADRENO("Not an Adreno GPU"), + } + + enum class Support { TESTED, UNTESTED, UNSUPPORTED } + + val support: Support + get() = when { + family == Family.NOT_ADRENO -> Support.UNSUPPORTED + family == Family.A8XX -> Support.TESTED + family == Family.A7XX && model >= 725 -> Support.TESTED + else -> Support.UNTESTED + } + + /** One line for the device card and the system check. */ + val supportText: String + get() = when (support) { + Support.TESTED -> "Supported" + Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds" + else "Below tested hardware (Adreno 725 and newer): it may not run" + Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU" + } + + companion object { + fun detect(): GpuInfo { + val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() + val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid") + .firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) } + val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN }.orEmpty() else "" + val model = raw?.let { Regex("""(\d{3})""").find(it)?.groupValues?.get(1)?.toIntOrNull() } ?: 0 + val family = familyOf(adreno, model) + val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) + return GpuInfo( + name = if (!adreno) Build.HARDWARE.ifBlank { "this GPU" } else if (model > 0) "Adreno $model" else "Adreno", + model = model, family = family, soc = soc, + oneUi8Gen2 = samsung && model == 740, + ) + } + + internal fun familyOf(adreno: Boolean, model: Int): Family = when { + !adreno -> Family.NOT_ADRENO + model == 0 -> Family.ADRENO_UNKNOWN + model >= 800 -> Family.A8XX + model in listOf(710, 720, 722) -> Family.A7XX_LOW + model >= 700 -> Family.A7XX + model >= 600 -> Family.A6XX + else -> Family.ADRENO_UNKNOWN + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java index 077e230cd..c0cb48f08 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java @@ -126,9 +126,7 @@ public class LinuxVulkanDriverManager { * Linux driver; {@link IOException} on read/extract failures. */ public String installDriver(Uri zipUri, String displayName) throws IOException { - File tmpDir = new File(rootDir, ".tmp-" + System.currentTimeMillis()); - FileUtils.delete(tmpDir); - if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir); + File tmpDir = newStagingDir(); boolean keep = false; try { String soName = null; @@ -156,9 +154,32 @@ public class LinuxVulkanDriverManager { } } // The zip's own freedreno_icd.aarch64.json is dropped on purpose: its - // library_path is relative to itself, and we write an absolute one below. + // library_path is relative to itself, and adopt() writes an absolute one. } } + String id = adopt(tmpDir, soName, zipMeta, displayName); + keep = true; + return id; + } finally { + if (!keep) FileUtils.delete(tmpDir); + } + } + + /** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */ + File newStagingDir() throws IOException { + File tmpDir = new File(rootDir, ".tmp-" + System.nanoTime()); + FileUtils.delete(tmpDir); + if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir); + return tmpDir; + } + + /** + * Check a staged driver ({@link #LIB_NAME} in {@code tmpDir}, copied from {@code soName} in + * the zip), write its manifest and meta.json, and move it in. Returns the id; the caller + * deletes {@code tmpDir} when this throws. + */ + String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException { + try { if (soName == null) { throw new IllegalArgumentException("No libvulkan_freedreno*.so in this zip. An Android " + "(AdrenoTools) or -Wayland Turnip zip is not a Linux runtime driver."); @@ -212,13 +233,10 @@ public class LinuxVulkanDriverManager { if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json"); if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir); - keep = true; Log.i(TAG, "imported Linux Vulkan driver " + id + " (" + soName + ", minGlibc=" + minGlibc + ") -> " + dir); return id; } catch (org.json.JSONException e) { throw new IOException("manifest write failed: " + e.getMessage()); - } finally { - if (!keep) FileUtils.delete(tmpDir); } } diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt b/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt new file mode 100644 index 000000000..7a153b37e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt @@ -0,0 +1,187 @@ +package com.droiddeck.launcher.gpu + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.GameStorage +import com.droiddeck.launcher.session.SessionPrefs +import java.io.File +import java.security.DigestOutputStream +import java.security.MessageDigest + +/** + * LSFG's shader chain, from the user's own Lossless Scaling (Steam app 993090). + * + * The copy the Steam client installs, in any library it installs to, is taken by + * itself and taken again whenever the client updates it. Once the session has seen the account + * own the app, a Lossless.dll can also be imported by hand; it stays until the Steam copy changes + * or another is imported. The DLL is copied in and its shaders are built into a cache named after + * its contents, so a different DLL hands the compositor a different path and its engine reloads. + * Everything here blocks: call it off the main thread. + */ +object Lossless { + enum class Source { NONE, STEAM, IMPORT } + + enum class ImportResult { UPDATED, UNCHANGED, NOT_OWNED, INVALID, FAILED } + + data class State(val owned: Boolean, val ready: Boolean, val source: Source) { + companion object { + val NONE = State(owned = false, ready = false, source = Source.NONE) + } + } + + private const val TAG = "Lossless" + private const val PREFS = "lossless" + private const val KEY_OWNED = "owned" + private const val KEY_ID = "id" + private const val KEY_SOURCE = "source" + private const val KEY_STEAM_STAMP = "steamStamp" + private const val STEAM_DLL = "steamapps/common/Lossless Scaling/Lossless.dll" + private const val UNCHANGED = -1 + + fun state(context: Context): State { + val source = prefs(context).getString(KEY_SOURCE, null) + ?.let { name -> Source.entries.firstOrNull { it.name == name } } ?: Source.NONE + return State(owned(context), cacheFile(context)?.isFile == true, source) + } + + /** Recorded once: by the session's ownership check (a flag in the guest's home) or a Steam copy. */ + fun owned(context: Context): Boolean { + if (prefs(context).getBoolean(KEY_OWNED, false)) return true + if (!ownedFlag(context).exists()) return false + markOwned(context) + return true + } + + fun cacheFile(context: Context): File? = prefs(context).getString(KEY_ID, null)?.let { cacheFor(context, it) } + + /** Takes a new or updated Steam copy and rebuilds a missing or outdated cache. A [LsfgNative] status. */ + @Synchronized + fun sync(context: Context): Int { + val steam = steamDll(context) + if (steam != null) { + markOwned(context) + val stamp = "${steam.length()}:${steam.lastModified()}" + if (stamp != prefs(context).getString(KEY_STEAM_STAMP, null)) { + val status = adopt(context, steam, Source.STEAM) + if (status != LsfgNative.STATUS_OK && status != UNCHANGED) { + Log.w(TAG, "Steam copy $steam not taken: ${statusName(status)}") + } + prefs(context).edit().putString(KEY_STEAM_STAMP, stamp).apply() + } + } + return ensureBuilt(context) + } + + @Synchronized + fun import(context: Context, dll: File): ImportResult { + if (!owned(context)) return ImportResult.NOT_OWNED + return when (adopt(context, dll, Source.IMPORT)) { + UNCHANGED -> ImportResult.UNCHANGED + LsfgNative.STATUS_OK -> ImportResult.UPDATED + LsfgNative.STATUS_UNREADABLE_FILE, LsfgNative.STATUS_NOT_PORTABLE_EXECUTABLE, + LsfgNative.STATUS_MISSING_SHADERS -> ImportResult.INVALID + else -> ImportResult.FAILED + } + } + + fun message(context: Context, result: ImportResult): String = context.getString( + when (result) { + ImportResult.UPDATED -> R.string.lsfg_imported + ImportResult.UNCHANGED -> R.string.lsfg_import_unchanged + ImportResult.NOT_OWNED -> R.string.lsfg_import_not_owned + ImportResult.INVALID -> R.string.lsfg_import_invalid + ImportResult.FAILED -> R.string.lsfg_import_failed + }, + ) + + private fun ensureBuilt(context: Context): Int { + val id = prefs(context).getString(KEY_ID, null) ?: return LsfgNative.STATUS_NOT_INSTALLED + val cache = cacheFor(context, id) + if (usable(cache)) return LsfgNative.STATUS_OK + val dll = storedDll(context) + if (!dll.isFile) return LsfgNative.STATUS_NOT_INSTALLED + return build(dll, cache) + } + + private fun adopt(context: Context, source: File, from: Source): Int { + val staged = File(dir(context).apply { mkdirs() }, "Lossless.dll.staged") + try { + val id = copyHashing(source, staged) + if (id == prefs(context).getString(KEY_ID, null) && usable(cacheFor(context, id))) return UNCHANGED + val cache = cacheFor(context, id) + var status = LsfgNative.nativeValidateDll(staged.path) + if (status == LsfgNative.STATUS_OK) status = build(staged, cache) + if (status != LsfgNative.STATUS_OK) { + cache.delete() + return status + } + if (!staged.renameTo(storedDll(context))) { + cache.delete() + return LsfgNative.STATUS_CACHE_UNUSABLE + } + prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, from.name).apply() + removeStale(context, id) + Log.i(TAG, "Lossless.dll from $source ($from) ready as $id") + return LsfgNative.STATUS_OK + } catch (e: java.io.IOException) { + Log.w(TAG, "could not copy $source", e) + return LsfgNative.STATUS_UNREADABLE_FILE + } catch (t: Throwable) { + Log.e(TAG, "could not take $source", t) + return LsfgNative.STATUS_CACHE_UNUSABLE + } finally { + staged.delete() + } + } + + private fun build(dll: File, cache: File): Int = try { + val status = LsfgNative.nativeBuildCache(dll.path, cache.path, true) + Log.i(TAG, "shader cache ${cache.name}: ${statusName(status)}" + + if (status == LsfgNative.STATUS_OK) " (${LsfgNative.nativeVariantName(LsfgNative.nativeCacheVariant(cache.path))})" else "") + status + } catch (t: Throwable) { + Log.e(TAG, "shader cache ${cache.name}", t) + LsfgNative.STATUS_CACHE_UNUSABLE + } + + private fun usable(cache: File): Boolean = cache.isFile && + runCatching { LsfgNative.nativeCacheVariant(cache.path) != LsfgNative.VARIANT_NONE }.getOrDefault(false) + + private fun copyHashing(source: File, target: File): String { + val digest = MessageDigest.getInstance("SHA-256") + source.inputStream().use { input -> + DigestOutputStream(target.outputStream(), digest).use { output -> input.copyTo(output) } + } + return digest.digest().take(8).joinToString("") { "%02x".format(it) } + } + + private fun removeStale(context: Context, keep: String) { + File(context.filesDir, "lsfg-native").deleteRecursively() + dir(context).listFiles { f -> f.name.startsWith("shaders-") && f.name != cacheFor(context, keep).name } + ?.forEach { it.delete() } + } + + /** The newest copy in any library the client installs to: its own, the card's, the Games folders. */ + private fun steamDll(context: Context): File? { + val libraries = listOfNotNull( + File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"), + GameStorage.effective(context)?.path?.let(::File), + ) + SessionPrefs.addedGamesDirs(context).map(::File) + return libraries.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() } + } + + private fun markOwned(context: Context) { + if (!prefs(context).getBoolean(KEY_OWNED, false)) prefs(context).edit().putBoolean(KEY_OWNED, true).apply() + } + + private fun statusName(status: Int): String = + runCatching { LsfgNative.nativeStatusName(status) }.getOrDefault("status $status") + + private fun ownedFlag(context: Context) = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/lossless-owned") + private fun dir(context: Context) = File(context.filesDir, "lsfg") + private fun storedDll(context: Context) = File(dir(context), "Lossless.dll") + private fun cacheFor(context: Context, id: String) = File(dir(context), "shaders-$id.cache") + private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) +} diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/LsfgNative.java b/app/src/main/java/com/droiddeck/launcher/gpu/LsfgNative.java index c9b03ef03..29c7dbd17 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/LsfgNative.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/LsfgNative.java @@ -1,99 +1,30 @@ package com.droiddeck.launcher.gpu; -import android.content.Context; -import android.util.Log; - -import com.droiddeck.launcher.runtime.LinuxRuntime; - -import java.io.File; - /** - * LSFG frame generation's shader chain: extracted from the user's own copy of Lossless Scaling - * and cached on device. - * - *

The 25 compute shaders are not redistributable. They live as resources inside the user's - * paid {@code Lossless.dll} (Steam app 993090), which in this app the user installs from the - * Steam client itself - so the DLL sits in the runtime's own Steam library. It is mapped - * read-only and parsed as data, never loaded or executed. Extraction is slow enough to be worth - * doing once (the DXBC chain is translated to SPIR-V), so the result is cached, keyed on the - * DLL's size and hash. Call {@link #ensureCache} off the main thread. - * - *

Ported from Bannerlator's LsfgNative; the native side is the same lsfg_jni.cpp compiled into - * the compositor library. + * The native half of LSFG's shader cache (lsfg_jni.cpp, compiled into the compositor library): + * {@code Lossless.dll} is mapped read-only and parsed as data, never loaded or executed, and its + * DXBC chain translated to SPIR-V. {@link Lossless} decides when; these calls block. */ -public final class LsfgNative { - private static final String TAG = "LsfgNative"; - +final class LsfgNative { static { System.loadLibrary("bannerwayland"); } private LsfgNative() {} // Mirrors lsfg::DllStatus. - public static final int STATUS_OK = 0; - public static final int STATUS_NOT_INSTALLED = 1; - public static final int STATUS_UNREADABLE_FILE = 2; - public static final int STATUS_NOT_PORTABLE_EXECUTABLE = 3; - public static final int STATUS_MISSING_SHADERS = 4; - public static final int STATUS_TRANSLATION_FAILED = 5; - public static final int STATUS_CACHE_UNUSABLE = 6; + static final int STATUS_OK = 0; + static final int STATUS_NOT_INSTALLED = 1; + static final int STATUS_UNREADABLE_FILE = 2; + static final int STATUS_NOT_PORTABLE_EXECUTABLE = 3; + static final int STATUS_MISSING_SHADERS = 4; + static final int STATUS_TRANSLATION_FAILED = 5; + static final int STATUS_CACHE_UNUSABLE = 6; - private static native int nativeValidateDll(String dllPath); - private static native int nativeDllVariant(String dllPath, boolean preferFp16); - private static native int nativeBuildCache(String dllPath, String cachePath, boolean preferFp16); - private static native boolean nativeCacheMatchesSource(String cachePath, String dllPath); - private static native int nativeCacheVariant(String cachePath); - private static native String nativeStatusName(int status); - private static native String nativeVariantName(int variant); + // Mirrors lsfg::Variant. + static final int VARIANT_NONE = 0; - /** Where Lossless Scaling lands when installed from the client inside the runtime. */ - public static File losslessDll(Context context) { - return new File(LinuxRuntime.rootDir(context), - "root/.local/share/Steam/steamapps/common/Lossless Scaling/Lossless.dll"); - } - - /** Where the translated SPIR-V chain is cached. */ - public static File cacheFile(Context context) { - return new File(context.getFilesDir(), "lsfg-native/shaders.cache"); - } - - public static boolean isInstalled(Context context) { - return losslessDll(context).isFile(); - } - - /** - * Makes sure a usable cache exists for the installed DLL, building it if the DLL is new or - * changed. Returns a {@code STATUS_*} code; {@link #STATUS_OK} means the engine can start. - */ - public static int ensureCache(Context context) { - File dll = losslessDll(context); - if (!dll.isFile()) return STATUS_NOT_INSTALLED; - File cache = cacheFile(context); - try { - if (cache.isFile() && nativeCacheMatchesSource(cache.getPath(), dll.getPath())) { - return STATUS_OK; - } - int status = nativeValidateDll(dll.getPath()); - if (status != STATUS_OK) { - Log.w(TAG, "Lossless.dll rejected: " + statusName(status)); - return status; - } - //noinspection ResultOfMethodCallIgnored - cache.getParentFile().mkdirs(); - status = nativeBuildCache(dll.getPath(), cache.getPath(), true); - Log.i(TAG, "cache build: " + statusName(status) - + (status == STATUS_OK ? " (" + nativeVariantName(nativeCacheVariant(cache.getPath())) + ")" : "")); - return status; - } catch (Throwable t) { - Log.e(TAG, "ensureCache", t); - return STATUS_CACHE_UNUSABLE; - } - } - - public static String statusName(int status) { - try { - return nativeStatusName(status); - } catch (Throwable t) { - return "status " + status; - } - } + static native int nativeValidateDll(String dllPath); + static native int nativeBuildCache(String dllPath, String cachePath, boolean preferFp16); + static native int nativeCacheVariant(String cachePath); + static native String nativeStatusName(int status); + static native String nativeVariantName(int variant); } diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java index 8d8863961..52d8129ff 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java @@ -179,10 +179,7 @@ public final class TurnipDriver { * {@link IOException} on read/extract failures. */ public String installFromZip(Uri zipUri, String displayName) throws IOException { - if (!contentDir.exists()) contentDir.mkdirs(); - File tmpDir = new File(contentDir, ".tmp-" + System.currentTimeMillis()); - FileUtils.delete(tmpDir); - if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir); + File tmpDir = newStagingDir(); boolean keep = false; try { try (InputStream is = context.getContentResolver().openInputStream(zipUri); @@ -198,26 +195,44 @@ public final class TurnipDriver { Files.copy(zis, new File(tmpDir, base).toPath(), StandardCopyOption.REPLACE_EXISTING); } } - String rejected = rejectionReason(tmpDir); - if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected); - - JSONObject meta = readMetaFile(new File(tmpDir, "meta.json")); - String name = meta != null ? meta.optString("name", "") : ""; - if (name.isEmpty()) { - name = displayName != null ? displayName : "adrenotools-driver"; - if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4); - } - String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name)); - File dir = new File(contentDir, id); - if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir); + String id = adopt(tmpDir, displayName); keep = true; - Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir); return id; } finally { if (!keep) FileUtils.delete(tmpDir); } } + /** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */ + File newStagingDir() throws IOException { + if (!contentDir.exists()) contentDir.mkdirs(); + File tmpDir = new File(contentDir, ".tmp-" + System.nanoTime()); + FileUtils.delete(tmpDir); + if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir); + return tmpDir; + } + + /** + * Check a staged driver (meta.json and its library, flat) and move it in as a new driver. + * Returns the id; the caller deletes {@code tmpDir} when this throws. + */ + String adopt(File tmpDir, String displayName) throws IOException { + String rejected = rejectionReason(tmpDir); + if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected); + + JSONObject meta = readMetaFile(new File(tmpDir, "meta.json")); + String name = meta != null ? meta.optString("name", "") : ""; + if (name.isEmpty()) { + name = displayName != null ? displayName : "adrenotools-driver"; + if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4); + } + String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name)); + File dir = new File(contentDir, id); + if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir); + Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir); + return id; + } + private static JSONObject readMetaFile(File metaFile) { try { return new JSONObject(FileUtils.readString(metaFile)); diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipReleases.kt b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipReleases.kt index 14e7e81e6..9a6235f1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipReleases.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipReleases.kt @@ -29,12 +29,20 @@ object TurnipReleases { /** [label] names the variant for the menu: the GPUs it is for, and a build flavour. */ /** [sha256] is the release asset's digest from GitHub; empty for a list cached before it was kept. */ + /** + * [pair] names the matched set an asset belongs to (DriverPairs): a display build and a Linux + * build of the same pair are made to run together. "" for a list cached before pairs were kept. + */ + /** [bundle]: one zip holding both halves of the pair (DriverBundle); [linux] is false for it. */ class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String, - val sha256: String = "") + val sha256: String = "", val pair: String = "", val bundle: Boolean = false) /** [latest] = each source's newest release tag, for the refresh line. */ class Check(val assets: List, val latest: List>, val failed: List, val checkedAt: Long) - private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Pair?) + /** What an asset is: a Linux build or not, the menu label, and the pair it belongs to. */ + private class Kind(val linux: Boolean, val label: String, val pair: String, val bundle: Boolean = false) + + private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Kind?) private val SOURCES = listOf( // Turnip-[-variant][-Linux|-Wayland].zip; -Wayland is for a path this app does not have. @@ -45,12 +53,14 @@ object TurnipReleases { if (variant.endsWith("-Wayland")) return@Source null val linux = variant.endsWith("-Linux") variant = variant.removeSuffix("-Linux") - linux to when { + val label = when { variant.isEmpty() -> "Adreno 6xx/7xx" variant == "-A8xx" -> "Adreno 8xx" variant.startsWith("-710-720") -> "Adreno 710/720" + if (variant.contains("Test")) " (test)" else "" + variant.contains("OneUI", ignoreCase = true) -> "8 Gen 2 on One UI" else -> variant.trimStart('-') } + Kind(linux, label, "banner" + variant.lowercase()) }, // WN-Turnip--_Axxx.zip (Android) and WN-Linux-Turnip--_Axxx.zip (Linux): // b = Balanced, p = Performance, Axxx = every Adreno. @@ -58,7 +68,13 @@ object TurnipReleases { val m = Regex("""^WN-(Linux-)?Turnip-[^-]+-([a-z]+)_(\w+)\.zip$""").find(name) ?: return@Source null val flavour = when (m.groupValues[2]) { "b" -> "Balanced"; "p" -> "Performance"; else -> m.groupValues[2] } val gpus = if (m.groupValues[3] == "Axxx") "all Adreno" else m.groupValues[3] - (m.groupValues[1].isNotEmpty()) to "$gpus · $flavour" + Kind(m.groupValues[1].isNotEmpty(), "$gpus · $flavour", "wn-" + m.groupValues[2]) + }, + // DD-Turnip-v.zip: DroidDeck's own all-in-one build, both halves in one zip, published + // to Drivers-CI (releases only). Every release is offered, not just the newest, each its own pair. + Source("DroidDeck", "Droid-Deck/Drivers-CI") { name, tag -> + if (!Regex("""^DD-Turnip-v\d+\.\d+\.\d+\.zip$""").matches(name)) return@Source null + Kind(false, "Android + Linux · all Adreno", DriverPairs.ddTurnip(tag), bundle = true) }, ) @@ -91,14 +107,19 @@ object TurnipReleases { for (j in 0 until list.length()) { val a = list.getJSONObject(j) val name = a.getString("name") - val (linux, label) = src.classify(name, tag) ?: continue + val kind = src.classify(name, tag) ?: continue + // A bundle is only offered from an official release, never a pre-release. + if (kind.bundle && r.optBoolean("prerelease")) continue + val linux = kind.linux + val label = kind.label // Only assets GitHub has a sha256 for are offered: the download is checked against it. val sha = Hashes.githubSha256(a.optString("digest")) ?: continue // Newest first: the first release carrying a variant is the one offered. - if (!seen.add("$linux|$label")) continue + if (!seen.add(if (kind.bundle) kind.pair else "$linux|$label")) continue assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name) .put("url", a.getString("browser_download_url")).put("size", a.optLong("size")) - .put("linux", linux).put("label", label).put("sha256", sha)) + .put("linux", linux).put("label", label).put("sha256", sha).put("pair", kind.pair) + .put("bundle", kind.bundle)) } } if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest)) @@ -136,7 +157,8 @@ object TurnipReleases { for (i in 0 until list.length()) { val a = list.getJSONObject(i) out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"), - a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", ""))) + a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", ""), a.optString("pair", ""), + a.optBoolean("bundle", false))) } val latest = ArrayList>() val l = json.optJSONArray("latest") ?: JSONArray() diff --git a/app/src/main/java/com/droiddeck/launcher/input/DeckControls.kt b/app/src/main/java/com/droiddeck/launcher/input/DeckControls.kt new file mode 100644 index 000000000..23146be37 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/DeckControls.kt @@ -0,0 +1,69 @@ +package com.droiddeck.launcher.input + +/** + * The Steam Deck controller's back grips and trackpads, which a handheld's own pad does not have: + * the second screen's Deck controls (DeckControlsPanel) drive them, and each change goes into the + * pad's ring ([FakeInputWriter.writeDeckControls]) for libfakeinput's Deck report. + * + * Trackpad positions are -1..1 each way with y up, as on a Deck; a pad touched reports its + * position, a pad clicked also reports full pressure. + */ +object DeckControls { + /** Bits of the ring's controls word - MUST match DECK_EXTRA_* in fakeinput_steam.cpp. */ + const val L4 = 1 + const val R4 = 2 + const val L5 = 4 + const val R5 = 8 + private const val LEFT_TOUCH = 16 + private const val RIGHT_TOUCH = 32 + private const val LEFT_CLICK = 64 + private const val RIGHT_CLICK = 128 + + /** The pad the Deck controller is made from (PadBridge's slot). */ + private const val SLOT = 0 + + private var controls = 0 + private val pads = ShortArray(4) + private val pressure = ShortArray(2) + + @Synchronized + fun setGrip(bit: Int, down: Boolean) { + set(bit, down) + publish() + } + + /** A finger on (or off) one trackpad at x, y in -1..1, y up. */ + @Synchronized + fun setPad(right: Boolean, touching: Boolean, x: Float = 0f, y: Float = 0f) { + val at = if (right) 2 else 0 + set(if (right) RIGHT_TOUCH else LEFT_TOUCH, touching) + pads[at] = if (touching) axis(x) else 0 + pads[at + 1] = if (touching) axis(y) else 0 + publish() + } + + @Synchronized + fun setClick(right: Boolean, down: Boolean) { + set(if (right) RIGHT_CLICK else LEFT_CLICK, down) + pressure[if (right) 1 else 0] = if (down) Short.MAX_VALUE else 0 + publish() + } + + /** Everything let go - for when the panel goes away with a finger still on it. */ + @Synchronized + fun releaseAll() { + if (controls == 0 && pads.all { it.toInt() == 0 } && pressure.all { it.toInt() == 0 }) return + controls = 0 + pads.fill(0) + pressure.fill(0) + publish() + } + + private fun set(bit: Int, on: Boolean) { + controls = if (on) controls or bit else controls and bit.inv() + } + + private fun axis(value: Float): Short = (value.coerceIn(-1f, 1f) * Short.MAX_VALUE).toInt().toShort() + + private fun publish() = FakeInputWriter.writeDeckControls(SLOT, controls, pads, pressure) +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java index 30b802166..0e4ea2de3 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java +++ b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java @@ -67,6 +67,9 @@ public class FakeInputWriter { /** Bit 10 of the snapshot word. The first ten are PadState's own bit order; the Steam * button is not, because PadState keeps 10 and 11 for the triggers. */ private static final int SNAPSHOT_IDX_MODE = 10; + /** Bit 11: the Quick Access button. Snapshot only - an Xbox pad's evdev node has no such key; + * libfakeinput's Deck controller reads it from here. */ + private static final int SNAPSHOT_IDX_QAM = 11; private static final int EVENT_SIZE = 24; static final int MAX_EVENTS_PER_UPDATE = 32; @@ -92,6 +95,18 @@ public class FakeInputWriter { private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40; private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8] private static final String RING_DIR_NAME = "fakeinput-rings"; + // After the events - MUST match the block in fakeinput_steam.cpp (DeckImu): what a Deck has and + // an Xbox pad does not - motion, back grips, trackpads - in the Steam Deck controller's axes and + // units, under a seqlock like the snapshot's. Only libfakeinput's Deck controller reads it. + private static final int IMU_OFFSET = RING_SIZE; + private static final int IMU_MAGIC = 0x31554D49; // IMU1 + private static final int IMU_SEQ_OFFSET = IMU_OFFSET + 8; + private static final int IMU_ACCEL_OFFSET = IMU_OFFSET + 16; // short[3] + private static final int IMU_GYRO_OFFSET = IMU_OFFSET + 22; // short[3] + private static final int DECK_PADS_OFFSET = IMU_OFFSET + 28; // short[4]: left X, Y, right X, Y + private static final int DECK_PRESSURE_OFFSET = IMU_OFFSET + 36; // short[2]: left, right + private static final int DECK_CONTROLS_OFFSET = IMU_OFFSET + 40; // int: DeckControls bits + private static final int RING_FILE_SIZE = RING_SIZE + 64; private static final Object RING_LOCK = new Object(); private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS]; @@ -110,6 +125,7 @@ public class FakeInputWriter { private volatile boolean destroyed = false; private final boolean[] prevButtonStates = new boolean[12]; + private boolean prevQam; private int prevThumbLX, prevThumbLY, prevThumbRX, prevThumbRY; private int prevTriggerL, prevTriggerR; private int prevHatX, prevHatY; @@ -217,30 +233,40 @@ public class FakeInputWriter { for (int i = 0; i < 8; i++) { data.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0); } + data.putInt(IMU_OFFSET, 0); + data.putLong(IMU_SEQ_OFFSET, 0L); + for (int i = 0; i < 12; i++) { + data.putShort(IMU_ACCEL_OFFSET + (i * 2), (short) 0); + } + data.putInt(DECK_CONTROLS_OFFSET, 0); } + // Lock order: RING_LOCK, then the slot. Every writer holds the slot while it touches data, and + // re-checks it there: a writer that looked the slot up just before this ran finds it gone. private static void releaseRingSlotLocked(int slot) { RingSlot ringSlot = RING_SLOTS[slot]; if (ringSlot == null) { return; } - ringSlot.data = null; - if (ringSlot.ringChannel != null) { - try { - ringSlot.ringChannel.close(); - } catch (IOException ignored) { + synchronized (ringSlot) { + ringSlot.data = null; + if (ringSlot.ringChannel != null) { + try { + ringSlot.ringChannel.close(); + } catch (IOException ignored) { + } + ringSlot.ringChannel = null; } - ringSlot.ringChannel = null; - } - if (ringSlot.ringRaf != null) { - try { - ringSlot.ringRaf.close(); - } catch (IOException ignored) { + if (ringSlot.ringRaf != null) { + try { + ringSlot.ringRaf.close(); + } catch (IOException ignored) { + } + ringSlot.ringRaf = null; + } + if (ringSlot.ringFile != null && ringSlot.ringFile.exists()) { + ringSlot.ringFile.delete(); } - ringSlot.ringRaf = null; - } - if (ringSlot.ringFile != null && ringSlot.ringFile.exists()) { - ringSlot.ringFile.delete(); } RING_SLOTS[slot] = null; } @@ -289,9 +315,9 @@ public class FakeInputWriter { FileChannel channel = null; try { raf = new RandomAccessFile(ringFile, "rw"); - raf.setLength(RING_SIZE); + raf.setLength(RING_FILE_SIZE); channel = raf.getChannel(); - ByteBuffer data = channel.map(FileChannel.MapMode.READ_WRITE, 0, RING_SIZE); + ByteBuffer data = channel.map(FileChannel.MapMode.READ_WRITE, 0, RING_FILE_SIZE); initializeRingHeader(data); RingSlot ringSlot = new RingSlot(); @@ -332,6 +358,9 @@ public class FakeInputWriter { return false; } synchronized (ringSlot) { + if (ringSlot.data == null) { + return false; + } if (!ringSlot.active) { if (ringSlot.everActivated) { ringSlot.generation++; @@ -381,6 +410,9 @@ public class FakeInputWriter { ByteBuffer source = this.buffer.duplicate(); synchronized (ringSlot) { ByteBuffer ring = ringSlot.data; + if (ring == null) { + return false; + } long writeSeq = ring.getLong(RING_WRITE_SEQ_OFFSET); int sourceLimit = source.limit(); while (source.remaining() >= EVENT_SIZE) { @@ -416,6 +448,9 @@ public class FakeInputWriter { buttons |= (1 << i); } } + if (this.prevQam) { + buttons |= (1 << SNAPSHOT_IDX_QAM); + } long seq = ring.getLong(RING_SNAPSHOT_SEQ_OFFSET); ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1); // odd: write in progress nativeStoreFence(); @@ -434,6 +469,58 @@ public class FakeInputWriter { ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 2); // even: write complete } + /** + * Publishes the pad's motion for slot {@code slot}: accelerometer and gyro, already in the Deck + * controller's axes and units (see PadMotion). Safe from any thread. + */ + public static void writeMotion(int slot, short[] accel, short[] gyro) { + RingSlot ringSlot; + synchronized (RING_LOCK) { + ringSlot = slot >= 0 && slot < RING_SLOTS.length ? RING_SLOTS[slot] : null; + } + if (ringSlot == null) return; + synchronized (ringSlot) { + ByteBuffer ring = ringSlot.data; + if (ring == null) return; + long seq = ring.getLong(IMU_SEQ_OFFSET); + ring.putLong(IMU_SEQ_OFFSET, seq + 1); // odd: write in progress + nativeStoreFence(); + for (int i = 0; i < 3; i++) { + ring.putShort(IMU_ACCEL_OFFSET + i * 2, accel[i]); + ring.putShort(IMU_GYRO_OFFSET + i * 2, gyro[i]); + } + ring.putInt(IMU_OFFSET, IMU_MAGIC); + nativeStoreFence(); + ring.putLong(IMU_SEQ_OFFSET, seq + 2); + } + } + + /** + * Publishes the Deck's back grips and trackpads for slot {@code slot} (see DeckControls): + * {@code controls} is the DeckControls bit set, {@code pads} left X, Y, right X, Y and + * {@code pressure} left, right, already in the Deck's units. Safe from any thread. + */ + public static void writeDeckControls(int slot, int controls, short[] pads, short[] pressure) { + RingSlot ringSlot; + synchronized (RING_LOCK) { + ringSlot = slot >= 0 && slot < RING_SLOTS.length ? RING_SLOTS[slot] : null; + } + if (ringSlot == null) return; + synchronized (ringSlot) { + ByteBuffer ring = ringSlot.data; + if (ring == null) return; + long seq = ring.getLong(IMU_SEQ_OFFSET); + ring.putLong(IMU_SEQ_OFFSET, seq + 1); + nativeStoreFence(); + for (int i = 0; i < 4; i++) ring.putShort(DECK_PADS_OFFSET + i * 2, pads[i]); + for (int i = 0; i < 2; i++) ring.putShort(DECK_PRESSURE_OFFSET + i * 2, pressure[i]); + ring.putInt(DECK_CONTROLS_OFFSET, controls); + ring.putInt(IMU_OFFSET, IMU_MAGIC); + nativeStoreFence(); + ring.putLong(IMU_SEQ_OFFSET, seq + 2); + } + } + private static short clampShort(int value) { if (value > Short.MAX_VALUE) { return Short.MAX_VALUE; @@ -512,6 +599,11 @@ public class FakeInputWriter { } } + if (prevQam) { + prevQam = false; + hasChanges = true; + } + // Zero all axes if (prevThumbLX != 0) { prevThumbLX = 0; @@ -620,6 +712,11 @@ public class FakeInputWriter { // reports as button 8 - exactly the "guide:b8" in the mapping Steam writes for this pad. writeButton(SNAPSHOT_IDX_MODE, state.isDown(PadState.GUIDE)); + boolean qam = state.isDown(PadState.QAM); + if (forceResend || qam != prevQam) { + prevQam = qam; + hasChanges = true; + } // Sticks int lx = (int) (state.leftX * 32767); diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt index 17b659734..e14ac7ccc 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -45,11 +45,11 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va val halfW get() = if (wide) radius * SHOULDER_WIDTH else radius val halfH get() = if (wide) radius * SHOULDER_HEIGHT else radius - fun contains(x: Float, y: Float, r: Float): Boolean { + fun contains(x: Float, y: Float, r: Float, padding: Float = 0f): Boolean { val dx = x - cx val dy = y - cy - if (wide) return abs(dx) <= halfW + r * 0.25f && abs(dy) <= halfH + r * 0.25f - val hit = r * 1.25f + if (wide) return abs(dx) <= halfW + r * 0.25f + padding && abs(dy) <= halfH + r * 0.25f + padding + val hit = r * 1.25f + padding return dx * dx + dy * dy <= hit * hit } @@ -350,6 +350,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va override fun onDraw(canvas: Canvas) { for (control in controls) { if (!isVisible(control)) continue + if (control.stick >= 0 && settings.adaptiveSticks && !editing && control.pressedBy == -1) continue val held = control.pressedBy != -1 val radius = control.radius if (control.stick >= 0) { @@ -426,10 +427,13 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va when (event.actionMasked) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { val index = event.actionIndex - val control = controlAt(event.getX(index), event.getY(index)) ?: return false + val x = event.getX(index) + val y = event.getY(index) + val control = controlAt(x, y) ?: adaptiveStickAt(x, y) ?: return false + if (control.pressedBy != -1) return true control.pressedBy = event.getPointerId(index) if (control.stick >= 0) { - control.clicked = settings.stickClick && event.eventTime - control.lastUp < DOUBLE_TAP_MS + control.clicked = settings.stickClick && control.lastUp > 0L && event.eventTime - control.lastUp < DOUBLE_TAP_MS val adaptive = settings.adaptiveSticks control.ax = if (adaptive) event.getX(index) else control.cx control.ay = if (adaptive) event.getY(index) else control.cy @@ -468,7 +472,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va for (control in controls) { if (control.pressedBy == pointer || event.actionMasked == MotionEvent.ACTION_CANCEL) { if (control.pressedBy != -1) changed = true - if (control.stick >= 0 && control.pressedBy != -1) control.lastUp = if (control.clicked) 0L else event.eventTime + if (control.stick >= 0 && control.pressedBy != -1) control.lastUp = if (control.clicked || event.actionMasked == MotionEvent.ACTION_CANCEL) 0L else event.eventTime control.pressedBy = -1 control.clicked = false if (control.stick >= 0 && (control.kx != 0f || control.ky != 0f)) control.dirty = true @@ -505,7 +509,25 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va } private fun controlAt(x: Float, y: Float): Control? = - controls.firstOrNull { isVisible(it) && it.contains(x, y, it.radius) } + controls.firstOrNull { + isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius) + } + + private fun adaptiveStickAt(x: Float, y: Float): Control? { + if (!settings.adaptiveSticks || editing || buttonsOnly) return null + if (x < safe.left || x >= width - safe.right || y < safe.top || y >= height - safe.bottom) return null + if (controls.any { it.stick < 0 && isVisible(it) && it.contains(x, y, it.radius, 5f) }) return null + return controls.filter { + val dx = x - it.cx + val dy = y - it.cy + val reach = it.radius * 1.4f * sqrt(1.5f) + it.stick >= 0 && isVisible(it) && it.pressedBy == -1 && dx * dx + dy * dy <= reach * reach + }.minByOrNull { + val dx = x - it.cx + val dy = y - it.cy + dx * dx + dy * dy + } + } private fun isVisible(control: Control): Boolean = when { buttonsOnly && !editing -> control.id == "guide" || control.id == "qam" @@ -574,6 +596,7 @@ class OnScreenControls(context: Context, private val pad: PadBridge?, private va controls.forEach { it.pressedBy = -1 it.clicked = false + it.lastUp = 0L if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true it.kx = 0f; it.ky = 0f } diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index 518904973..9fe6f6ecd 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -7,6 +7,8 @@ import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; +import com.droiddeck.launcher.session.SessionState; + import java.io.File; /** @@ -19,16 +21,34 @@ import java.io.File; * SDL → Big Picture. * *

The identity the interposer reports is an Xbox 360 pad, which is what makes SDL apply a known - * mapping without the user configuring anything. + * mapping without the user configuring anything. In a Steam session it is a Steam Deck controller + * to the client instead ({@link com.droiddeck.launcher.session.SteamDeckPad}), which has a Quick + * Access button of its own; an Xbox pad has none, so there the client's menu is reached with the + * Guide-then-A chord the client itself answers. */ public final class PadBridge { private static final String TAG = "PadBridge"; /** Slot 0 is the one the session exports; extra slots would each show as another pad. */ private static final int SLOT = 0; private static final float DEAD_ZONE = 0.12f; - private static final long QAM_GUIDE_LEAD_MS = 80; - private static final long QAM_A_HOLD_MS = 120; - private static final long QAM_GUIDE_TAIL_MS = 40; + // The client takes A as part of the chord only once it has had Guide held for a while, and a + // client starved of CPU needs longer. Too short, and it acts on A as well, selecting whatever it + // had focused before opening QAM: with 80 ms of lead that was 3 times in 20 at rest, and 250 ms + // none in 20; with the session down to 1 fps a fixed 400 ms still let 3 in 15 through, where + // 1000 ms let none. The lead keeps 80 ms when frames are quick, for a QAM that feels immediate, + // and stretches to eight frames when they are slow. + private static final long QAM_GUIDE_LEAD_MIN_MS = 80; + private static final long QAM_GUIDE_LEAD_MAX_MS = 1500; + private static final int QAM_GUIDE_LEAD_FRAMES = 8; + private static final long QAM_A_HOLD_MS = 200; + private static final long QAM_GUIDE_TAIL_MS = 200; + // Off the main thread, so a busy UI cannot shorten or stretch the steps. + private static final Handler chordHandler; + static { + android.os.HandlerThread thread = new android.os.HandlerThread("qam-chord", android.os.Process.THREAD_PRIORITY_DISPLAY); + thread.start(); + chordHandler = new Handler(thread.getLooper()); + } private final FakeInputWriter writer; private final PadState state = new PadState(); @@ -39,6 +59,8 @@ public final class PadBridge { private boolean systemQamPressed; private boolean qamChordActive; private boolean qamSyntheticAPressed; + /** The Deck controller's Quick Access button, held for one tap. */ + private boolean qamTapPressed; private int qamChordGeneration; /** Told on the main thread when a player uses the pad or the on-screen controls; see [setOnPlayerInput]. */ private volatile Runnable onPlayerInput; @@ -62,6 +84,7 @@ public final class PadBridge { systemQamPressed = false; qamChordActive = false; qamSyntheticAPressed = false; + qamTapPressed = false; qamChordGeneration++; if (open) { state.clear(); @@ -189,7 +212,8 @@ public final class PadBridge { boolean qamStarted = qamPressed && !systemQamPressed; systemGuidePressed = guidePressed; systemQamPressed = qamPressed; - if (qamStarted) startQamChord(); + // A Deck controller's QAM button is held for as long as the touch one is. + if (qamStarted && !SessionState.getDeckPad()) startQamChord(); else publish(); } @@ -202,9 +226,23 @@ public final class PadBridge { publish(); } - /** Starts the same Guide-then-A sequence used by the touch QAM button. */ + /** Opens the client's Quick Access menu: a tap of the Deck's button, or the Guide-then-A chord. */ public synchronized void triggerQam() { - startQamChord(); + if (!SessionState.getDeckPad()) { + startQamChord(); + return; + } + if (qamTapPressed) return; + qamTapPressed = true; + int generation = qamChordGeneration; + publish(); + chordHandler.postDelayed(() -> releaseQamTap(generation), QAM_A_HOLD_MS); + } + + private synchronized void releaseQamTap(int generation) { + if (generation != qamChordGeneration || !qamTapPressed) return; + qamTapPressed = false; + publish(); } private void startQamChord() { @@ -212,21 +250,27 @@ public final class PadBridge { qamChordActive = true; int generation = ++qamChordGeneration; publish(); - mainHandler.postDelayed(() -> pressQamA(generation), QAM_GUIDE_LEAD_MS); + chordHandler.postDelayed(() -> pressQamA(generation), qamGuideLeadMs()); + } + + static long qamGuideLeadMs() { + long frame = com.droiddeck.launcher.wayland.WaylandCompositor.recentFrameIntervalMs(); + if (frame <= 0) return QAM_GUIDE_LEAD_MIN_MS; + return Math.max(QAM_GUIDE_LEAD_MIN_MS, Math.min(QAM_GUIDE_LEAD_MAX_MS, frame * QAM_GUIDE_LEAD_FRAMES)); } private synchronized void pressQamA(int generation) { if (generation != qamChordGeneration || !qamChordActive) return; qamSyntheticAPressed = true; publish(); - mainHandler.postDelayed(() -> releaseQamA(generation), QAM_A_HOLD_MS); + chordHandler.postDelayed(() -> releaseQamA(generation), QAM_A_HOLD_MS); } private synchronized void releaseQamA(int generation) { if (generation != qamChordGeneration || !qamChordActive) return; qamSyntheticAPressed = false; publish(); - mainHandler.postDelayed(() -> releaseQamGuide(generation), QAM_GUIDE_TAIL_MS); + chordHandler.postDelayed(() -> releaseQamGuide(generation), QAM_GUIDE_TAIL_MS); } private synchronized void releaseQamGuide(int generation) { @@ -237,16 +281,17 @@ public final class PadBridge { private void publish() { if (!open && !start()) return; - if (systemGuidePressed || qamChordActive) { - effectiveState.copyFrom(state); - effectiveState.press(PadState.GUIDE, true); - if (qamSyntheticAPressed) { - effectiveState.press(PadState.A, state.isDown(PadState.A) || qamSyntheticAPressed); - } - writer.writePad(effectiveState); - } else { + boolean guide = systemGuidePressed || qamChordActive; + boolean qam = SessionState.getDeckPad() && (systemQamPressed || qamTapPressed); + if (!guide && !qam) { writer.writePad(state); + return; } + effectiveState.copyFrom(state); + if (guide) effectiveState.press(PadState.GUIDE, true); + if (qam) effectiveState.press(PadState.QAM, true); + if (qamSyntheticAPressed) effectiveState.press(PadState.A, true); + writer.writePad(effectiveState); } private static float axis(MotionEvent event, int axis) { diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadMotion.kt b/app/src/main/java/com/droiddeck/launcher/input/PadMotion.kt new file mode 100644 index 000000000..31707a9a0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/PadMotion.kt @@ -0,0 +1,103 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import android.os.Handler +import android.os.HandlerThread +import android.util.Log +import android.view.Surface +import kotlin.math.roundToInt + +/** + * The handheld's own gyro and accelerometer, as the Steam Deck controller's (SteamDeckPad). + * + * The phone is the controller's body, so its motion sensors are the ones a Deck's would be. Android + * reports them in the device's natural orientation; they are turned to the screen as it is shown + * (x right, y up, z towards the player - SDL's frame for a gamepad), then to the Deck's own axes + * and units as SDL's Deck driver undoes them (SDL_hidapi_steamdeck.c): X right, Y away from the + * player, Z up; 1 g = 16384, 2000 °/s = 32768. The Steam client calibrates the gyro itself. + * + * Sensors run only while the session is on screen with the pad a Deck controller, sampled as often + * as the Deck reports (4 ms); each reading goes straight into the pad's ring + * ([FakeInputWriter.writeMotion]), where libfakeinput's 4 ms report picks up the latest. + */ +class PadMotion(private val context: Context, private val rotation: () -> Int) : SensorEventListener { + private val sensors = context.getSystemService(SensorManager::class.java) + private var thread: HandlerThread? = null + /** Readings are taken only while this is set; a callback already queued when [stop] ran drops. */ + @Volatile private var active = false + // Touched only on the worker thread. + private val accel = ShortArray(3) + private val gyro = ShortArray(3) + + fun start() { + if (thread != null || sensors == null) return + val gyroscope = sensors.getDefaultSensor(Sensor.TYPE_GYROSCOPE) + val accelerometer = sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) + if (gyroscope == null && accelerometer == null) { + Log.i(TAG, "pad motion: this device has no gyro or accelerometer") + return + } + val worker = HandlerThread("pad-motion", android.os.Process.THREAD_PRIORITY_DISPLAY).apply { start() } + thread = worker + val handler = Handler(worker.looper) + active = true + gyroscope?.let { sensors.registerListener(this, it, SAMPLING_US, handler) } + accelerometer?.let { sensors.registerListener(this, it, SAMPLING_US, handler) } + Log.i(TAG, "pad motion: gyro ${gyroscope?.name ?: "none"}, accelerometer ${accelerometer?.name ?: "none"}") + } + + fun stop() { + val worker = thread ?: return + thread = null + active = false + sensors?.unregisterListener(this) + // A still controller, not one frozen mid-turn - published on the worker, after any reading + // already queued there, so nothing can overwrite it. + Handler(worker.looper).post { + gyro.fill(0) + FakeInputWriter.writeMotion(SLOT, accel, gyro) + } + worker.quitSafely() + } + + override fun onSensorChanged(event: SensorEvent) { + if (!active) return + val values = event.values + // Natural orientation to the screen's: Android's display-rotation transform. + val (x, y) = when (rotation()) { + Surface.ROTATION_90 -> -values[1] to values[0] + Surface.ROTATION_180 -> -values[0] to -values[1] + Surface.ROTATION_270 -> values[1] to -values[0] + else -> values[0] to values[1] + } + val z = values[2] + val (target, scale) = when (event.sensor.type) { + Sensor.TYPE_GYROSCOPE -> gyro to GYRO_COUNTS_PER_RAD_S + Sensor.TYPE_ACCELEROMETER -> accel to ACCEL_COUNTS_PER_M_S2 + else -> return + } + // Screen frame (right, up, towards the player) to the Deck's (right, away, up). + target[0] = counts(x * scale) + target[1] = counts(-z * scale) + target[2] = counts(y * scale) + FakeInputWriter.writeMotion(SLOT, accel, gyro) + } + + override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit + + private fun counts(value: Float): Short = value.roundToInt().coerceIn(-32768, 32767).toShort() + + companion object { + private const val TAG = "PadMotion" + /** The pad the Deck controller is made from (PadBridge's slot). */ + private const val SLOT = 0 + /** The Deck controller's report interval (libfakeinput: DECK_REPORT_INTERVAL_US). */ + private const val SAMPLING_US = 4000 + private const val ACCEL_COUNTS_PER_M_S2 = 16384f / SensorManager.GRAVITY_EARTH + private const val GYRO_COUNTS_PER_RAD_S = (32768f / 2000f) * (180f / Math.PI.toFloat()) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadState.kt b/app/src/main/java/com/droiddeck/launcher/input/PadState.kt index 7f4c9efbd..c798b682f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadState.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/PadState.kt @@ -57,5 +57,7 @@ class PadState { const val R3 = 9 /** The Steam/Guide button, which the fake evdev node reports as BTN_MODE. */ const val GUIDE = 12 + /** The Quick Access button: a Deck controller's (SteamDeckPad) only, since an Xbox pad has none. */ + const val QAM = 13 } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt index 85fc94ca8..4b08a6d21 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt @@ -8,6 +8,8 @@ enum class SecondScreenMode(val id: String, val label: String) { NONE("none", "None"), KEYBOARD_TRACKPAD("keyboard-trackpad", "Keyboard + trackpad"), TERMINAL("terminal", "Terminal"), + /** The Steam Deck controller's back grips and trackpads; offered while the pad is one. */ + DECK_CONTROLS("deck-controls", "Deck grips + trackpads"), } data class SecondScreenDisplay(val id: Int, val label: String) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/AppImageManager.kt b/app/src/main/java/com/droiddeck/launcher/runtime/AppImageManager.kt new file mode 100644 index 000000000..a11df690e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/AppImageManager.kt @@ -0,0 +1,181 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.os.StatFs +import android.util.Log +import com.droiddeck.launcher.core.FileUtils +import java.io.File +import java.io.RandomAccessFile + +/** + * AppImages the user brings: picked from storage, checked, and extracted once into the runtime at + * /opt/appimages/user//app. proot has no FUSE to mount an image, and extracting it at every + * start would cost its whole size in /tmp each time. Each one gets a menu entry on the Linux + * desktop, and the front end starts it under gamescope through bannerlator-appimage-run. + * + * /name holds the name to show, /icon.png the icon when the image has a PNG one. + */ +object AppImageManager { + private const val TAG = "AppImageManager" + const val GUEST_DIR = "/opt/appimages/user" + const val LAUNCHER = "/usr/local/bin/bannerlator-appimage-run" + private const val ELF_AARCH64 = 183 + private const val ELF_X86_64 = 62 + + class Item(val id: String, val name: String, val icon: File?, val comment: String?) { + val guestDir: String get() = "$GUEST_DIR/$id" + } + + private fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1)) + + fun list(context: Context): List = + root(context).listFiles()?.filter { File(it, "app/AppRun").exists() || Files.isLink(File(it, "app/AppRun")) } + ?.map { dir -> + Item( + dir.name, + FileUtils.readString(File(dir, "name"))?.trim()?.takeIf { it.isNotEmpty() } ?: dir.name, + File(dir, "icon.png").takeIf { it.isFile }, + FileUtils.readString(File(dir, "comment"))?.trim()?.takeIf { it.isNotEmpty() }, + ) + }?.sortedBy { it.name.lowercase() } ?: emptyList() + + /** + * What is wrong with [file] as an AppImage for this device, or null when it can be imported. + * An AppImage is an ELF program (its runtime) with "AI" and the format version at byte 8. + */ + internal fun problem(file: File): String? { + if (!file.isFile) return "The file is gone" + val head = ByteArray(20) + try { + RandomAccessFile(file, "r").use { if (it.read(head) < head.size) return "The file is too small to be an AppImage" } + } catch (e: Exception) { + return "The file cannot be read: ${e.message}" + } + if (head[0] != 0x7f.toByte() || head[1] != 'E'.code.toByte() || head[2] != 'L'.code.toByte() || head[3] != 'F'.code.toByte()) { + return "This is not an AppImage (it is not a Linux program)" + } + val machine = (head[18].toInt() and 0xff) or ((head[19].toInt() and 0xff) shl 8) + return when { + machine == ELF_X86_64 -> "This AppImage is built for x86_64 PCs. DroidDeck runs ARM64 (aarch64) AppImages - look for an \"aarch64\" or \"arm64\" download." + machine != ELF_AARCH64 -> "This AppImage is not built for ARM64 (aarch64)" + head[8] != 'A'.code.toByte() || head[9] != 'I'.code.toByte() -> "This is an ARM64 program but not an AppImage" + head[10].toInt() != 2 -> "Only type 2 AppImages can be imported (this one is type ${head[10].toInt()})" + else -> null + } + } + + /** A directory name from the image's file name: "Some_App-1.2-aarch64.AppImage" -> "some-app-1-2-aarch64". */ + internal fun idFor(fileName: String, taken: Set): String { + val base = fileName.removeSuffix(".AppImage").removeSuffix(".appimage").lowercase() + .replace(Regex("[^a-z0-9]+"), "-").trim('-').take(48).ifEmpty { "appimage" } + var id = base + var n = 2 + while (id in taken) id = "$base-${n++}" + return id + } + + /** Imports [file]; null on success, else what went wrong. [onProgress] gets a stage line. */ + fun import(context: Context, file: File, onProgress: (String) -> Unit): String? { + if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first" + problem(file)?.let { return it } + val base = root(context).apply { mkdirs() } + // Room for the image while it is extracted, and the extracted tree (about the same again). + if (StatFs(base.path).availableBytes < file.length() * 3) { + return "Not enough free space: importing needs about ${FileUtils.sizeToString(file.length() * 3)}" + } + val id = idFor(file.name, base.list()?.toSet() ?: emptySet()) + val dir = File(base, id) + val image = File(dir, "image.AppImage") + try { + dir.mkdirs() + // Copied in, not run where it lies: shared storage is mounted noexec, and proot's loader + // maps a program executable. + onProgress("Copying ${file.name}") + file.inputStream().use { input -> image.outputStream().use { FileUtils.copy(input, it) } } + image.setExecutable(true, false) + onProgress("Extracting ${file.name}") + val guestDir = "$GUEST_DIR/$id" + val out = StringBuilder() + val status = GuestCommand.run(context, listOf( + "/bin/bash", "-c", + "cd \"$1\" && ./image.AppImage --appimage-extract >/dev/null && mv squashfs-root app", + "extract", guestDir, + ), logName = "appimage-import") { line -> if (out.length < 2000) out.appendLine(line) } + if (status != 0 || !File(dir, "app").isDirectory) { + FileUtils.delete(dir) + return "The AppImage could not be extracted" + (out.lines().lastOrNull { it.isNotBlank() }?.let { ": $it" } ?: "") + } + image.delete() + describe(dir, file) + writeMenuEntry(context, dir) + return null + } catch (e: Exception) { + Log.e(TAG, "import ${file.name}", e) + FileUtils.delete(dir) + return e.message ?: "Import failed" + } finally { + image.delete() + } + } + + /** Name, comment and icon from the image's own desktop entry; the file name when it has none. */ + private fun describe(dir: File, source: File) { + val app = File(dir, "app") + val entry = app.listFiles { f -> f.isFile && f.name.endsWith(".desktop") }?.firstOrNull() + val text = entry?.let { FileUtils.readString(it) } + fun key(k: String) = text?.let { desktopKey(it, k) } + val name = key("Name") ?: source.name.substringBeforeLast('.') + FileUtils.writeString(File(dir, "name"), name) + key("Comment")?.let { FileUtils.writeString(File(dir, "comment"), it) } + key("Categories")?.let { FileUtils.writeString(File(dir, "categories"), it) } + // The icon the entry names, beside it or anywhere in the image's icon theme, else .DirIcon. + val iconName = key("Icon") + val candidates = listOfNotNull( + iconName?.let { File(app, "$it.png") }, + iconName?.let { n -> app.walkTopDown().maxDepth(8).filter { it.isFile && it.name == "$n.png" }.maxByOrNull { it.length() } }, + File(app, ".DirIcon"), + ) + candidates.firstOrNull { it.isFile && isPng(it) }?.copyTo(File(dir, "icon.png"), overwrite = true) + } + + private fun isPng(f: File): Boolean = try { + f.inputStream().use { val b = ByteArray(4); it.read(b) == 4 && b[1] == 'P'.code.toByte() && b[2] == 'N'.code.toByte() && b[3] == 'G'.code.toByte() } + } catch (e: Exception) { false } + + /** A key of a desktop entry's main group, unlocalised. */ + internal fun desktopKey(desktop: String, key: String): String? { + var inMain = false + for (line in desktop.lineSequence()) { + val t = line.trim() + if (t.startsWith("[")) { inMain = t == "[Desktop Entry]"; continue } + if (inMain && t.startsWith("$key=")) return t.substringAfter('=').trim().takeIf { it.isNotEmpty() } + } + return null + } + + private fun menuEntry(context: Context, id: String) = + // A system directory, not ~/.local/share/applications: the desktop copies game entries from + // here into the user's with a GPU launcher (droiddeck-desktop-gpu) while it runs on pixman. + File(LinuxRuntime.rootDir(context), "usr/local/share/applications/droiddeck-appimage-$id.desktop") + + /** The Linux desktop's menu entry: the desktop's own Exec rules (and droiddeck-gpu) apply to it. */ + private fun writeMenuEntry(context: Context, dir: File) { + val id = dir.name + val name = FileUtils.readString(File(dir, "name"))?.trim() ?: id + val categories = FileUtils.readString(File(dir, "categories"))?.trim()?.takeIf { it.isNotEmpty() } ?: "Utility;" + val icon = if (File(dir, "icon.png").isFile) "$GUEST_DIR/$id/icon.png" else "application-x-executable" + FileUtils.writeString(menuEntry(context, id), + "[Desktop Entry]\nType=Application\nName=$name\nExec=$LAUNCHER $GUEST_DIR/$id %U\nIcon=$icon\n" + + "Terminal=false\nCategories=$categories\nX-DroidDeck-AppImage=$id\n") + } + + fun remove(context: Context, id: String) { + if (id.isEmpty() || '/' in id || id.startsWith(".")) return + FileUtils.delete(File(root(context), id)) + menuEntry(context, id).delete() + } + + private object Files { + fun isLink(f: File) = java.nio.file.Files.isSymbolicLink(f.toPath()) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt new file mode 100644 index 000000000..6ec25ddbf --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt @@ -0,0 +1,424 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.net.LocalServerSocket +import android.net.LocalSocket +import android.os.Process +import android.system.Os +import android.util.Base64 +import android.util.Log +import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.core.HostProcess +import com.droiddeck.launcher.session.SessionPrefs +import org.json.JSONObject +import java.io.DataInputStream +import java.io.DataOutputStream +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.util.concurrent.atomic.AtomicInteger + +/** + * Flatpak's sandboxes, started for the runtime's bwrap stand-in (bannerlator-bwrap). + * + * A Flatpak app runs with its runtime as /usr and itself as /app, which bwrap arranges with mount + * namespaces Android gives no app. proot can show the same picture, and started here - beside the + * session's proot rather than inside it - it traces the app once instead of twice. The stand-in + * sends the sandbox Flatpak asked for (its binds, directories, symlinks and files, in guest paths), + * this builds it under the cache and starts it, then streams the output, the pid and the exit + * status back until one side goes away: the stand-in ending takes the sandbox down with it. + * + * The socket is abstract, so anything on the device could connect: only this app's own uid - the + * uid every program in the runtime already runs as - is served. + */ +object BwrapSpawner { + private const val TAG = "BwrapSpawner" + const val SOCKET = "com.droiddeck.launcher.bwrap" + private val seq = AtomicInteger() + @Volatile private var server: LocalServerSocket? = null + + /** Listens for sandboxes for the rest of the process's life; later calls do nothing. */ + @Synchronized + fun start(context: Context) { + if (server != null) return + val app = context.applicationContext + val socket = try { + LocalServerSocket(SOCKET) + } catch (e: IOException) { + Log.e(TAG, "cannot listen on $SOCKET", e) + return + } + server = socket + FileUtils.delete(File(app.cacheDir, "bwrap")) + Thread({ + while (true) { + val client = try { socket.accept() } catch (e: IOException) { Log.e(TAG, "accept", e); break } + Thread({ serve(app, client) }, "bwrap-${seq.get() + 1}").apply { isDaemon = true; start() } + } + }, "bwrap-server").apply { isDaemon = true; start() } + } + + private fun serve(context: Context, client: LocalSocket) { + val id = seq.incrementAndGet() + val dir = File(context.cacheDir, "bwrap/$id") + client.use { + val out = DataOutputStream(client.outputStream) + try { + val peer = client.peerCredentials + if (peer.uid != Process.myUid()) { + Log.w(TAG, "refused a sandbox for uid ${peer.uid}") + return + } + val input = DataInputStream(client.inputStream) + val kind = input.readUnsignedByte() + val body = ByteArray(input.readInt()).also { input.readFully(it) } + if (kind != 'R'.code) return + val request = JSONObject(String(body, Charsets.UTF_8)) + val plan = plan(context, request, dir) + run(context, plan, client, out, id) + } catch (e: Exception) { + Log.e(TAG, "sandbox $id", e) + runCatching { + frame(out, 'E', (e.message ?: e.toString()).toByteArray()) + frame(out, 'X', "1".toByteArray()) + } + } finally { + FileUtils.delete(dir) + } + } + } + + /** What proot is started with: the sandbox root, its binds (host to guest), and the program. */ + class Plan(val root: File, val binds: List, val cwd: String, val argv: List, val env: Map) + + data class Bind(val host: String, val guest: String) { + val spec: String get() = if (host == guest) host else "$host:$guest" + + companion object { + fun parse(spec: String): Bind { + val colon = spec.indexOf(':') + return if (colon < 0) Bind(spec, spec) else Bind(spec.substring(0, colon), spec.substring(colon + 1)) + } + } + } + + /** True when [path] is [dir] or inside it. */ + internal fun under(path: String, dir: String): Boolean = + dir == "/" || path == dir || path.startsWith(if (dir.endsWith("/")) dir else "$dir/") + + /** + * Where a path the session's programs see lives on the host: through the session's own binds + * (the most specific one), or else inside the rootfs. + */ + internal fun hostPath(sessionBinds: List, rootfs: String, guest: String): String { + val bind = sessionBinds.filter { under(guest, it.guest) }.maxByOrNull { it.guest.length } + ?: return rootfs.trimEnd('/') + guest + val rest = guest.substring(bind.guest.length).trimStart('/') + return if (rest.isEmpty()) bind.host else bind.host.trimEnd('/') + "/" + rest + } + + /** + * Guest [src] bound at [dest]: the bind itself, then every session bind below [src] moved + * under [dest] - /dev brings the session's /dev/shm and GPU node, /proc its stand-ins for what + * Android keeps apps from reading. + */ + internal fun bindsFor(sessionBinds: List, rootfs: String, src: String, dest: String): List { + val out = ArrayList() + out.add(Bind(hostPath(sessionBinds, rootfs, src), dest)) + for (b in sessionBinds.sortedBy { it.guest.length }) { + if (b.guest != src && under(b.guest, src)) { + out.add(Bind(b.host, (dest.trimEnd('/') + "/" + b.guest.substring(src.length).trimStart('/')))) + } + } + return out + } + + internal fun plan(context: Context, request: JSONObject, dir: File): Plan { + val rootfs = LinuxRuntime.rootDir(context).path + val session = LinuxRuntime.lastBinds(context).map { Bind.parse(it) } + val root = File(dir, "root").apply { mkdirs() } + val binds = ArrayList() + var scratch = 0 + fun addBind(b: Bind) { + binds.removeAll { it.guest == b.guest } + binds.add(b) + } + fun coveringBind(dest: String) = binds.filter { under(dest, it.guest) }.maxByOrNull { it.guest.length } + fun newScratch(): File = File(dir, "x${scratch++}") + /** + * Where [dest] can be created on the host: inside the sandbox root, or inside a directory + * of ours bound into it (a --tmpfs under the runtime's /usr, which Flatpak fills with the + * GL extension's links). Null inside anything else bound in - the runtime itself, a host + * directory - which must not be written to. + */ + fun writable(dest: String): File? { + val cover = coveringBind(dest) ?: return inRoot(root, dest) + if (!under(cover.host, dir.path)) return null + return inRoot(File(cover.host), dest.substring(cover.guest.length)) + } + val ops = request.getJSONArray("ops") + for (i in 0 until ops.length()) { + val op = ops.getJSONObject(i) + val dest = op.optString("dest") + when (op.getString("t")) { + "bind" -> { + val src = op.getString("src") + val all = bindsFor(session, rootfs, src, dest) + if (!File(all.first().host).exists()) { + if (!op.optBoolean("try")) Log.w(TAG, "sandbox source $src is missing; left out") + continue + } + all.forEach { addBind(it) } + } + "proc" -> bindsFor(session, rootfs, "/proc", dest).forEach { addBind(it) } + "dev" -> bindsFor(session, rootfs, "/dev", dest).forEach { addBind(it) } + "dir" -> { + val perms = op.optInt("perms", 0x1ed) + val here = writable(dest) + when { + op.optBoolean("empty") && coveringBind(dest) != null -> + addBind(Bind(newScratch().apply { mkdirs(); chmod(this, perms) }.path, dest)) + here != null && (here.isDirectory || here.mkdirs()) -> chmod(here, perms) + File(hostPath(binds, root.path, dest)).isDirectory -> {} + else -> addBind(Bind(newScratch().apply { mkdirs(); chmod(this, perms) }.path, dest)) + } + } + "file" -> { + val data = Base64.decode(op.getString("data"), Base64.DEFAULT) + val here = writable(dest) + val f = if (here != null && here.parentFile?.let { it.isDirectory || it.mkdirs() } == true) here + else newScratch().also { addBind(Bind(it.path, dest)) } + f.writeBytes(data) + chmod(f, op.optInt("perms", 0x1b6)) + } + "symlink" -> { + val target = op.getString("target") + val link = writable(dest) + if (link != null) { + link.parentFile?.mkdirs() + if (!Files.isSymbolicLink(link.toPath()) && !link.exists()) Files.createSymbolicLink(link.toPath(), java.nio.file.Paths.get(target)) + } else { + // A link inside the runtime's own tree cannot be made; what it points at is + // bound in its place. + val abs = if (target.startsWith("/")) target else normalize(dest.substringBeforeLast('/') + "/" + target) + val host = hostPath(binds, root.path, abs) + if (File(host).exists()) addBind(Bind(host, dest)) else Log.w(TAG, "symlink $dest -> $target: nothing there; left out") + } + } + } + } + if (binds.any { it.guest == "/proc" }) genericCpuinfo(context)?.let { addBind(Bind(it.path, "/proc/cpuinfo")) } + val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } } + val env = LinkedHashMap() + request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } } + if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) } + preload(session, rootfs, env).forEach { addBind(it) } + browserSandboxes(env) + return Plan(root, binds, request.optString("cwd", "/").ifEmpty { "/" }, argv, env) + } + + /** Where a sandbox finds the runtime's own GPU driver. */ + private const val GPU_DIR = "/run/droiddeck-gpu" + + /** + * The GPU, for an app that is given /dev. Flathub's Mesa has Turnip, but built for the DRM + * kernel driver: Adreno on Android is KGSL, so apps fell back to drawing on the CPU. The + * runtime's own Turnip has the KGSL backend and needs nothing the Freedesktop runtime lacks + * but three libraries, which come with it; Mesa's GL then runs on it through Zink. An app's + * own choice of driver (VK_ICD_FILENAMES, MESA_LOADER_DRIVER_OVERRIDE) is left alone. + */ + private fun gpu(rootfs: String, root: File, env: MutableMap): List? { + val lib = File(rootfs, "usr/lib") + val driver = File(lib, "libvulkan_freedreno.so") + if (!driver.isFile || !File("/dev/kgsl-3d0").exists()) return null + if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null + // A window on the desktop while labwc composites with pixman gets shared-memory buffers + // only; Zink cannot present there, so such an app keeps Flathub's own Mesa (llvmpipe). + // From the desktop, games go through droiddeck-gpu's gamescope and do get the GPU. + if (env["WLR_RENDERER"] == "pixman" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null + val binds = ArrayList() + for (name in listOf("libvulkan_freedreno.so", "libdisplay-info.so.3", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")) { + val f = File(lib, name) + if (!f.exists()) { Log.w(TAG, "gpu: the runtime has no $name; apps draw on the CPU"); return null } + binds.add(Bind(f.canonicalPath, "$GPU_DIR/$name")) + } + // Beside the sandbox root, in the sandbox's own directory: removed with it. + val icd = File(root.parentFile, "freedreno_icd.json") + icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_freedreno.so\", \"api_version\": \"1.4.0\"}}\n") + binds.add(Bind(icd.path, "$GPU_DIR/freedreno_icd.json")) + env["VK_DRIVER_FILES"] = "$GPU_DIR/freedreno_icd.json" + env["VK_ICD_FILENAMES"] = "$GPU_DIR/freedreno_icd.json" + if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) { + env["MESA_LOADER_DRIVER_OVERRIDE"] = "zink" + env["GALLIUM_DRIVER"] = "zink" + } + // The driver's own libraries, found beside it; nothing else is in that directory. + env["LD_LIBRARY_PATH"] = listOf(env["LD_LIBRARY_PATH"], GPU_DIR).filter { !it.isNullOrEmpty() }.joinToString(":") + return binds + } + + /** + * What every program in the session preloads (SessionFiles writes /etc/ld.so.preload): the + * session shim - SysV shared memory for X11, the network calls Android refuses - and the + * controller reader. A sandbox's /etc is the runtime's, so the same libraries go in through + * LD_PRELOAD instead, with the directory the controllers' rings live in; without them an app + * saw no gamepad. Both are built against an older glibc than any Flathub runtime has. + */ + private fun preload(session: List, rootfs: String, env: MutableMap): List { + val libs = FileUtils.readString(File(rootfs, "etc/ld.so.preload"))?.lines() + ?.map { it.trim() }?.filter { it.startsWith("/") && File(rootfs + it).isFile } ?: return emptyList() + if (libs.isEmpty()) return emptyList() + val binds = ArrayList() + val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } } + env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":") + // Not through ZYPAK_LD_PRELOAD to Chromium's children: the session shim's stat hooks then + // hide the setuid bit zypak fakes on chrome-sandbox, and Chromium refuses to start. + // The controllers: FAKE_EVDEV_DIR is /dev/input, the rings beside it in /dev. + env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev -> + binds.addAll(bindsFor(session, rootfs, dev, dev)) + } + return binds + } + + private const val PRELOAD_DIR = "/run/droiddeck-preload" + + /** + * Browsers sandbox their own children, and neither way works in here. Firefox wants + * namespaces and seccomp from the kernel; its content processes died without them (the + * desktop sets the same for the runtime's own Firefox). Chromium and Electron apps start + * their zygote through Flatpak's portal (zypak's spawn strategy), and the portal refuses: + * it knows a Flatpak by /proc//root/.flatpak-info, and a proot sandbox's root is the + * host's. zypak's older strategy mimics the zygote inside the app's own sandbox instead. + */ + private fun browserSandboxes(env: MutableMap) { + env.putIfAbsent("ZYPAK_ZYGOTE_STRATEGY_SPAWN", "0") + // Qt WebEngine is Chromium without zypak: it sets up its own namespace sandbox. + env.putIfAbsent("QTWEBENGINE_DISABLE_SANDBOX", "1") + // Chromium on Wayland asks the render node the compositor names for its DRM version; + // KGSL has none, and the GPU process aborts until Chromium gives up ("GPU process isn't + // usable"). Electron picks Wayland from XDG_SESSION_TYPE; with an X server there (every + // session has Xwayland) it stays on X11, which works. GTK and Qt go by their own settings. + if (env.containsKey("DISPLAY")) env["XDG_SESSION_TYPE"] = "x11" + for (name in listOf("MOZ_DISABLE_CONTENT_SANDBOX", "MOZ_DISABLE_GMP_SANDBOX", "MOZ_DISABLE_RDD_SANDBOX", + "MOZ_DISABLE_SOCKET_PROCESS_SANDBOX", "MOZ_DISABLE_UTILITY_SANDBOX")) { + env.putIfAbsent(name, "1") + } + } + + /** + * /proc/cpuinfo without the cores' names. Snapdragon's ARMv9 cores (Cortex-A510/A715/X3) have + * SVE2 by architecture, and LLVM - llvmpipe's JIT in Flathub's Mesa, which is what apps draw + * with here - takes the CPU part to mean it may use it. Qualcomm leaves SVE off, so the first + * shader compiled killed the app with SIGILL. Without a part number LLVM targets generic + * ARMv8 plus the "Features" line, which lists what the kernel really enabled. + */ + private fun genericCpuinfo(context: Context): File? = try { + val out = File(context.cacheDir, "cpuinfo-generic") + val text = File("/proc/cpuinfo").readLines() + .filterNot { it.startsWith("CPU implementer") || it.startsWith("CPU part") || it.startsWith("CPU variant") || it.startsWith("CPU revision") } + .joinToString("\n", postfix = "\n") + // Sandboxes start side by side; one must never read another's half-written copy. + if (!out.isFile || out.readText() != text) { + val staged = File.createTempFile("cpuinfo", null, context.cacheDir) + staged.writeText(text) + if (!staged.renameTo(out)) staged.delete() + } + out + } catch (e: Exception) { + Log.w(TAG, "cpuinfo", e); null + } + + /** [path] with "." and ".." resolved lexically. */ + internal fun normalize(path: String): String { + val out = ArrayList() + for (part in path.split('/')) when (part) { + "", "." -> {} + ".." -> if (out.isNotEmpty()) out.removeAt(out.size - 1) + else -> out.add(part) + } + return "/" + out.joinToString("/") + } + + /** + * [guest] inside the sandbox root, or null when the way there crosses a symlink: one of + * Flatpak's (var/run -> ../run) may point anywhere once followed on the host. + */ + private fun inRoot(root: File, guest: String): File? { + var f = root + for (part in guest.split('/').filter { it.isNotEmpty() }) { + if (part == "..") return null + f = File(f, part) + if (Files.isSymbolicLink(f.toPath())) return null + } + return f + } + + private fun chmod(f: File, mode: Int) { + try { Os.chmod(f.path, mode) } catch (e: Exception) { /* the default mode serves */ } + } + + private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) { + val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd) + // DROIDDECK_PROOT_VERBOSE=N in the app's environment (flatpak run --env=...) has proot + // say what it does, to logcat in full: for a sandbox that dies without a word. + val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull() + if (verbose != null) { cmd.add(1, "-v"); cmd.add(2, verbose.toString()) } + plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) } + // proot hands its own environment on; the sandbox gets exactly what Flatpak asked for. + cmd.add("/usr/bin/env") + cmd.add("-i") + plan.env.forEach { (k, v) -> cmd.add("$k=$v") } + cmd.addAll(plan.argv) + val builder = ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root) + builder.environment().apply { + clear() + put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path) + put("PROOT_TMP_DIR", context.cacheDir.path) + if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1") + LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) } + } + val process = builder.start() + val pid = HostProcess.pidOf(process) + // A sandbox lives exactly as long as its bwrap stand-in, which ends it; a session starting + // meanwhile (OrphanReaper) must not take it - an install's extra-data step, say. + com.droiddeck.launcher.session.OrphanReaper.keep(pid) + Log.i(TAG, "sandbox $id pid $pid: ${plan.argv.joinToString(" ")} (${plan.binds.size} binds)") + synchronized(out) { frame(out, 'P', pid.toString().toByteArray()) } + // The stand-in going away (Flatpak killed, the session over) ends the sandbox. + Thread({ + try { while (client.inputStream.read() >= 0) { /* nothing is sent after the request */ } } + catch (e: IOException) { /* closed */ } + if (process.isAlive) { + Log.i(TAG, "sandbox $id: its bwrap is gone; stopping it") + process.destroy() + } + }, "bwrap-$id-watch").apply { isDaemon = true; start() } + val buffer = ByteArray(16384) + // The start of what the sandbox says goes to logcat too: a sandbox that fails at once + // (proot refusing a bind, a missing library) says why there even when nothing reads it. + var logged = 0 + process.inputStream.use { stream -> + while (true) { + val n = try { stream.read(buffer) } catch (e: IOException) { -1 } + if (n < 0) break + if (logged < 4096 || verbose != null) { + String(buffer, 0, if (verbose != null) n else minOf(n, 4096 - logged)).lines().filter { it.isNotBlank() } + .forEach { Log.i(TAG, "sandbox $id: $it") } + logged += n + } + try { synchronized(out) { frame(out, 'O', buffer.copyOf(n)) } } catch (e: IOException) { break } + } + } + val status = process.waitFor() + com.droiddeck.launcher.session.OrphanReaper.release(pid) + Log.i(TAG, "sandbox $id exited $status") + runCatching { synchronized(out) { frame(out, 'X', status.toString().toByteArray()) } } + } + + private fun frame(out: DataOutputStream, kind: Char, payload: ByteArray) { + out.writeByte(kind.code) + out.writeInt(payload.size) + out.write(payload) + out.flush() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/FlatpakManager.kt b/app/src/main/java/com/droiddeck/launcher/runtime/FlatpakManager.kt new file mode 100644 index 000000000..0960d95e9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/FlatpakManager.kt @@ -0,0 +1,204 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.core.FileUtils +import org.json.JSONObject +import java.io.File + +/** + * Flatpak in the Linux runtime: putting it there (bannerlator-flatpak-setup), the apps installed + * from Flathub, and installing, removing and updating them (bannerlator-flatpak). One per-user + * installation at /root/.local/share/flatpak, so nothing needs the system helper or polkit. + * + * Every command runs in a proot of its own, outside any session: the store works whether or not + * Steam or the desktop is up, and a session starting meanwhile leaves it running (OrphanReaper). + */ +object FlatpakManager { + private const val TAG = "FlatpakManager" + const val FLATPAK = "/usr/bin/flatpak" + const val BWRAP = "/usr/local/bin/bannerlator-bwrap" + /** The program the front end starts a Flatpak app through, in a session of its own. */ + const val LAUNCHER = "/usr/local/bin/bannerlator-flatpak-run" + private const val HELPER = "/usr/local/bin/bannerlator-flatpak" + private const val SETUP = "/usr/local/bin/bannerlator-flatpak-setup" + private const val USER_DIR = "root/.local/share/flatpak" + + /** One store operation at a time: Flatpak locks its installation per transaction anyway. */ + @Volatile var busy: String? = null + private set + + class App(val id: String, val name: String, val icon: File?, val branch: String, val summary: String?) + + /** Flatpak is in the runtime, with Flathub to install from. */ + fun ready(context: Context): Boolean { + val root = LinuxRuntime.rootDir(context) + return File(root, FLATPAK.substring(1)).isFile && + File(root, "var/cache/droiddeck-flatpak/installed").isFile && + (FileUtils.readString(File(root, "$USER_DIR/repo/config"))?.contains("[remote \"flathub\"]") == true) + } + + private fun arch(): String = when (android.os.Build.SUPPORTED_ABIS.firstOrNull()) { + "x86_64" -> "x86_64" + else -> "aarch64" + } + + /** + * The installed apps, read from the installation itself: each app's deployed files carry the + * desktop entry and icons it exports, so listing them needs no process in the runtime. + */ + fun installedApps(context: Context): List { + val apps = File(LinuxRuntime.rootDir(context), "$USER_DIR/app") + val arch = arch() + return apps.listFiles()?.mapNotNull { dir -> + val id = dir.name + val archDir = File(dir, arch) + val branch = archDir.listFiles()?.firstOrNull { File(it, "active").exists() } ?: return@mapNotNull null + val active = File(branch, "active") + val export = File(active, "export/share") + val desktop = FileUtils.readString(File(export, "applications/$id.desktop")) + val name = desktop?.let { entry(it, "Name") } ?: id.substringAfterLast('.') + val summary = desktop?.let { entry(it, "Comment") } + App(id, name, icon(export, id), branch.name, summary) + }?.sortedBy { it.name.lowercase() } ?: emptyList() + } + + fun isInstalled(context: Context, id: String): Boolean = + File(LinuxRuntime.rootDir(context), "$USER_DIR/app/$id/${arch()}").listFiles()?.any { File(it, "active").exists() } == true + + /** A key of the desktop entry's main group ([Desktop Entry]), unlocalised. */ + private fun entry(desktop: String, key: String): String? { + var inMain = false + for (line in desktop.lineSequence()) { + val t = line.trim() + if (t.startsWith("[")) { inMain = t == "[Desktop Entry]"; continue } + if (inMain && t.startsWith("$key=")) return t.substringAfter('=').trim().takeIf { it.isNotEmpty() } + } + return null + } + + /** The largest PNG the app exports (the front end draws no SVG). */ + private fun icon(export: File, id: String): File? { + val hicolor = File(export, "icons/hicolor") + return hicolor.listFiles() + ?.mapNotNull { size -> size.name.substringBefore('x').toIntOrNull()?.let { it to File(size, "apps/$id.png") } } + ?.filter { it.second.isFile } + ?.maxByOrNull { it.first }?.second + } + + /** Runs [argv] in the runtime, its output also in Download/DroidDeck/flatpak-.log. */ + private fun runGuest(context: Context, argv: List, 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) + } + + private inline fun exclusive(what: String, block: () -> T): T? { + synchronized(this) { + if (busy != null) return null + busy = what + } + try { return block() } finally { busy = null } + } + + /** Puts Flatpak into the runtime and adds Flathub. Null on success, else what went wrong. */ + fun setup(context: Context, onProgress: (String, Int) -> Unit): String? { + if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first" + return exclusive("setup") { + var failure: String? = null + val status = runGuest(context, listOf("/bin/bash", SETUP), fakeRoot = true) { line -> + Log.i(TAG, "setup: $line") + when { + line.startsWith("== STEP ") -> onProgress(line.removePrefix("== STEP "), -1) + line.startsWith("== FAIL ") -> failure = line.removePrefix("== FAIL ") + } + } + when { + failure != null -> failure + status != 0 -> "Flatpak setup failed (exit $status)" + !ready(context) -> "Flatpak setup did not finish" + else -> null + } + } ?: "Another store task is running" + } + + /** + * One store operation - install, uninstall or update - with its progress as a stage line and + * an overall percentage across the steps Flatpak plans (a runtime, its extensions, the app). + */ + private fun transaction(context: Context, verb: String, id: String?, onProgress: (String, Int) -> Unit): String? { + if (!ready(context)) return "Set up Flatpak first" + return exclusive("$verb:${id ?: "all"}") { + var error: String? = null + // Progress lines carry no ref; they belong to the step the last "op" line started. + var step = "Starting" + val argv = listOfNotNull("/usr/bin/python3", HELPER, verb, id) + val status = runGuest(context, argv, fakeRoot = false) { line -> + val o = runCatching { JSONObject(line) }.getOrNull() + if (o == null) { Log.i(TAG, "$verb: $line"); return@runGuest } + when (o.optString("e")) { + "op" -> { step = stage(o); onProgress(step, overall(o, 0)) } + "progress" -> onProgress(step, overall(o, o.optInt("percent"))) + "error" -> { error = o.optString("message"); Log.w(TAG, "$verb $id: $error") } + "warning" -> Log.w(TAG, "$verb $id: ${o.optString("message")}") + } + } + error ?: if (status != 0) "Flatpak exited with status $status" else null + } ?: "Another store task is running" + } + + private fun stage(o: JSONObject): String { + val ref = o.optString("ref") + val name = refLabel(ref) + val step = if (o.optInt("n") > 1) " (${o.optInt("i")}/${o.optInt("n")})" else "" + return when (o.optString("kind")) { + "uninstall" -> "Removing $name$step" + "update" -> "Updating $name$step" + else -> "Installing $name$step" + }.let { if (ref.isEmpty()) o.optString("status").ifEmpty { "Working" } else it } + } + + /** A ref in words: "app/org.supertuxproject.SuperTux/aarch64/stable" is "SuperTux". */ + internal fun refLabel(ref: String): String { + val parts = ref.split('/') + val id = parts.getOrNull(1) ?: return ref + if (parts.firstOrNull() == "app") return id.substringAfterLast('.') + val branch = parts.getOrNull(3)?.let { " $it" } ?: "" + return when { + id.endsWith(".Locale") -> "translations" + ".GL." in id || ".GL32." in id -> "graphics drivers" + "codecs" in id.lowercase() || id.endsWith(".ffmpeg-full") -> "media codecs" + id.endsWith(".Platform") -> when (val vendor = id.removeSuffix(".Platform").substringAfterLast('.')) { + "gnome", "kde" -> vendor.uppercase() + else -> vendor.replaceFirstChar { it.uppercase() } + } + " runtime$branch" + else -> id.substringAfterLast('.') + } + } + + /** The whole transaction's percentage: steps done, plus this one's share. */ + private fun overall(o: JSONObject, percent: Int): Int { + val n = o.optInt("n").coerceAtLeast(1) + val i = o.optInt("i").coerceIn(1, n) + return (((i - 1) * 100 + percent.coerceIn(0, 100)) / n) + } + + fun install(context: Context, id: String, onProgress: (String, Int) -> Unit) = transaction(context, "install", id, onProgress) + fun uninstall(context: Context, id: String, onProgress: (String, Int) -> Unit) = transaction(context, "uninstall", id, onProgress) + fun update(context: Context, id: String?, onProgress: (String, Int) -> Unit) = transaction(context, "update", id, onProgress) + + /** Installed apps with an update on Flathub, or null when that could not be checked. */ + fun updates(context: Context): Set? { + if (!ready(context)) return emptySet() + var apps: Set? = null + exclusive("updates") { + runGuest(context, listOf("/usr/bin/python3", HELPER, "updates"), fakeRoot = false) { line -> + val o = runCatching { JSONObject(line) }.getOrNull() ?: return@runGuest + if (o.optString("e") == "updates") { + val a = o.optJSONArray("apps") + apps = (0 until (a?.length() ?: 0)).map { a!!.getString(it) }.toSet() + } + } + } + return apps + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt new file mode 100644 index 000000000..d420d5771 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt @@ -0,0 +1,69 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +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.SessionPrefs +import java.io.File + +/** + * One command in the Linux runtime outside any session - the store's Flatpak work, an AppImage + * import - in a proot of its own. A session starting meanwhile leaves it running (OrphanReaper). + */ +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/.log beside the session logs, so a problem can + * be handed over like a session's. + */ + fun run(context: Context, argv: List, fakeRoot: Boolean = false, logName: String? = null, + onLine: (String) -> Unit): Int { + val log = logName?.let { + 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) { line -> log?.println(line); log?.flush(); onLine(line) } + } finally { + log?.close() + } + } + + private fun runLogged(context: Context, argv: List, fakeRoot: Boolean, onLine: (String) -> Unit): Int { + val root = LinuxRuntime.rootDir(context) + LinuxRuntime.writeAccounts(context) + SessionFiles.stage(context, root) + // The resolver otherwise names the DNS of whatever network the last session was on. + LinuxNetworkLinkComponent(context, root).publish() + val runtimeDir = File(context.filesDir, ".flatpak-rt").apply { mkdirs() } + val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot) + LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), null) + .forEach { cmd.add("-b"); cmd.add(it) } + cmd += listOf( + "/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8", + "PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${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", + ) + cmd += argv + val builder = ProcessBuilder(cmd).directory(root).redirectErrorStream(true) + builder.environment().apply { + put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path) + put("PROOT_TMP_DIR", context.cacheDir.path) + if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1") + LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) } + } + val process = builder.start() + val pid = HostProcess.pidOf(process) + OrphanReaper.keep(pid) + try { + process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) } + return process.waitFor() + } finally { + OrphanReaper.release(pid) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java index 816d7c3ad..6ad52da27 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java @@ -6,6 +6,7 @@ import android.system.ErrnoException; import android.system.Os; import android.system.StructStat; import android.system.StructUtsname; +import com.droiddeck.launcher.session.SessionPrefs; import java.io.File; @@ -33,7 +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"; - private static final String GUEST_HOSTNAME = "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"; @@ -115,22 +115,65 @@ public final class LinuxRuntime { File externalStorage, List extraBinds, List guestCommand) { File root = rootDir(context); + List binds = binds(context, 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 cmd = prootPrefix(context, root, "/root"); + for (String spec : binds) bind(cmd, spec); + cmd.addAll(guestCommand); + return cmd; + } + + /** + * The binds of the last command built: the guest's view of the host, which the Flatpak + * sandboxes started beside a session (BwrapSpawner) translate their paths through. + */ + private static volatile List lastBinds; + + public static List lastBinds(Context context) { + List binds = lastBinds; + if (binds != null) return binds; + return binds(context, null, null, android.os.Environment.getExternalStorageDirectory(), null); + } + + /** proot and its options up to the binds: the rootfs at {@code root}, starting in {@code cwd}. */ + public static List prootPrefix(Context context, File root, String cwd) { + return prootPrefix(context, root, cwd, false); + } + + /** + * As above; {@code fakeRoot} has the guest see uid 0 (proot -0), for the package tools that + * refuse any other uid. Files it writes still belong to the app. + */ + public static List prootPrefix(Context context, File root, String cwd, boolean fakeRoot) { List cmd = new ArrayList<>(); cmd.add(prootBinary(context).getPath()); cmd.add("--kill-on-exit"); // Preserve the host kernel identity while giving the guest the app's branded host name. - cmd.add("--kernel-release=" + guestUtsname()); + cmd.add("--kernel-release=" + guestUtsname(SessionPrefs.guestHostname(context))); // Android's app seccomp policy traps the whole set*id family. Xwayland's Popen() calls // setgid()/setuid() before it execs xkbcomp and _exit(127)s when they fail, so without // this the keymap never compiles and Xwayland dies. -i makes proot answer those calls // itself while still reporting our real ids, so nothing inside sees a different user. int uid = Process.myUid(); - cmd.add("-i"); - cmd.add(uid + ":" + uid); + if (fakeRoot) { + cmd.add("-0"); + } else { + cmd.add("-i"); + cmd.add(uid + ":" + uid); + } cmd.add("-r"); cmd.add(root.getPath()); cmd.add("-w"); - cmd.add("/root"); + cmd.add(cwd); + return cmd; + } + + /** The {@code host:guest} (or same-path) bind specs of a session; see {@link #command}. */ + public static List binds(Context context, File sessionRoot, File runtimeDir, + File externalStorage, List extraBinds) { + File root = rootDir(context); + List cmd = new ArrayList<>(); bind(cmd, "/dev"); bind(cmd, "/proc"); bind(cmd, "/sys"); @@ -142,7 +185,7 @@ public final class LinuxRuntime { bind(cmd, new File(root, "etc/bannerlator/empty").getPath() + ":/sys/fs/selinux"); bind(cmd, context.getFilesDir().getPath()); bind(cmd, context.getCacheDir().getPath()); - bind(cmd, runtimeDir.getPath()); + if (runtimeDir != null) bind(cmd, runtimeDir.getPath()); if (sessionRoot != null) bind(cmd, sessionRoot.getPath()); if (externalStorage != null && externalStorage.isDirectory()) { bind(cmd, externalStorage.getPath()); @@ -193,11 +236,14 @@ public final class LinuxRuntime { } } bindGpuNode(context, cmd); + bindAdrenoStats(cmd); + bindCpuTemps(cmd, root); if (extraBinds != null) { for (String spec : extraBinds) bind(cmd, spec); } - cmd.addAll(guestCommand); - return cmd; + List specs = new ArrayList<>(); + for (int i = 0; i + 1 < cmd.size(); i += 2) specs.add(cmd.get(i + 1)); + return specs; } /** @@ -244,15 +290,91 @@ public final class LinuxRuntime { bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node); } + /** + * Valve's mangoapp (Deck mode's performance overlay) reads an Adreno GPU's load, clock and + * temperatures from where they are on Valve's own hardware; every Adreno under Android keeps + * them in KGSL's sysfs, readable by the app, though which files a kernel has differs between + * Snapdragon generations - so each value takes the first source that exists, the order other + * Android PC emulators (GameNative, Winlator forks) read them in. A value found nowhere is left + * alone. + */ + private static void bindAdrenoStats(List cmd) { + String kgsl = "/sys/class/kgsl/kgsl-3d0/"; + String gpuTemp = firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu")); + String[][] stats = { + {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"}, + {gpuTemp, "/sys/class/thermal/thermal_zone26/temp"}, + {thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"}, + }; + for (String[] stat : stats) { + if (stat[0] != null) bind(cmd, stat[0] + ":" + stat[1]); + } + } + + /** + * mangoapp's CPU temperature is the mean of the thermal zones named cpuN-thermal or + * cpuN-top-thermal, as mainline kernels name them; Android kernels name the same sensors + * cpuss-0, cpu-1-0, cpu0-silver-usr, apc1-cpu0-usr and the like, so those zones are shown + * under the mainline name. + */ + private static void bindCpuTemps(List cmd, File root) { + File name = new File(root, "etc/bannerlator/cpu-thermal-type"); + try { + if (!name.isFile()) Files.write(name.toPath(), "cpu0-thermal\n".getBytes(StandardCharsets.US_ASCII)); + } catch (IOException e) { + return; + } + for (java.util.Map.Entry zone : thermalZones().entrySet()) { + String type = zone.getKey(); + if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) { + bind(cmd, name.getPath() + ":" + new File(zone.getValue(), "type").getPath()); + } + } + } + + private static String firstReadable(String... paths) { + for (String path : paths) { + if (path != null && new File(path).canRead()) return path; + } + return null; + } + + /** The temp file of the thermal zone for a sensor: the one named so, else the first whose name has it. */ + private static String thermalZone(String sensor) { + java.util.Map zones = thermalZones(); + File zone = zones.get(sensor); + for (java.util.Map.Entry e : new java.util.TreeMap<>(zones).entrySet()) { + if (zone == null && e.getKey().contains(sensor)) zone = e.getValue(); + } + return zone != null ? new File(zone, "temp").getPath() : null; + } + + /** The device's thermal zones by their sensor's name, in lower case. */ + private static java.util.Map thermalZones() { + java.util.Map byType = new java.util.HashMap<>(); + File[] zones = new File("/sys/class/thermal").listFiles((dir, n) -> n.startsWith("thermal_zone")); + if (zones == null) return byType; + for (File zone : zones) { + try (java.io.BufferedReader r = new java.io.BufferedReader(new java.io.FileReader(new File(zone, "type")))) { + byType.putIfAbsent(String.valueOf(r.readLine()).trim().toLowerCase(java.util.Locale.ROOT), zone); + } catch (IOException ignored) { + } + } + return byType; + } + private static void bind(List cmd, String spec) { cmd.add("-b"); cmd.add(spec); } /** PRoot's complex -k format: sysname, nodename, release, version, machine, domain, HWCAP. */ - private static String guestUtsname() { + static String guestUtsname(String hostname) { StructUtsname host = Os.uname(); - return "\\" + host.sysname + "\\" + GUEST_HOSTNAME + "\\" + host.release + return "\\" + host.sysname + "\\" + hostname + "\\" + host.release + "\\" + host.version + "\\" + host.machine + "\\localdomain\\-1\\"; } diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt new file mode 100644 index 000000000..4210d07e6 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt @@ -0,0 +1,75 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.util.AtomicFile +import com.droiddeck.launcher.core.GameEnvironment +import com.droiddeck.launcher.runtime.LinuxRuntime +import org.json.JSONObject +import java.io.File + +object GameEnvironmentStore { + private const val SETTINGS = "game-environment.json" + private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json" + + @Synchronized + fun read(context: Context): GameEnvironment.Config { + val file = AtomicFile(File(context.filesDir, SETTINGS)) + val bytes = try { file.readFully() } catch (_: java.io.FileNotFoundException) { return GameEnvironment.Config() } + return decode(JSONObject(bytes.toString(Charsets.UTF_8))) + } + + fun decode(json: JSONObject): GameEnvironment.Config { + require(json.getInt("version") == 1) + fun entries(value: JSONObject?): Map = buildMap { + value?.keys()?.forEach { name -> + require(GameEnvironment.validName(name)) + val entry = value.get(name) + require(entry == JSONObject.NULL || entry is String && GameEnvironment.validValue(entry)) + put(name, if (entry == JSONObject.NULL) null else entry as String) + } + } + val games = json.optJSONObject("games") + return GameEnvironment.Config(entries(json.optJSONObject("shared")), buildMap { + games?.keys()?.forEach { id -> + require(id.isNotEmpty() && GameEnvironment.validScope(id)) + put(id, entries(games.getJSONObject(id))) + } + }) + } + + fun encode(config: GameEnvironment.Config): JSONObject { + fun entries(values: Map) = JSONObject().apply { + values.forEach { (key, value) -> put(key, value ?: JSONObject.NULL) } + } + return JSONObject().put("version", 1).put("shared", entries(config.shared)).put("games", JSONObject().apply { + config.games.forEach { (id, values) -> put(id, entries(values)) } + }) + } + + @Synchronized + fun save(context: Context, config: GameEnvironment.Config) { + val json = encode(config) + decode(json) + write(File(context.filesDir, SETTINGS), json.toString()) + publish(context, config) + } + + @Synchronized + fun publish(context: Context, config: GameEnvironment.Config = read(context)) { + val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context)) + config.shared) + write(File(LinuxRuntime.rootDir(context), GUEST_FILE), encode(resolved).toString()) + } + + private fun write(file: File, text: String) { + check(file.parentFile!!.isDirectory || file.parentFile!!.mkdirs()) + val atomic = AtomicFile(file) + val output = atomic.startWrite() + try { + output.write(text.toByteArray(Charsets.UTF_8)) + atomic.finishWrite(output) + } catch (error: Exception) { + atomic.failWrite(output) + throw error + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt b/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt new file mode 100644 index 000000000..e73668468 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt @@ -0,0 +1,238 @@ +package com.droiddeck.launcher.session + +import android.os.Environment +import com.droiddeck.launcher.frontend.Library +import java.io.BufferedInputStream +import java.io.BufferedOutputStream +import java.io.File +import java.io.FileOutputStream +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream + +/** + * Game saves in and out of a game's Proton prefix, as zips other apps read: GameHub keeps a prefix's + * drive_c rooted at "/drive_c/users/steamuser/…", Winlator / WinNative / Bannerlator at + * "drive_c/users/xuser/…". Proton here runs as steamuser too, so on the way in any user folder but + * Public becomes steamuser, and on the way out the chosen layout decides the user segment. + * + * Saves belong to the game's prefix (compatdata//pfx), whichever Proton it runs with. + * Ported from Bannerlator's GameSaveBackup and SaveLocator. + */ +object GameSaves { + enum class Layout(val label: String, val rootPrefix: String, val user: String) { + GAMEHUB("GameHub zip", "/drive_c/", "steamuser"), + WINLATOR("Winlator zip", "drive_c/", "xuser"), + } + + /** A game, its prefix, and the save folders found in it. */ + data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List) { + val launched get() = prefix?.let { File(it, "drive_c").isDirectory } == true + } + + /** A folder of saves, relative to the steamuser profile. */ + data class SaveDir(val relPath: String, val files: Int, val bytes: Long) + + private const val USER = "steamuser" + + fun savesDir(): File = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck/Saves") + private fun backupsDir(): File = File(savesDir(), "backups") + + /** [game] with its prefix and the saves found there; reads files, so not on the main thread. */ + fun game(game: Library.SteamGame): Game = Game(game, game.protonPrefix, game.protonPrefix?.let { locate(it, game) } ?: emptyList()) + + // ------------------------------------------------------------------ finding saves + + /** Roots of the steamuser profile that hold most PC game saves, in the order they are trusted. */ + private val SAVE_ROOTS = listOf("Documents/My Games", "Saved Games", "AppData/Roaming", "Documents", "AppData/Local", "AppData/LocalLow") + private const val KEEP_THRESHOLD = 50 + + private fun profile(prefix: File) = File(prefix, "drive_c/users/$USER") + + /** + * Folders under the save roots, one and two deep, whose names match the game's name or its folder's. + * Nested matches keep the outer folder only. + */ + fun locate(prefix: File, game: Library.SteamGame): List { + val profile = profile(prefix) + if (!profile.isDirectory) return emptyList() + val ids = listOfNotNull(game.name, game.gameFiles?.name).map(::ident).filter { it.norm.isNotEmpty() } + if (ids.isEmpty()) return emptyList() + val hits = LinkedHashMap() + fun consider(dir: File) { + val d = ident(dir.name) + if (d.norm.isEmpty()) return + val s = ids.maxOf { score(it, d) } + if (s < KEEP_THRESHOLD) return + val rel = dir.relativeTo(profile).path.replace(File.separatorChar, '/') + if ((hits[rel] ?: -1) < s) hits[rel] = s + } + for (root in SAVE_ROOTS) { + File(profile, root).listFiles()?.filter { it.isDirectory }?.forEach { d1 -> + consider(d1) + d1.listFiles()?.filter { it.isDirectory }?.forEach(::consider) + } + } + val kept = ArrayList() + for (rel in hits.entries.sortedByDescending { it.value }.map { it.key }) { + if (kept.none { rel == it || rel.startsWith("$it/") }) kept.add(rel) + } + return kept.map { rel -> + var files = 0 + var bytes = 0L + File(profile, rel).walkTopDown().filter { it.isFile }.forEach { files++; bytes += it.length() } + SaveDir(rel, files, bytes) + }.filter { it.files > 0 } + } + + private data class Ident(val norm: String, val tokens: Set) + + private fun ident(raw: String): Ident { + val cleaned = raw.lowercase().replace("®", "").replace("™", "").replace("©", "") + return Ident(cleaned.filter { it.isLetterOrDigit() }, cleaned.split(Regex("[^a-z0-9]+")).filter { it.isNotEmpty() }.toSet()) + } + + /** exact 100, one contains the other 70, half the words shared 50, close spelling 40. */ + private fun score(a: Ident, b: Ident): Int { + if (a.norm.isEmpty() || b.norm.isEmpty()) return 0 + if (a.norm == b.norm) return 100 + if (a.norm.contains(b.norm) || b.norm.contains(a.norm)) return 70 + if (a.tokens.isNotEmpty() && b.tokens.isNotEmpty() && + a.tokens.intersect(b.tokens).size.toDouble() / minOf(a.tokens.size, b.tokens.size) >= 0.5) return 50 + return if (1.0 - levenshtein(a.norm, b.norm).toDouble() / maxOf(a.norm.length, b.norm.length) >= 0.85) 40 else 0 + } + + private fun levenshtein(a: String, b: String): Int { + val prev = IntArray(b.length + 1) { it } + val cur = IntArray(b.length + 1) + for (i in 1..a.length) { + cur[0] = i + for (j in 1..b.length) cur[j] = minOf(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + if (a[i - 1] == b[j - 1]) 0 else 1) + System.arraycopy(cur, 0, prev, 0, cur.size) + } + return prev[b.length] + } + + // ------------------------------------------------------------------ export + + private fun stamp() = SimpleDateFormat("yyyy-MM-dd_HHmm", Locale.US).format(Date()) + private fun safe(name: String) = name.replace(Regex("[/\\\\:*?\"<>|]"), "_").trim().ifEmpty { "game" } + + /** + * Zips the game's saves into [dir] as "_.zip" in [layout]. The found save folders when + * there are any, else the whole steamuser profile minus Temp and crash dumps. Returns the zip. + */ + fun export(game: Game, layout: Layout, dir: File): Pair { + val prefix = game.prefix ?: error("${game.game.name} has not been launched yet") + dir.mkdirs() + val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip") + val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out) + if (count == 0) { out.delete(); error("No save files found for ${game.game.name}") } + return out to count + } + + private fun zipProfile(profile: File, roots: List?, layout: Layout, out: File): Int { + if (!profile.isDirectory) return 0 + val scope = roots?.map { File(profile, it) }?.filter { it.exists() } ?: listOf(profile) + var count = 0 + ZipOutputStream(BufferedOutputStream(FileOutputStream(out))).use { zos -> + for (top in scope) top.walkTopDown() + .onEnter { d -> d.relativeTo(profile).path.replace(File.separatorChar, '/').let { !it.equals("AppData/Local/Temp", true) && !it.equals("AppData/Local/CrashDumps", true) } } + .filter { it.isFile } + .forEach { f -> + val rel = f.relativeTo(profile).path.replace(File.separatorChar, '/') + zos.putNextEntry(ZipEntry("${layout.rootPrefix}users/${layout.user}/$rel")) + f.inputStream().use { it.copyTo(zos) } + zos.closeEntry() + count++ + } + } + return count + } + + // ------------------------------------------------------------------ import + + /** + * Unzips a GameHub or Winlator save zip into the game's drive_c, after zipping what its steamuser + * profile holds now into Download/DroidDeck/Saves/backups. Entries outside drive_c, launcher + * shortcuts and anything escaping drive_c are skipped. Returns (files written, backup or null). + */ + fun import(game: Game, zip: File): Pair { + val prefix = game.prefix ?: error("${game.game.name} has not been launched yet") + val driveC = File(prefix, "drive_c") + if (!driveC.isDirectory) error("${game.game.name} has not been launched yet") + if (!looksLikeSaveZip(zip)) error("${zip.name} has no drive_c folder, so it isn't a GameHub or Winlator save zip") + + backupsDir().mkdirs() + val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip") + val backedUp = zipProfile(profile(prefix), null, Layout.GAMEHUB, backup) + if (backedUp == 0) backup.delete() + + val base = driveC.canonicalFile + var written = 0 + ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis -> + var e = zis.nextEntry + while (e != null) { + remap(e.name)?.let { rel -> + val out = File(driveC, rel).canonicalFile + if (out.path.startsWith(base.path + File.separator)) { + if (e.isDirectory) out.mkdirs() + else { + out.parentFile?.mkdirs() + Files.copy(zis, out.toPath(), StandardCopyOption.REPLACE_EXISTING) + written++ + } + } + } + zis.closeEntry() + e = zis.nextEntry + } + } + return written to backup.takeIf { it.exists() } + } + + /** Which layout a zip was written in, from its first user folder; null when it has none. */ + fun layoutOf(zip: File): Layout? = runCatching { + ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis -> + var e = zis.nextEntry + while (e != null) { + val segs = driveCSegments(e.name) + if (segs != null && segs.size >= 2 && segs[0].equals("users", true) && !segs[1].equals("Public", true)) + return@use if (segs[1].equals("xuser", true)) Layout.WINLATOR else Layout.GAMEHUB + e = zis.nextEntry + } + null + } + }.getOrNull() + + private fun looksLikeSaveZip(zip: File): Boolean = runCatching { + ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis -> + var e = zis.nextEntry + while (e != null) { if (driveCSegments(e.name) != null) return@use true; e = zis.nextEntry } + false + } + }.getOrDefault(false) + + /** An entry's path below drive_c, with any user folder but Public renamed to steamuser. */ + private fun remap(raw: String): String? { + val segs = driveCSegments(raw)?.takeIf { it.isNotEmpty() } ?: return null + if (segs.any { it == ".." }) return null + // GameHub also packs its own launcher shortcuts; they are never saves. + if (segs[0].equals("proton_shortcuts", true)) return null + val last = segs.last().lowercase() + if ((last.endsWith(".lnk") || last.endsWith(".desktop") || last.endsWith(".url")) && segs.any { it.equals("Desktop", true) }) return null + if (segs.size >= 2 && segs[0].equals("users", true) && !segs[1].equals("Public", true)) segs[1] = USER + return segs.joinToString("/") + } + + private fun driveCSegments(raw: String): MutableList? { + val segs = raw.replace('\\', '/').trimStart('/').split("/").filter { it.isNotEmpty() && it != "." } + if (segs.isEmpty() || !segs[0].equals("drive_c", true)) return null + return segs.drop(1).toMutableList() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt b/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt new file mode 100644 index 000000000..8e0c7c8a0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.io.File + +/** + * The GPU held at its top clock for a session, without root: KGSL's power-control property turned + * off on /dev/kgsl-3d0, the node the driver already opens (adrenotools' "turbo"). Left to itself the + * governor lets the GPU sit low between bursts, and a frame that lands on a low clock is a hitch; + * Bannerlator measured the clock going from 231 to 1000 MHz with this set. It costs power and heat, + * so it is opt-in, and the kernel's thermal limits still apply on top of it. + * + * The property belongs to the device, not to this process, and a killed app cannot unwind it: it + * is cleared when a session stops, and at the next app start when a marker file says this app set + * it and never cleared it - only then, so another app's own setting is not undone. + * (Bannerlator, PerfGpuTurbo.) + */ +object GpuClockPin { + private const val TAG = "GpuClockPin" + private const val KGSL_NODE = "/dev/kgsl-3d0" + + private const val MARKER = "gpu-clock-pinned" + + @Volatile + private var pinned = false + + private val supported: Boolean by lazy { File(KGSL_NODE).exists() } + + /** At a session's start: pins the clock when the user asked for it. The line is for the log. */ + @Synchronized + fun start(context: Context): String { + if (!SessionPrefs.gpuClockPin(context)) return "gpu clock: governed" + if (!supported) return "gpu clock: no $KGSL_NODE, left governed" + return try { + File(context.filesDir, MARKER).createNewFile() + WaylandCompositor.nativeSetGpuTurbo(true) + pinned = true + "gpu clock: held at its top" + } catch (t: Throwable) { + Log.w(TAG, "pin", t) + "gpu clock: pin failed" + } + } + + /** At a session's end. */ + @Synchronized + fun stop(context: Context) { + if (pinned) clear(context) + } + + /** At the app's start: a process killed with the clock pinned left only the marker behind. */ + @Synchronized + fun clearLeftover(context: Context) { + if (File(context.filesDir, MARKER).exists()) clear(context) + } + + private fun clear(context: Context) { + if (supported) { + try { + WaylandCompositor.nativeSetGpuTurbo(false) + } catch (t: Throwable) { + Log.w(TAG, "clear", t) + } + } + pinned = false + File(context.filesDir, MARKER).delete() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt index 9264a7f6a..9a17a97ae 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt @@ -13,17 +13,28 @@ import java.io.File * 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. */ object OrphanReaper { private const val TAG = "OrphanReaper" + private val kept = java.util.concurrent.ConcurrentHashMap.newKeySet() + + /** Spares [pid] and its descendants until [release]. */ + fun keep(pid: Int) { if (pid > 0) kept.add(pid) } + + fun release(pid: Int) { kept.remove(pid) } fun reap(reason: String): Int { val me = android.os.Process.myPid() val uid = android.os.Process.myUid() + val spared = descendants(kept) var killed = 0 File("/proc").listFiles()?.forEach { entry -> val pid = entry.name.toIntOrNull() ?: return@forEach - if (pid == me || pid <= 1) return@forEach + if (pid == me || pid <= 1 || pid in spared) return@forEach if (uidOf(pid) != uid) return@forEach val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" } try { @@ -38,6 +49,25 @@ object OrphanReaper { return killed } + /** [roots] and every process below them, by each process's parent in /proc//stat. */ + private fun descendants(roots: Set): Set { + if (roots.isEmpty()) return emptySet() + val parent = HashMap() + File("/proc").listFiles()?.forEach { entry -> + val pid = entry.name.toIntOrNull() ?: return@forEach + val stat = try { File(entry, "stat").readText() } catch (e: Exception) { return@forEach } + // "pid (comm) state ppid ...": comm may hold spaces and parentheses; the last ')' ends it. + stat.substringAfterLast(") ").split(' ').getOrNull(1)?.toIntOrNull()?.let { parent[pid] = it } + } + val out = HashSet(roots) + var grew = true + while (grew) { + grew = false + for ((pid, ppid) in parent) if (ppid in out && out.add(pid)) grew = true + } + return out + } + private fun uidOf(pid: Int): Int { return try { File("/proc/$pid/status").useLines { lines -> diff --git a/app/src/main/java/com/droiddeck/launcher/session/PerfHints.kt b/app/src/main/java/com/droiddeck/launcher/session/PerfHints.kt deleted file mode 100644 index da651314e..000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/PerfHints.kt +++ /dev/null @@ -1,87 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.Context -import android.os.Build -import android.os.Handler -import android.os.Looper -import android.os.PerformanceHintManager -import android.util.Log -import androidx.annotation.RequiresApi -import com.droiddeck.launcher.wayland.WaylandCompositor -import java.util.concurrent.Executors - -/** - * ADPF (Android 12+): a PerformanceHintManager session over the compositor thread, told the - * panel's frame period as its target and each presented frame's interval as the actual. When a - * frame runs long the power HAL raises CPU clocks for the next one at once, instead of the - * governor waiting for the load average to climb - the difference between a menu that stutters - * on the first scroll and one that does not. - * - * The session may only carry this process's threads, so the guest (gamescope, the Steam client - * under FEX) cannot join it; they are covered by the app-wide game category and sustained mode. - * Below API 31 nothing here runs; on a power HAL without hint sessions createHintSession returns - * null and the log says so. - */ -object PerfHints { - private const val TAG = "PerfHints" - - @Volatile private var session: PerformanceHintManager.Session? = null - @Volatile private var target = 0L - /** Compositor thread only. */ - private var last = 0L - private val main = Handler(Looper.getMainLooper()) - /** Reports leave the compositor thread: each one is a binder call to the power HAL. */ - private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "adpf-report").apply { isDaemon = true } } - - /** Opens the session once the compositor thread exists (it is started just before this). */ - fun arm(context: Context, refreshHz: Float) { - if (Build.VERSION.SDK_INT < 31) { Log.i(TAG, "adpf: needs Android 12; this is API ${Build.VERSION.SDK_INT}"); return } - val wanted = (1_000_000_000.0 / refreshHz.coerceAtLeast(30f)).toLong() - val s = session - if (s != null) { - if (wanted != target) { target = wanted; try { s.updateTargetWorkDuration(wanted) } catch (t: Throwable) { Log.w(TAG, "adpf: retarget", t) } } - return - } - target = wanted - val app = context.applicationContext - var tries = 0 - main.post(object : Runnable { - override fun run() { - if (session != null) return - val tid = try { WaylandCompositor.nativeCompositorTid() } catch (t: Throwable) { 0 } - if (tid == 0) { - if (++tries < 30) main.postDelayed(this, 100) else Log.w(TAG, "adpf: the compositor thread never reported its tid") - return - } - open(app, tid) - } - }) - } - - @RequiresApi(31) - private fun open(app: Context, tid: Int) { - val pm = app.getSystemService(PerformanceHintManager::class.java) - if (pm == null) { Log.i(TAG, "adpf: no PerformanceHintManager on this device"); return } - val s = try { pm.createHintSession(intArrayOf(tid), target) } catch (t: Throwable) { Log.w(TAG, "adpf: createHintSession", t); null } - if (s == null) { Log.i(TAG, "adpf: unsupported here (the power HAL has no hint sessions)"); return } - last = 0L - session = s - Log.i(TAG, "adpf: session on compositor thread $tid · target ${target / 1000} µs · HAL wants updates every ${pm.preferredUpdateRateNanos / 1000} µs") - } - - /** Compositor thread, once per presented game frame; the interval since the last is the actual. */ - @JvmStatic - fun onFrame() { - val s = session ?: return - val now = System.nanoTime() - val prev = last - last = now - if (prev == 0L) return - val dt = now - prev - // Under half a millisecond is a double present; over half a second is a pause, not a frame. - if (dt < 500_000L || dt > 500_000_000L) return - worker.execute { - try { s.reportActualWorkDuration(dt) } catch (t: Throwable) { Log.w(TAG, "adpf: report failed, session dropped", t); session = null } - } - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt b/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt index b0d49257b..a9b5b0459 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PerfHud.kt @@ -8,7 +8,9 @@ import android.os.SystemClock import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import com.droiddeck.launcher.R import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.wayland.WaylandCompositor import java.io.File import java.util.Locale @@ -86,20 +88,22 @@ class PerfHud(context: Context) { } private fun line(base: Float): String { - val engine = FrameGen.engine(context) - if (engine == FrameGen.ENGINE_OFF) return fps(base) - val name = if (engine == FrameGen.ENGINE_LSFG) "LSFG" else "Win-FG" - val multiplier = FrameGen.multiplier(context) + val mode = FrameGen.mode(context) + if (mode.engine == FrameGen.ENGINE_OFF) return fps(base) + val lsfg = mode.engine == FrameGen.ENGINE_LSFG + val name = if (lsfg) "LSFG" else "Win-FG" + val label = FrameGen.label(context, mode) + if (lsfg && Lossless.cacheFile(context)?.isFile != true) return context.getString(R.string.hud_fg_needs_lossless, name) val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null } val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 } return when { - problem == 1 -> "$name: unsupported" - problem == 2 -> "$name: engine failed" + 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 -> { val source = if (stats[2] > 1f) stats[2] else base - String.format(Locale.US, "%s %d× %.0f → %.0f fps", name, multiplier, source, stats[3]) + String.format(Locale.US, "%s %.0f → %.0f fps", label, source, stats[3]) } - else -> String.format(Locale.US, "%s %d× %s · FG starting", name, multiplier, fps(base)) + else -> context.getString(R.string.hud_fg_starting, label, fps(base)) } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt b/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt index 16d142560..7a44423a0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt @@ -4,7 +4,6 @@ import android.app.Activity import android.app.GameManager import android.app.GameState import android.os.Build -import android.os.PowerManager import android.util.Log /** @@ -13,10 +12,13 @@ import android.util.Log * The manifest already makes the app a game (appCategory + game_mode_config); this is the * per-window half, applied when the session activity is created: * - * - sustained performance mode (Android 7+): a clock floor that does not throttle away after - * two minutes, which suits an hour in Big Picture better than a boost that fades; + * - NOT sustained performance mode: on Pixel and Qualcomm power HALs it caps the CPU and GPU at + * a level the device can hold indefinitely rather than holding a floor, which cost games and + * Big Picture their peak clocks. WinNative never asks for it; the thermal budget is left to + * the game; * - the panel's fastest mode at its current size (Android 6+): a 120 Hz phone is switched to - * 120 Hz for the menu, not only when a game votes for it; + * 120 Hz for the menu, not only when a game votes for it. With a frame cap, the fastest mode + * the cap divides evenly, so every capped frame is shown for the same number of refreshes; * - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases * its boost on loading screens or menus keeps it up. * @@ -26,26 +28,20 @@ import android.util.Log object PerfMode { private const val TAG = "PerfMode" - fun apply(a: Activity): String { - val parts = ArrayList(3) - - // Sustained performance mode. - parts += if (Build.VERSION.SDK_INT >= 24) { - val pm = a.getSystemService(PowerManager::class.java) - if (pm?.isSustainedPerformanceModeSupported == true) { - try { a.window.setSustainedPerformanceMode(true); "sustained mode on" } catch (t: Throwable) { Log.w(TAG, "sustained mode", t); "sustained mode refused" } - } else "sustained mode unsupported" - } else "sustained mode needs Android 7" + fun apply(a: Activity, fpsLimit: Int = 0): String { + val parts = ArrayList(2) // The fastest display mode at the panel's current size. parts += try { val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else { val cur = display.mode - val best = display.supportedModes + val sameSize = display.supportedModes .filter { it.physicalWidth == cur.physicalWidth && it.physicalHeight == cur.physicalHeight } - .maxByOrNull { it.refreshRate } - if (best != null && best.modeId != cur.modeId && best.refreshRate > cur.refreshRate + 0.5f) { + val best = sameSize.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate } + ?: sameSize.maxByOrNull { it.refreshRate } + if (best != null && best.modeId != cur.modeId && + (best.refreshRate > cur.refreshRate + 0.5f || !cadenceFits(cur.refreshRate, fpsLimit))) { a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = best.modeId } "display ${cur.refreshRate.toInt()} → ${best.refreshRate.toInt()} Hz (mode ${best.modeId})" } else "display ${cur.refreshRate.toInt()} Hz" @@ -71,4 +67,11 @@ object PerfMode { return parts.joinToString(" · ") } + + /** A panel rate that shows every capped frame for a whole number of refreshes (no cap: any). */ + fun cadenceFits(hz: Float, fpsLimit: Int): Boolean { + if (fpsLimit <= 0) return true + val ratio = hz / fpsLimit + return ratio >= 0.98f && Math.abs(ratio - Math.round(ratio)) < 0.02f + } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index ede2b4fd5..ed23b57f3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -24,7 +24,9 @@ object SessionFiles { * rename, so a session that still has one mapped keeps the file it opened. */ fun stage(context: Context, root: File) { + GameEnvironmentStore.publish(context) val files = arrayOf( + "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", "usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session", @@ -38,7 +40,15 @@ object SessionFiles { "usr/local/bin/bannerlator-desktop-games" to "usr/local/bin/bannerlator-desktop-games", "usr/local/bin/bannerlator-steam-shim" to "usr/local/bin/bannerlator-steam-shim", "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", + // 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", + "usr/local/bin/bannerlator-flatpak-setup" to "usr/local/bin/bannerlator-flatpak-setup", + "usr/local/bin/bannerlator-flatpak-run" to "usr/local/bin/bannerlator-flatpak-run", + // The user's own AppImages, extracted at import (AppImageManager). + "usr/local/bin/bannerlator-appimage-run" to "usr/local/bin/bannerlator-appimage-run", // The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus // the three under /usr/bin, all no-ops that answer "nothing to do" (see each file). "usr/bin/steamos-update" to "usr/bin/steamos-update", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 13e680c88..9eb8a1d35 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -8,6 +8,8 @@ object SessionPrefs { const val SUSPEND_MANUAL = "manual" const val SUSPEND_NEVER = "never" + const val CONTROLLER_DECK = "deck" + const val CONTROLLER_XBOX360 = "xbox360" const val OSC_AUTO = "auto" const val OSC_ALWAYS = "always" const val OSC_STEAM_QAM = "steam-qam" @@ -28,12 +30,37 @@ object SessionPrefs { prefs(context).edit().putBoolean("launcherFullscreen", on).apply() } - fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true) + /** The Flathub Store (beta): its rail item and the Store's apps on the Desktop page. Off by default. */ + fun storeEnabled(context: Context): Boolean = prefs(context).getBoolean("storeEnabled", false) + + fun setStoreEnabled(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("storeEnabled", on).apply() + } + + /** AppImage import (beta): the AppImages section on the Desktop page. Off by default. */ + fun appImagesEnabled(context: Context): Boolean = prefs(context).getBoolean("appImagesEnabled", false) + + fun setAppImagesEnabled(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("appImagesEnabled", on).apply() + } + + /** + * The session's performance HUD (the fps box). A Deck-mode Steam session with the performance + * overlay has Steam's own (mangoapp, from the QAM), so there the HUD is off unless turned on + * in one - a choice kept apart from every other session's, where it stays on by default. + */ + fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), !mangoappSession(context)) fun setHudEnabled(context: Context, on: Boolean) { - prefs(context).edit().putBoolean("hud", on).apply() + prefs(context).edit().putBoolean(hudKey(context), on).apply() } + private fun hudKey(context: Context) = if (mangoappSession(context)) "hudDeck" else "hud" + + /** A Steam session that runs Deck mode with its performance overlay (mangoapp). */ + private fun mangoappSession(context: Context) = + SessionState.mode == SessionService.MODE_STEAM && steamDeckMode(context) && mangoapp(context) + /** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */ fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false) @@ -85,15 +112,52 @@ object SessionPrefs { } /** - * The imported glibc Turnip a mode draws with inside the runtime, keyed by - * SessionService.MODE_STEAM / MODE_DESKTOP so Steam and the desktop can differ; "" = the - * driver built into the runtime. Resolved by LinuxVulkanDriver at session start. + * The imported glibc Turnip every session draws with inside the runtime - Steam, its games and + * the desktop alike, as they run on the same GPU; "" = the driver built into the runtime. + * Resolved by LinuxVulkanDriver at session start. It was once chosen per mode: the Steam + * session's choice, the one nearly everyone set, carries over. */ - fun linuxDriver(context: Context, mode: String): String = - prefs(context).getString("linuxDriver.$mode", "") ?: "" + fun linuxDriver(context: Context): String = + prefs(context).getString("linuxDriver", null) + ?: prefs(context).getString("linuxDriver.steam", null) + ?: prefs(context).getString("linuxDriver.desktop", "") ?: "" - fun setLinuxDriver(context: Context, mode: String, id: String) { - prefs(context).edit().putString("linuxDriver.$mode", id).apply() + fun setLinuxDriver(context: Context, id: String) { + prefs(context).edit().putString("linuxDriver", id).apply() + } + + const val GPU_DRIVERS_AUTO = "auto" + const val GPU_DRIVERS_MANUAL = "manual" + + /** + * Who picks the GPU drivers: [GPU_DRIVERS_AUTO] (the app, the matched pair recommended for + * this GPU, kept current - DriverPairs) or [GPU_DRIVERS_MANUAL] (the user). Auto for new + * installs; see settleGpuDriverMode. + */ + fun gpuDriverMode(context: Context): String = + prefs(context).getString("gpuDriverMode", GPU_DRIVERS_AUTO) ?: GPU_DRIVERS_AUTO + + fun setGpuDriverMode(context: Context, mode: String) { + prefs(context).edit().putString("gpuDriverMode", mode).apply() + } + + /** + * Auto arrived after people had picked drivers by hand: an install that chose either driver + * keeps its choice (Manual), everyone else is Auto. Decided once, at process start. + */ + fun settleGpuDriverMode(context: Context) { + val p = prefs(context) + if (p.contains("gpuDriverMode")) return + val chosen = androidDriver(context).isNotEmpty() || linuxDriver(context).isNotEmpty() + p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply() + } + + /** Drivers Auto downloaded: the only ones it removes when a newer pair replaces them. */ + fun gpuAutoInstalled(context: Context): Set = + prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty() + + fun setGpuAutoInstalled(context: Context, ids: Set) { + prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply() } /** @@ -143,8 +207,8 @@ object SessionPrefs { prefs(context).edit().putBoolean("directAudio", on).apply() } - /** The microphone for voice chat, on unless turned off; used only once RECORD_AUDIO is granted. */ - fun micEnabled(context: Context): Boolean = prefs(context).getBoolean("mic", true) + /** The microphone for voice chat, off until the user turns it on (which asks for RECORD_AUDIO). */ + fun micEnabled(context: Context): Boolean = prefs(context).getBoolean("mic", false) /** Whether the app has already asked for the microphone once at start-up. */ fun micAsked(context: Context): Boolean = prefs(context).getBoolean("micAsked", false) @@ -188,14 +252,28 @@ object SessionPrefs { * xalia is an x86 Windows program Proton launches to give Windows programs gamepad navigation. * Under FEX it cannot load the session's aarch64 preload shim, so its socket() and memfd calls * reach the vendor's seccomp filter raw; where that answers ENOSYS - a Galaxy Fold, measured - - * it storms, and the session dies seconds after Big Picture appears. + * it storms, and the session dies seconds after Big Picture appears. On by default: where it + * does run, it sits beside every game under FEX for nothing a controller-first session needs + * (about 10% of a core beside Once Upon a KATAMARI on an SD 8 Gen 2). */ - fun noXalia(context: Context): Boolean = prefs(context).getBoolean("noXalia", false) + fun noXalia(context: Context): Boolean = prefs(context).getBoolean("noXalia", true) fun setNoXalia(context: Context, on: Boolean) { prefs(context).edit().putBoolean("noXalia", on).apply() } + /** + * Whether gamescope asks for realtime-priority Vulkan queues (GAMESCOPE_FORCE_VULKAN_REALTIME=1, + * which the app's gamescope build honours without CAP_SYS_NICE). Off by default, as in + * Bannerlator's session: the compositor's queue preempting the game's buys nothing on a device + * whose GPU is waiting on the CPU. + */ + fun gamescopeRealtime(context: Context): Boolean = prefs(context).getBoolean("gamescopeRealtime", false) + + fun setGamescopeRealtime(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("gamescopeRealtime", on).apply() + } + /** * Whether proot runs without its seccomp acceleration (PROOT_NO_SECCOMP=1). * @@ -205,14 +283,42 @@ object SessionPrefs { * plainly exist is the signature - and the fallback is to trace everything instead: slower, * but correct. Max's advice for devices whose kernels "don't work well with it". */ + /** Hold the GPU at its top clock during a session (GpuClockPin). Off by default: power and heat. */ + fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false) + + fun setGpuClockPin(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("gpuClockPin", on).apply() + } + fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false) fun setProotNoSeccomp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("prootNoSeccomp", on).apply() } - /** Turnip's sysmem rendering (TU_DEBUG=sysmem) for the runtime's driver: bypasses GMEM tiling. */ - fun tuSysmem(context: Context): Boolean = prefs(context).getBoolean("tuSysmem", false) + const val DEFAULT_GUEST_HOSTNAME = "DroidDeck" + + @JvmStatic + fun guestHostname(context: Context): String = + validGuestHostname(prefs(context).getString("guestHostname", null)) ?: DEFAULT_GUEST_HOSTNAME + + fun setGuestHostname(context: Context, name: String) { + val valid = validGuestHostname(name) + prefs(context).edit().apply { if (valid == null) remove("guestHostname") else putString("guestHostname", valid) }.apply() + } + + fun validGuestHostname(name: String?): String? { + val trimmed = name?.trim() ?: return null + return trimmed.takeIf { Regex("[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?").matches(it) } + } + + /** + * Turnip's sysmem rendering (TU_DEBUG=sysmem) for the runtime's driver: bypasses GMEM tiling. + * On by default, as WinNative runs every Linux session: Chromium -> ANGLE -> Zink draws the + * client's interface as many small render passes, each paying GMEM's load/store and binning, + * and WinNative's A/B on an Adreno 840 put a game ahead with it too (Palworld 42.8 against 41.3). + */ + fun tuSysmem(context: Context): Boolean = prefs(context).getBoolean("tuSysmem", true) fun setTuSysmem(context: Context, on: Boolean) { prefs(context).edit().putBoolean("tuSysmem", on).apply() @@ -232,11 +338,43 @@ object SessionPrefs { fun noGlError(context: Context): Boolean = prefs(context).getBoolean("noGlError", true) fun setNoGlError(context: Context, on: Boolean) { prefs(context).edit().putBoolean("noGlError", on).apply() } - /** `steam -steamdeck -steamos3`: the client as SteamOS runs it. Expects Deck hardware; untested. */ - fun steamDeckMode(context: Context): Boolean = prefs(context).getBoolean("steamDeckMode", false) + /** + * What the pad is to the Steam client: [CONTROLLER_DECK], a Steam Deck controller (Quick Access + * button, gyro, Steam Input's full treatment - SteamDeckPad), or [CONTROLLER_XBOX360], the plain + * Xbox 360 pad of earlier versions (QAM by the Guide+A chord). + */ + fun steamController(context: Context): String = + prefs(context).getString("steamController", CONTROLLER_DECK) ?: CONTROLLER_DECK + fun setSteamController(context: Context, id: String) { prefs(context).edit().putString("steamController", id).apply() } + + /** Runs the SteamOS gamepad client with its Quick Access performance controls. On for new installs (settleDeckModeDefault). */ + fun steamDeckMode(context: Context): Boolean = prefs(context).getBoolean("steamDeckMode", true) fun setSteamDeckMode(context: Context, on: Boolean) { prefs(context).edit().putBoolean("steamDeckMode", on).apply() } - /** Zink's lazy descriptor mode (ZINK_DESCRIPTORS=lazy) for the client's GL-on-Vulkan UI. On by default. */ + /** + * Deck mode became the default for new installs; an install from before keeps what it ran with + * (off), so an update never changes its interface or restarts the client on its own. Run once at + * process start, before anything reads or writes these prefs: a new install has neither prefs + * nor a runtime yet. The answer is written down, so it is decided once. + */ + fun settleDeckModeDefault(context: Context) { + val p = prefs(context) + if (p.contains("steamDeckMode")) return + val existing = p.all.isNotEmpty() || java.io.File(context.filesDir, "linuxfs").exists() + p.edit().putBoolean("steamDeckMode", !existing).apply() + } + + /** + * Deck mode's performance overlay (mangoapp, beside gamescope): the QAM's Overlay Level draws + * through it. Off is the way out where Valve's mangoapp crashes (one Turnip build did). + */ + fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true) + fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() } + + /** + * Zink's lazy descriptor mode (ZINK_DESCRIPTORS=lazy) with its compact set layout + * (ZINK_DEBUG=compact) for the client's GL-on-Vulkan UI, as WinNative runs it. On by default. + */ fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true) fun setZinkLazy(context: Context, on: Boolean) { @@ -293,21 +431,34 @@ object SessionPrefs { fun resolutionChosen(context: Context, mode: String): Boolean = prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null - /** The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults. */ - fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", "") ?: "" + /** + * The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults. + * Performance + TSO unless chosen, WinNative's default: FEX's own defaults keep half-barrier TSO + * and full-precision x87, which cost every x86 game time; a game that needs them can still be + * given another preset. + */ + fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", DEFAULT_FEX_PRESET) ?: DEFAULT_FEX_PRESET + + private const val DEFAULT_FEX_PRESET = "PERFORMANCE_TSO" fun setFexPreset(context: Context, id: String) { prefs(context).edit().putString("fexPreset", id).apply() + runCatching { GameEnvironmentStore.publish(context) } + .onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) } } - /** The Steam client branch forced on the command line: "publicbeta" (every session so far) or "steamdeck_publicbeta" (Armada's). */ + /** + * The Steam client branch forced on the command line: "publicbeta" (every session so far) or + * "steamdeck_publicbeta" (Armada's). Deck mode always takes the Deck branch, whatever was chosen: + * with -steamos3 the client picks its own branch as SteamOS does, and on publicbeta it settled + * on steamdeck_stable - an older client it then offered as a "Software Update" in every session, + * which applying turns into the exit-42 restart loop (seen on device 2026-09-30). Earlier, Deck + * mode on publicbeta also reinstalled the same client at every start (2026-09-23). On + * steamdeck_publicbeta the client finds no update. The choice applies with Deck mode off. + */ fun steamChannel(context: Context): String = - prefs(context).getString("steamChannel", null) - // Deck mode on the publicbeta channel reinstalls the same client at every start (the - // client reports "installed version 0" against that manifest and exits 42 to apply it, - // losing the launch URL each time); on steamdeck_publicbeta the second launch comes up - // clean. Seen on device 2026-09-23. So Deck mode takes the Deck channel unless chosen. - ?: if (steamDeckMode(context)) "steamdeck_publicbeta" else "publicbeta" + if (steamDeckMode(context)) "steamdeck_publicbeta" + else prefs(context).getString("steamChannel", null) ?: "publicbeta" fun setSteamChannel(context: Context, id: String) { prefs(context).edit().putString("steamChannel", id).apply() @@ -412,6 +563,22 @@ object SessionPrefs { prefs(context).edit().putBoolean("hdr.$mode", on).apply() } + /** + * The session's frame cap, 0 for none. One number used everywhere a frame is paced: gamescope's + * -r (what the client and its games see as the display's rate), the compositor's buffer release + * pacer, the rate the display layer votes for, and the panel mode picked, which is the fastest + * one the cap divides evenly (40 on a 120 Hz panel, not on a 144 Hz one). A 60 fps cap on a + * 144 Hz panel with nothing else changed judders; this is what WinNative's per-shortcut limit + * does. Applies next session. + */ + fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0) + + fun setFpsLimit(context: Context, mode: String, fps: Int) { + prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply() + } + + val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120") + /** * The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a * fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices. @@ -432,7 +599,7 @@ object SessionPrefs { // ── Game storage ──────────────────────────────────────────────────────────────────────── /** - * A second Steam library on this device: the folder bound at /mnt/bannerlator-sd and + * A second Steam library on this device: the folder bound at /mnt/droiddeck-sd and * registered with the client, which then asks where to install every game and shows both * on its Storage page. "" = automatic: the SD card when one is in the phone (the default, * so the choice is made inside the client like anywhere else); GAME_STORAGE_OFF = internal diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 87d690743..4114c627e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -36,6 +36,7 @@ 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.wayland.WaylandCompositor import java.io.File import java.text.SimpleDateFormat import java.util.Date @@ -57,6 +58,8 @@ import java.util.Locale */ class SessionService : Service() { private val components = java.util.concurrent.CopyOnWriteArrayList() + /** The Steam Deck controller's sysfs binds (SteamDeckPad), when this session has one. */ + private var deckBinds: List = emptyList() private val stopLock = Any() private var wakeLock: PowerManager.WakeLock? = null private var wifiLock: WifiManager.WifiLock? = null @@ -267,6 +270,8 @@ class SessionService : Service() { val sessionDir = openSessionFolder() val sessionLog = File(sessionDir, "session.log") + Log.i(TAG, GpuClockPin.start(this)) + val size = SessionState.outputSize val guest = ArrayList() // The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the @@ -285,13 +290,15 @@ class SessionService : Service() { guest.add("DXVK_HDR=1") Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1") } - guest.add("BL_FPS=0") + guest.add("BL_FPS=" + SessionState.fpsLimit) guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz)) guest.add("BL_LOG=" + sessionLog.path) guest.add("BL_DEBUG_DIR=" + sessionDir.path) val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() } val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists() + SessionState.deckPad = false + deckBinds = emptyList() 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 @@ -309,6 +316,8 @@ class SessionService : Service() { val added = com.droiddeck.launcher.frontend.AddedGames.scan(this) val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) guest.add("BL_ADDED_GAMES=" + listing.path) + if (OfflineMode.enabled(this)) guest.add("BL_STEAM_OFFLINE=1") + if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("BL_LOSSLESS_OWNED=1") if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" }) } // Where the guest leaves a request for another session (the desktop's Steam launchers). @@ -430,6 +439,7 @@ class SessionService : Service() { } sessionPid = pid if (pid > 1) { + raiseTracer(pid, gen) SessionEvents.guestStarted(pid) } else { SessionEvents.record("guest.start_failed", mapOf("pid" to pid)) @@ -493,15 +503,12 @@ class SessionService : Service() { guest.add("GALLIUM_DRIVER=zink") guest.add("LIBGL_KOPPER_DRI2=true") LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) } - // An imported glibc Turnip for this mode, when the user chose one: the session script checks - // the manifest and its library from inside and points the loader at it with VK_DRIVER_FILES, - // so the runtime's own driver above stays untouched and is what a bad import falls back to. - // A program from the rail is one of the desktop's emulators, so it draws with the desktop's - // Linux driver, not the Steam session's: the driver's shader cache is keyed on the driver - // build, and with two drivers every emulator compiled its shaders twice - once per way of - // starting it (RPCS3's 6650 interpreter variants on each first boot). - val driverMode = if (SessionState.mode == MODE_RUN) MODE_DESKTOP else SessionPrefs.prefMode(SessionState.mode) - val linuxDriverId = SessionPrefs.linuxDriver(this, driverMode) + // An imported glibc Turnip, when one is set (by the user, or by Auto): the session script + // checks the manifest and its library from inside and points the loader at it with + // VK_DRIVER_FILES, so the runtime's own driver above stays untouched and is what a bad + // import falls back to. One driver for every session: the driver's shader cache is keyed on + // its build, and with one per mode every emulator compiled its shaders twice. + val linuxDriverId = SessionPrefs.linuxDriver(this) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId) ?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) } // Turnip's own debug switches, for the runtime's driver and everything on it. The file in @@ -512,31 +519,36 @@ class SessionService : Service() { // Zink renders the client's UI (Chromium -> ANGLE -> Zink -> Turnip). Lazy descriptors is // the mode Zink recommends where the driver has no descriptor buffer, and what Ludashi ships // by default for its Zink path; a switch here because on one Fold the menus run at 14 fps. - if (SessionPrefs.zinkLazy(this)) guest.add("ZINK_DESCRIPTORS=lazy") + // compact packs Zink's descriptor sets into fewer, so a draw binds less (WinNative's default). + if (SessionPrefs.zinkLazy(this)) { + guest.add("ZINK_DESCRIPTORS=lazy") + guest.add("ZINK_DEBUG=compact") + } // The rest of the client-interface switches (SessionPrefs): GL marshalled off the calling // thread, no GL error checks, and the client run as SteamOS runs it (the script reads // BL_STEAMDECK; it is the one that builds the command line). if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true") if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1") + // Mesa's shader cache as one database instead of a file per entry. Every lookup in the + // file cache is an open and every store an open and a rename, each a proot stop (a rename + // two), for every pipeline DXVK, vkd3d-proton and Zink compile or find; the database is + // opened once and read and written with pread/pwrite, which proot never sees. Mesa removes + // the old folder itself once it has gone a week untouched. + guest.add("MESA_DISK_CACHE_DATABASE=1") 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")) SessionPrefs.writeForceFullscreenFlag(this) } // Proton's own gate for its xalia helper (its `proton` script reads this, and sets - // XALIA_SUPPORTED_ONLY itself otherwise). Off by default: xalia is Valve's, and on a device - // whose seccomp answers its syscalls normally there is no reason to take it away. + // XALIA_SUPPORTED_ONLY itself otherwise). Skipped by default: under FEX it costs every game + // a slice of a core for gamepad navigation the session already has. if (SessionPrefs.noXalia(this)) guest.add("PROTON_USE_XALIA=0") - // The FEXCore preset for the x86 games the client launches: its FEX_* variables go in - // here, before the script, so every game process inherits them from the client. The - // default preset sets nothing, which is what every session ran on before. - if (steamHere) { - val preset = SessionPrefs.fexPreset(this) - val vars = com.droiddeck.launcher.core.FexPreset.env(preset) - vars.forEach { guest.add(it) } - if (vars.isNotEmpty()) Log.i(TAG, "fex preset $preset: ${vars.joinToString(" ")}") - } + // gamescope's realtime Vulkan queues (the session script turns this into + // GAMESCOPE_FORCE_VULKAN_REALTIME); off unless the user turns it on. + guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0")) // Anything else, for a device that cannot be reached with a debugger: Downloads/droiddeck-env // holds KEY=VALUE lines that go into the session's environment as written, after ours, so a // line here wins. Zink and Turnip tunables (ZINK_DESCRIPTORS=lazy, MESA_*), gamescope's, @@ -606,6 +618,12 @@ 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, 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. + fakeInputDir.listFiles()?.forEach { file -> + val node = Regex("event(\\d+)").matchEntire(file.name)?.groupValues?.get(1)?.toIntOrNull() + if (file.name.startsWith(".uinput-") || (node != null && node >= FIRST_VIRTUAL_PAD)) file.delete() + } guest.add("FAKE_EVDEV_DIR=" + fakeInputDir.path) val rings = FakeInputWriter.getRingEnv(fakeInputDir) if (!rings.isNullOrEmpty()) guest.add("FAKE_EVDEV_MEMFD_PATHS=$rings") @@ -613,14 +631,34 @@ class SessionService : Service() { // identity gets the standard layout without the user configuring the pad by hand. guest.add("FAKE_EVDEV_IDENTITY=xbox360") guest.add("FAKE_EVDEV_VIBRATION=1") - // Steam Input's virtual-gamepad identity is for games the client starts, which are - // meant to see that pad. Everywhere else (the desktop, a program from the rail) it - // hides the pad: SDL ignores a Steam virtual gamepad unless it runs under Steam, so - // every SDL emulator came up with no controller. There it is a plain Xbox 360 pad. - if (SessionState.mode == MODE_STEAM) guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1") + val uinput = !File(Environment.getExternalStorageDirectory(), NO_UINPUT_SWITCH).exists() + // In Steam, the pad is what a Deck's is: a Steam Deck controller the client reads over + // hidraw (SteamDeckPad), which only works with Steam Input's virtual pad for games to read. + // Decided only once its sysfs is in place: without it the client would find no Deck, and + // with the Deck asked for the pad's own nodes are withdrawn - no controller at all. + val wantsDeck = uinput && SessionState.mode == MODE_STEAM && + SessionPrefs.steamController(this) == SessionPrefs.CONTROLLER_DECK && + !File(Environment.getExternalStorageDirectory(), NO_DECK_PAD_SWITCH).exists() + 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") + 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") + } 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 + // rail) that identity hides the pad: SDL ignores a Steam virtual gamepad unless it + // runs under Steam, so every SDL emulator came up with no controller. + guest.add("FAKE_EVDEV_STEAM_VIRTUAL=1") + } guest.add("SDL_JOYSTICK_DISABLE_UDEV=1") guest.add("SDL_HIDAPI_JOYSTICK_DISABLE_UDEV=1") - guest.add("SDL_JOYSTICK_HIDAPI=0") + // 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") if (File(Environment.getExternalStorageDirectory(), PAD_LOG_SWITCH).exists()) { guest.add("FAKE_EVDEV_LOG=1") } @@ -631,6 +669,7 @@ class SessionService : Service() { private fun sessionBinds(controllersOn: Boolean, fakeInputDir: File): ArrayList { val binds = ArrayList() if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input") + if (controllersOn) binds.addAll(deckBinds) // The client's battery readout (the Quick Access Menu, the top bar) reads // /sys/class/power_supply/BAT/..., 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 @@ -658,9 +697,12 @@ class SessionService : Service() { if (library != null) { val problem = GameStorage.prepare(library.path) if (problem == null) { + File(LinuxRuntime.rootDir(this), "mnt/droiddeck-sd").mkdirs() + binds.add("${library.path}:/mnt/droiddeck-sd") + // Links, prefixes and Steam entries made before the rename still name the old path. File(LinuxRuntime.rootDir(this), "mnt/bannerlator-sd").mkdirs() binds.add("${library.path}:/mnt/bannerlator-sd") - Log.i(TAG, "game storage: ${library.path} -> /mnt/bannerlator-sd (\"${library.label}\")") + Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\")") } else { Log.w(TAG, "game storage: $problem; internal only this session") } @@ -744,6 +786,24 @@ class SessionService : Service() { return try { Pair(fields[1].toInt(), fields[19].toLong()) } catch (e: NumberFormatException) { null } } + private fun askSteamToExit(prootPid: Int) { + if (!File("/proc/$prootPid").exists()) return + val request = File(LinuxRuntime.sessionRoot(this), "steam-stop") + try { + request.writeText("") + } catch (e: Exception) { + Log.w(TAG, "could not ask the Steam client to exit", e) + return + } + val started = System.currentTimeMillis() + if (waitForExit(prootPid, STEAM_PICKUP_MS) || request.exists()) { + request.delete() + return + } + val exited = waitForExit(prootPid, STEAM_EXIT_MS) + Log.i(TAG, "Steam client ${if (exited) "exited" else "did not exit"} after ${System.currentTimeMillis() - started} ms") + } + private fun waitForExit(pid: Int, timeoutMs: Long): Boolean { val deadline = System.currentTimeMillis() + timeoutMs while (System.currentTimeMillis() < deadline) { @@ -918,6 +978,31 @@ class SessionService : Service() { } } + /** + * proot is one thread, and every syscall it traps anywhere in the session - a path lookup in + * Proton's python, Wine's file opens, the Steam client's /proc scans - waits for that thread to + * be scheduled, at nice 0 beside a game that keeps the big cores busy. It is raised to nice -6, + * under the compositor's -8. After a moment, not at once: the first guest process is forked by + * proot itself and would inherit the value, and with it everything the session starts. + */ + private fun raiseTracer(pid: Int, gen: Int) { + Thread({ + try { + Thread.sleep(2000) + } catch (e: InterruptedException) { + return@Thread + } + if (gen != sessionGen || sessionPid != pid) return@Thread + val nice = try { + WaylandCompositor.nativeRaisePriority(pid, TRACER_NICE) + } catch (t: Throwable) { + Log.w(TAG, "tracer priority", t) + return@Thread + } + Log.i(TAG, "proot tracer $pid: nice $nice (asked for $TRACER_NICE)") + }, "tracer-priority").start() + } + private fun stopSession(status: Int) { synchronized(stopLock) { if (!SessionState.running) return @@ -926,6 +1011,7 @@ class SessionService : Service() { val stoppedGen = sessionGen SessionState.stopRequested = false SessionEvents.record("guest.exited", mapOf("status" to status)) + GpuClockPin.stop(this) SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status)) suspendOperationPending = false launchWatcher?.stopWatching() @@ -961,9 +1047,11 @@ class SessionService : Service() { } components.clear() FakeInputWriter.releaseAllRingSlots() + val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP val finishAfterTeardown: () -> Unit = { if (prootPid > 1 || auxiliary.isNotEmpty()) { Thread({ + if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid) auxiliary.forEach { (pid, started) -> teardown(pid, started) } if (prootPid > 1) teardown(prootPid) killGuestLeftovers() @@ -1100,6 +1188,8 @@ class SessionService : Service() { companion object { private const val TAG = "SessionService" + /** proot's tracer: above everything in the guest, under the compositor thread's -8. */ + private const val TRACER_NICE = -6 /** Downloads file whose contents become TU_DEBUG inside the session, e.g. "sysmem". */ private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug" /** Downloads file of KEY=VALUE lines added to the session environment verbatim. */ @@ -1122,8 +1212,14 @@ class SessionService : Service() { "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. */ + private const val FIRST_VIRTUAL_PAD = 16 const val EXTRA_MODE = "mode" const val MODE_STEAM = "steam" diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 21227ba51..e197a6f8b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -63,6 +63,27 @@ object SessionState { * gets DXVK_HDR=1 and gamescope --hdr-enabled. Decided by the activity before the compositor starts. */ @JvmStatic var hdr = false + /** The pad is presented to the Steam client as a Steam Deck controller this session + * (SteamDeckPad): its Quick Access button is a real button, not the Guide+A chord. Decided by + * the service as the session starts, which can be after the activity has resumed - hence + * [deckPadListener]. */ + @Volatile private var deckPadValue = false + @JvmStatic var deckPad: Boolean + get() = deckPadValue + set(value) { + if (deckPadValue == value) return + deckPadValue = value + deckPadListener?.invoke() + } + + /** Told (on the thread that changed it) whenever [deckPad] changes. */ + @Volatile var deckPadListener: (() -> Unit)? = null + + /** What the second screen shows, and on which display: kept for the session, so a screen + * turned off (sleep, a closed lid) or an activity recreated brings it back as it was. */ + @Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE + @Volatile var secondScreenDisplay = -1 + /** Which session this is: SessionService.MODE_STEAM or MODE_DESKTOP. */ @Volatile var mode = "steam" @@ -74,6 +95,10 @@ object SessionState { @Volatile var refreshHz: Float = 60f + /** The session's frame cap (SessionPrefs.fpsLimit), fixed when it starts; 0 = none. */ + @Volatile + var fpsLimit: Int = 0 + /** The compositor has presented a frame, so the loading panel is behind us for this session. */ @Volatile var firstFrameSeen = false diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamDeckPad.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamDeckPad.kt new file mode 100644 index 000000000..39747df8f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamDeckPad.kt @@ -0,0 +1,105 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.system.Os +import android.util.Log +import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.runtime.LinuxRuntime +import java.io.File + +/** + * The session's pad, described to the Steam client as a Steam Deck controller. + * + * On a Deck - and on the handhelds InputPlumber serves as one - the client finds the controller + * through libudev as a `hidraw` device under a `hid` device under a USB interface and reads it + * itself. libfakeinput serves the device node (`/dev/hidraw16`, built from the pad's input ring); + * what the client also needs is the sysfs it walks to find and identify that node, which a sandbox + * shows nothing of. This writes that sysfs as the kernel lays out a Deck's controller interface and + * returns the binds that put it in place: + * + * - `/sys/devices/droiddeck/usb1` - the USB device (Valve, 28de:1205), its interface 2, the HID + * device on it (`HID_ID`, `report_descriptor`) and that device's `hidraw/hidraw16`; + * - `/sys/class/hidraw/hidraw16` - what an enumeration of the `hidraw` subsystem lists; + * - `/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. + * + * Symlinks are absolute guest paths; proot resolves them inside the session. + */ +object SteamDeckPad { + private const val TAG = "SessionService" + /** Must match libfakeinput (fakeinput_steam.cpp: DECK_HIDRAW_*). */ + private const val MAJOR = 240 + private const val MINOR = 16 + private const val NODE = "hidraw$MINOR" + private const val GUEST_DEVICES = "/sys/devices/droiddeck" + private const val USB = "$GUEST_DEVICES/usb1" + private const val INTERFACE = "$USB/1-1:1.2" + private const val HID = "$INTERFACE/0003:28DE:1205.0001" + private const val HIDRAW = "$HID/hidraw/$NODE" + private const val SERIAL = "DROIDDECK0001" + + /** InputPlumber's CONTROLLER_DESCRIPTOR, as libfakeinput answers HIDIOCGRDESC. */ + private val REPORT_DESCRIPTOR = intArrayOf( + 0x06, 0xff, 0xff, 0x09, 0x01, 0xa1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, + 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x06, 0x09, 0x07, + 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0, + ).map { it.toByte() }.toByteArray() + + /** 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 { + val base = File(sessionRoot, "sys/deck") + val devices = File(base, "devices") + val hidrawClass = File(base, "class-hidraw") + return try { + FileUtils.clear(base) + fun dir(guest: String) = File(devices, guest.removePrefix("$GUEST_DEVICES/")).apply { mkdirs() } + fun write(guest: String, name: String, text: String) = File(dir(guest), name).writeText(text) + fun link(file: File, target: String) { + file.parentFile?.mkdirs() + file.delete() + Os.symlink(target, file.path) + } + + write(USB, "uevent", "DEVTYPE=usb_device\nPRODUCT=28de/1205/100\nTYPE=0/0/0\nBUSNUM=001\nDEVNUM=002\n") + write(USB, "idVendor", "28de\n") + write(USB, "idProduct", "1205\n") + write(USB, "bcdDevice", "0100\n") + write(USB, "manufacturer", "Valve Software\n") + write(USB, "product", "Steam Deck Controller\n") + write(USB, "serial", "$SERIAL\n") + link(File(dir(USB), "subsystem"), "/sys/bus/usb") + + write(INTERFACE, "uevent", "DEVTYPE=usb_interface\nPRODUCT=28de/1205/100\nINTERFACE=3/0/0\n") + write(INTERFACE, "bInterfaceNumber", "02\n") + write(INTERFACE, "bInterfaceClass", "03\n") + link(File(dir(INTERFACE), "subsystem"), "/sys/bus/usb") + + write(HID, "uevent", "DRIVER=hid-steam\nHID_ID=0003:000028DE:00001205\n" + + "HID_NAME=Valve Software Steam Deck Controller\nHID_PHYS=usb-droiddeck-1/input2\n" + + "HID_UNIQ=$SERIAL\nMODALIAS=hid:b0003g0001v000028DEp00001205\n") + File(dir(HID), "report_descriptor").writeBytes(REPORT_DESCRIPTOR) + link(File(dir(HID), "subsystem"), "/sys/bus/hid") + + write(HIDRAW, "uevent", "MAJOR=$MAJOR\nMINOR=$MINOR\nDEVNAME=$NODE\n") + write(HIDRAW, "dev", "$MAJOR:$MINOR\n") + link(File(dir(HIDRAW), "subsystem"), "/sys/class/hidraw") + link(File(dir(HIDRAW), "device"), HID) + + hidrawClass.mkdirs() + link(File(hidrawClass, NODE), HIDRAW) + // The runtime binds this directory over /sys/dev/char for the GPU (LinuxRuntime.bindGpuNode). + link(File(context.cacheDir, "drm/sys/$MAJOR:$MINOR"), HIDRAW) + + val udevData = File(LinuxRuntime.rootDir(context), "run/udev/data").apply { mkdirs() } + File(udevData, "c$MAJOR:$MINOR").writeText("I:1\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\n") + + Log.i(TAG, "deck pad: /dev/$NODE described as a Steam Deck controller (28de:1205)") + listOf(devices.path + ":" + GUEST_DEVICES, hidrawClass.path + ":/sys/class/hidraw") + } catch (e: Exception) { + Log.w(TAG, "deck pad: could not describe the pad as a Deck controller: $e") + emptyList() + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/store/AppImageState.kt b/app/src/main/java/com/droiddeck/launcher/store/AppImageState.kt new file mode 100644 index 000000000..91a7ac58c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/store/AppImageState.kt @@ -0,0 +1,63 @@ +package com.droiddeck.launcher.store + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.widget.Toast +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.runtime.AppImageManager +import java.io.File + +/** The imported AppImages and the import in progress, for the Desktop page. */ +object AppImageState { + private val main = Handler(Looper.getMainLooper()) + + var items by mutableStateOf>(emptyList()) + private set + /** The file being imported and what the import is doing; null when idle. */ + var importing by mutableStateOf(null) + private set + var stage by mutableStateOf(null) + private set + /** Why the last import was refused, shown on the page until the next one. */ + var lastError by mutableStateOf(null) + private set + + fun refresh(context: Context) { + val app = context.applicationContext + Thread({ + val list = AppImageManager.list(app) + main.post { items = list } + }, "appimage-refresh").start() + } + + fun import(context: Context, file: File) { + if (importing != null) return + val app = context.applicationContext + importing = file.name; stage = "Starting…"; lastError = null + Thread({ + val problem = try { + AppImageManager.import(app, file) { s -> main.post { stage = s } } + } catch (e: Exception) { + e.message ?: e.toString() + } + val list = AppImageManager.list(app) + main.post { + importing = null; stage = null; items = list + lastError = problem?.let { "${file.name}: $it" } + if (problem == null) Toast.makeText(app, "${file.name} imported", Toast.LENGTH_SHORT).show() + } + }, "appimage-import").start() + } + + fun remove(context: Context, id: String) { + val app = context.applicationContext + Thread({ + AppImageManager.remove(app, id) + val list = AppImageManager.list(app) + main.post { items = list } + }, "appimage-remove").start() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/store/FlathubApi.kt b/app/src/main/java/com/droiddeck/launcher/store/FlathubApi.kt new file mode 100644 index 000000000..536e2aa9e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/store/FlathubApi.kt @@ -0,0 +1,158 @@ +package com.droiddeck.launcher.store + +import android.util.Log +import org.json.JSONArray +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder + +/** + * Flathub's public API (flathub.org/api/v2): the collections its front page shows, search, and an + * app's AppStream data. Only what this device can install is kept - apps built for aarch64. + */ +object FlathubApi { + private const val TAG = "FlathubApi" + private const val BASE = "https://flathub.org/api/v2" + private const val ARCH = "aarch64" + private const val TIMEOUT_MS = 20_000 + + class AppSummary( + val id: String, val name: String, val summary: String, val icon: String?, + val developer: String?, val verified: Boolean, val installs: Int, + ) + + class Screenshot(val thumb: String, val full: String) + + class AppDetails( + val id: String, val name: String, val summary: String, val description: String, + val developer: String?, val icon: String?, val version: String?, val license: String?, + val homepage: String?, val screenshots: List, val categories: List, + val runtime: String?, val downloadSize: Long, val installedSize: Long, val arches: List, + ) + + /** A category as Flathub's search filters it, with the name shown for it. */ + class Category(val id: String, val label: String) + + val categories = listOf( + Category("Game", "Games"), Category("AudioVideo", "Audio & Video"), Category("Graphics", "Graphics"), + Category("Network", "Internet"), Category("Office", "Office"), Category("Development", "Developer"), + Category("Education", "Education"), Category("Science", "Science"), Category("System", "System"), + Category("Utility", "Utilities"), + ) + + /** Front-page collections: popular, trending, recently-updated, recently-added. */ + fun collection(name: String, count: Int = 30): List? { + // The collections are not filtered by architecture; ask for more and keep what fits. + val body = get("$BASE/collection/$name?page=1&per_page=${count * 2}") ?: return null + return hits(body)?.take(count) + } + + /** Search, optionally within one category (Flathub's main_categories facet). */ + fun search(query: String, category: String? = null, count: Int = 48): List? { + val filters = JSONArray().put(JSONObject().put("filterType", "arches").put("value", ARCH)) + if (category != null) filters.put(JSONObject().put("filterType", "main_categories").put("value", category)) + val payload = JSONObject().put("query", query).put("filters", filters) + .put("hits_per_page", count).put("page", 1) + val body = post("$BASE/search", payload.toString()) ?: return null + return hits(body) + } + + /** Flathub's own copy of an app's icon: for apps that export only an SVG, which is not drawn here. */ + fun iconUrl(id: String) = "https://dl.flathub.org/media/icons/128x128/$id.png" + + fun details(id: String): AppDetails? { + val app = get("$BASE/appstream/${enc(id)}")?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return null + val summary = get("$BASE/summary/${enc(id)}?arch=$ARCH")?.let { runCatching { JSONObject(it) }.getOrNull() } + val shots = app.optJSONArray("screenshots")?.let { arr -> + (0 until arr.length()).mapNotNull { i -> + val sizes = arr.optJSONObject(i)?.optJSONArray("sizes") ?: return@mapNotNull null + val all = (0 until sizes.length()).mapNotNull { sizes.optJSONObject(it) } + .map { (it.optString("width").toIntOrNull() ?: 0) to it.optString("src") } + .filter { it.second.startsWith("http") }.sortedBy { it.first } + if (all.isEmpty()) null + else Screenshot(all.firstOrNull { it.first >= 600 }?.second ?: all.last().second, + all.firstOrNull { it.first >= 1200 }?.second ?: all.last().second) + } + } ?: emptyList() + val release = app.optJSONArray("releases")?.optJSONObject(0) + val cats = app.optJSONArray("categories")?.let { a -> (0 until a.length()).map { a.optString(it) } } ?: emptyList() + val arches = summary?.optJSONArray("arches")?.let { a -> (0 until a.length()).map { a.optString(it) } } ?: emptyList() + return AppDetails( + id = app.optString("id", id), + name = app.optString("name", id), + summary = app.optString("summary"), + description = plainText(app.optString("description")), + developer = app.optString("developer_name").takeIf { it.isNotEmpty() && it != "null" }, + icon = app.optString("icon").takeIf { it.startsWith("http") }, + version = release?.optString("version")?.takeIf { it.isNotEmpty() && it != "null" }, + license = app.optString("project_license").takeIf { it.isNotEmpty() && it != "null" }, + homepage = app.optJSONObject("urls")?.optString("homepage")?.takeIf { it.startsWith("http") }, + screenshots = shots, + categories = cats, + runtime = summary?.optJSONObject("metadata")?.optString("runtime")?.takeIf { it.isNotEmpty() }, + downloadSize = summary?.optLong("download_size") ?: 0L, + installedSize = summary?.optLong("installed_size") ?: 0L, + arches = arches, + ) + } + + private fun hits(body: String): List? = try { + val arr = JSONObject(body).getJSONArray("hits") + (0 until arr.length()).mapNotNull { i -> + val o = arr.getJSONObject(i) + val arches = o.optJSONArray("arches") + if (arches != null && (0 until arches.length()).none { arches.optString(it) == ARCH }) return@mapNotNull null + if (o.optString("type", "desktop-application") != "desktop-application") return@mapNotNull null + AppSummary( + id = o.optString("app_id"), + name = o.optString("name"), + summary = o.optString("summary"), + icon = o.optString("icon").takeIf { it.startsWith("http") }, + developer = o.optString("developer_name").takeIf { it.isNotEmpty() && it != "null" }, + verified = o.optBoolean("verification_verified"), + installs = o.optInt("installs_last_month"), + ) + }.filter { it.id.isNotEmpty() } + } catch (e: Exception) { + Log.w(TAG, "hits: $e"); null + } + + /** AppStream descriptions are a small HTML subset: paragraphs and lists become lines. */ + internal fun plainText(html: String): String = html + .replace(Regex("(?i)

  • \\s*"), "• ") + .replace(Regex("(?i)"), "\n") + .replace(Regex("<[^>]+>"), "") + .replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'") + .lines().map { it.trim().replace(Regex("\\s+"), " ") } + .joinToString("\n").replace(Regex("\n{3,}"), "\n\n").trim() + + private fun enc(s: String) = URLEncoder.encode(s, "UTF-8") + + private fun get(url: String): String? = request(url, null) + + private fun post(url: String, json: String): String? = request(url, json) + + private fun request(url: String, json: 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 (json != null) { + requestMethod = "POST" + doOutput = true + setRequestProperty("Content-Type", "application/json") + outputStream.use { it.write(json.toByteArray()) } + } + } + if (c.responseCode / 100 != 2) { Log.w(TAG, "$url -> HTTP ${c.responseCode}"); null } + else c.inputStream.bufferedReader().use { it.readText() } + } catch (e: Exception) { + Log.w(TAG, "$url: $e"); null + } finally { + c?.disconnect() + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/store/StoreState.kt b/app/src/main/java/com/droiddeck/launcher/store/StoreState.kt new file mode 100644 index 000000000..1564194df --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/store/StoreState.kt @@ -0,0 +1,142 @@ +package com.droiddeck.launcher.store + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.widget.Toast +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.runtime.FlatpakManager + +/** + * The store's state for the life of the process, so an install carries on - and its progress + * shows - while the user moves around the launcher or plays something meanwhile. + */ +object StoreState { + private val main = Handler(Looper.getMainLooper()) + + var ready by mutableStateOf(false) + private set + var installed by mutableStateOf>(emptyList()) + private set + var updates by mutableStateOf>(emptySet()) + private set + var checkingUpdates by mutableStateOf(false) + private set + /** Flathub has been asked this session, so an empty [updates] means up to date. */ + var updatesChecked by mutableStateOf(false) + private set + /** What is running: "setup", an app id, or "update-all"; null when idle. */ + var busy by mutableStateOf(null) + private set + var stage by mutableStateOf(null) + private set + var percent by mutableStateOf(-1) + private set + + /** The front page's sections, by collection name; absent until loaded, empty list on failure. */ + val sections = mutableStateMapOf>() + var sectionsFailed by mutableStateOf(false) + private set + val details = mutableStateMapOf() + val detailsFailed = mutableStateMapOf() + + var searchResults by mutableStateOf?>(null) + private set + var searching by mutableStateOf(false) + private set + private var searchSeq = 0 + + val SECTIONS = listOf("popular" to "Popular", "trending" to "Trending", "recently-added" to "New", "recently-updated" to "Updated") + + fun refresh(context: Context) { + val app = context.applicationContext + Thread({ + val r = FlatpakManager.ready(app) + val list = if (r) FlatpakManager.installedApps(app) else emptyList() + main.post { ready = r; installed = list; updates = updates.filter { id -> list.any { it.id == id } }.toSet() } + }, "store-refresh").start() + } + + fun loadSections(force: Boolean = false) { + if (!force && sections.isNotEmpty()) return + sectionsFailed = false + Thread({ + var failed = false + for ((key, _) in SECTIONS) { + val apps = FlathubApi.collection(key, 18) + if (apps == null) failed = true + main.post { sections[key] = apps ?: emptyList() } + } + main.post { sectionsFailed = failed } + }, "store-sections").start() + } + + fun loadDetails(id: String) { + if (details.containsKey(id)) return + detailsFailed.remove(id) + Thread({ + val d = FlathubApi.details(id) + main.post { if (d != null) details[id] = d else detailsFailed[id] = true } + }, "store-details").start() + } + + fun search(query: String, category: String?) { + val seq = ++searchSeq + searching = true + Thread({ + val r = FlathubApi.search(query, category) + main.post { if (seq == searchSeq) { searchResults = r ?: emptyList(); searching = false } } + }, "store-search").start() + } + + fun clearSearch() { searchSeq++; searchResults = null; searching = false } + + private fun run(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 = FlatpakManager.ready(app) + val list = if (r) FlatpakManager.installedApps(app) else emptyList() + main.post { + busy = null; stage = null; percent = -1 + ready = r; installed = list + if (problem != null) Toast.makeText(app, "$label: $problem", Toast.LENGTH_LONG).show() + } + }, "store-$what").start() + } + + fun setup(context: Context) = run(context, "setup", "Flatpak setup") { c, p -> FlatpakManager.setup(c, p) } + + fun install(context: Context, id: String, name: String) = + run(context, id, name) { c, p -> FlatpakManager.install(c, id, p) } + + fun uninstall(context: Context, id: String, name: String) = + run(context, id, name) { c, p -> FlatpakManager.uninstall(c, id, p).also { if (it == null) main.post { updates = updates - id } } } + + fun update(context: Context, id: String?, name: String) = + run(context, id ?: "update-all", name) { c, p -> + FlatpakManager.update(c, id, p).also { if (it == null) main.post { updates = if (id == null) emptySet() else updates - id } } + } + + fun checkUpdates(context: Context) { + if (checkingUpdates || busy != null) return + val app = context.applicationContext + checkingUpdates = true + Thread({ + val u = FlatpakManager.updates(app) + main.post { + checkingUpdates = false + if (u != null) { updates = u; updatesChecked = true } else Toast.makeText(app, "Could not check Flathub for updates", Toast.LENGTH_SHORT).show() + } + }, "store-updates").start() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index 7822ef44e..67fc47be7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -102,6 +102,9 @@ fun ComponentsPage( onImport: () -> Unit, onBack: () -> Unit, requestInitialFocus: Boolean = true, + /** The GPU drivers tab ([GPU_TAB]): what it shows and does. */ + gpu: GpuDriversState = GpuDriversState(), + gpuActions: GpuDriversActions = GpuDriversActions(), ) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -112,23 +115,55 @@ fun ComponentsPage( var about by remember { mutableStateOf(false) } var protonMenu by remember { mutableStateOf(false) } fun ask(title: String, body: String, action: () -> Unit) { confirmTitle = title; confirm = body to action } + // The GPU drivers tab's Advanced pages: one driver list on its own, full page. + var driverPage by remember { mutableStateOf(null) } + val gpuTab = comp == GPU_TAB + when (driverPage) { + "rt" -> { + DriverPage( + title = "Runtime driver", hint = "Steam, its games and the desktop draw with it. Applies next session.", + rows = gpu.linuxRows, selected = gpu.linuxSelected, downloads = gpu.linuxDownloads, + status = gpu.releaseStatus, checking = gpu.checking, importLabel = "Import Turnip zip…", canRestore = false, + onSelect = gpuActions.onSelectLinux, onDelete = gpuActions.onRemoveLinux, onRefresh = gpuActions.onRefresh, + onDownload = gpuActions.onDownloadDriver, onImport = gpuActions.onImportLinux, onRestore = {}, onBack = { driverPage = null }, + ) + return + } + "panel" -> { + DriverPage( + title = "Display driver", hint = "Puts frames on the screen in both modes. Restart the app to apply.", + rows = gpu.androidRows, selected = gpu.androidSelected, downloads = gpu.androidDownloads, + status = gpu.releaseStatus, checking = gpu.checking, importLabel = "Import an AdrenoTools zip…", + canRestore = gpu.canRestoreBundled, + onSelect = gpuActions.onSelectAndroid, onDelete = gpuActions.onRemoveAndroid, onRefresh = gpuActions.onRefresh, + onDownload = gpuActions.onDownloadDriver, onImport = gpuActions.onImportAndroid, onRestore = gpuActions.onRestoreBundled, + onBack = { driverPage = null }, + ) + return + } + } val views = snapshot?.protons ?: emptyList() val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull() val label = ComponentsManager.LABEL[comp] ?: comp val checked = if (catalogAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(catalogAt * 1000)) else "never" - val nightlies = if (busy != null) "$busy…" else "Nightlies checked $checked" + val nightlies = if (gpuTab) gpu.releaseStatus else if (busy != null) "$busy…" else "Nightlies checked $checked" Column(Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) { // ---- title, and the one thing that goes online ----------------------------------------- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) { Text( "Components", fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, - maxLines = 1, modifier = Modifier.weight(1f), + maxLines = 1, ) - if (!narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) - ToolIcon(Icons.Outlined.Info, "About Components") { about = true } - ToolIcon(Icons.Outlined.Refresh, "Check the Nightlies for new packages", busy = checking, enabled = !checking, onClick = onRefresh) + // The status gives way to the title, not the other way round. + if (!narrow) Text( + nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + textAlign = androidx.compose.ui.text.style.TextAlign.End, modifier = Modifier.weight(1f), + ) else Spacer(Modifier.weight(1f)) + if (!gpuTab) ToolIcon(Icons.Outlined.Info, "About Components") { about = true } + if (gpuTab) ToolIcon(Icons.Outlined.Refresh, "Check for new drivers", busy = gpu.checking, enabled = !gpu.checking && gpu.busy == null, onClick = gpuActions.onRefresh) + else ToolIcon(Icons.Outlined.Refresh, "Check the Nightlies for new packages", busy = checking, enabled = !checking, onClick = onRefresh) } if (narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) @@ -138,7 +173,7 @@ fun ComponentsPage( horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = 12.dp), ) { - if (view != null) Box { + if (view != null && !gpuTab) Box { ValueChip(view.proton.name, protonMenu, modifier = Modifier.widthIn(max = 300.dp).heightIn(min = 44.dp)) { protonMenu = !protonMenu } AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = "Proton", note = "Valve's own Proton is replaced when Steam updates it; its originals are kept per build.") { first -> @@ -152,11 +187,12 @@ fun ComponentsPage( } } } - TabStrip(comps.map { ComponentsManager.LABEL.getValue(it) }, comps.indexOf(comp).coerceAtLeast(0), { onComp(comps[it]) }) + val tabs = listOf(GPU_TAB) + comps + TabStrip(tabs.map { ComponentsManager.LABEL[it] ?: "GPU drivers" }, tabs.indexOf(comp).coerceAtLeast(0), { onComp(tabs[it]) }) } // ---- what is in use ----------------------------------------------------------------------- - if (view != null) { + if (view != null && !gpuTab) { val st = view.components.getValue(comp) val fixedAt = if (view.reappliedAt > 0) " · re-applied at launch " + DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(view.reappliedAt * 1000)) else "" Row( @@ -179,6 +215,12 @@ fun ComponentsPage( // ---- the lists ------------------------------------------------------------------------------ when { + gpuTab -> Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + GpuDriversPanel(gpu, gpuActions) { driverPage = it } + Row(modifier = Modifier.padding(top = 14.dp)) { + SmallButton("Import .zip", onClick = gpuActions.onImportZip) + } + } snapshot == null -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp)) { CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp)) Spacer(Modifier.width(12.dp)) @@ -295,7 +337,7 @@ fun ComponentsPage( } @Composable -private fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) { +internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val src = remember { MutableInteractionSource() } @@ -304,7 +346,7 @@ private fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = fal contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).clip(RoundedCornerShape(12.dp)) .background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) - .border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line2, RoundedCornerShape(12.dp)) + .glideBorder(hot, RoundedCornerShape(12.dp), pal.signal, pal.line2) .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick), ) { @@ -327,7 +369,7 @@ private fun SmallButton(text: String, enabled: Boolean = true, accent: Boolean = contentAlignment = Alignment.Center, modifier = modifier.heightIn(min = 44.dp).clip(RoundedCornerShape(10.dp)) .background(if (hot) pal.signal else colors.surfaceVariant) - .border(2.dp, if (hot) colors.onBackground else pal.line2, RoundedCornerShape(10.dp)) + .glideBorder(hot, RoundedCornerShape(10.dp), colors.onBackground, pal.line2, restWidth = 2.dp) .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 14.dp, vertical = 8.dp), @@ -369,7 +411,7 @@ private fun InstalledLine(item: InstalledItem, modifier: Modifier = Modifier, on Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.weight(1f).heightIn(min = 56.dp).then(modifier) - .border(2.dp, if (hot) pal.signal else Color.Transparent, ROW_SHAPE) + .glideBorder(hot, ROW_SHAPE, pal.signal) .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onSelect) .controllerConfirm(onClick = onSelect) .padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp), @@ -398,7 +440,7 @@ private fun InstalledLine(item: InstalledItem, modifier: Modifier = Modifier, on contentAlignment = Alignment.Center, modifier = Modifier.padding(end = 6.dp).size(40.dp).clip(ROW_SHAPE) .background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent) - .border(2.dp, if (delHot) colors.error else Color.Transparent, ROW_SHAPE) + .glideBorder(delHot, ROW_SHAPE, colors.error) .hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete) .controllerConfirm(onClick = onDelete), ) { Icon(Icons.Outlined.Delete, contentDescription = "Delete ${item.name}", tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) } @@ -432,3 +474,6 @@ private fun AvailableLine(d: CatalogItem, progress: Int?, enabled: Boolean, onDo } Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) } + +/** The Components page's tab for the GPU drivers, before the Proton components' own. */ +const val GPU_TAB = "gpu" diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ControllerSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/ControllerSettings.kt index bbbb78892..ee5ffd4df 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ControllerSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ControllerSettings.kt @@ -59,7 +59,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre ChoiceRow(host, "controller-opacity", "Opacity", null, ControllerPrefs.opacities.map { it to "$it%" }, c.opacity, onPick = a.onOpacity) ChoiceRow(host, "controller-size", "Button size", "100% keeps the standard size", ControllerPrefs.sizes.map { it to "$it%" }, c.size, onPick = a.onSize) ToggleRow(host, "controller-stick-click", "Stick click", "Double-tap a stick and hold for L3 or R3", c.stickClick, onChange = a.onStickClick) - ToggleRow(host, "controller-adaptive", "Adaptive sticks", "A stick centers where your thumb lands and returns home when you let go", c.adaptiveSticks, onChange = a.onAdaptiveSticks) + ToggleRow(host, "controller-adaptive", "Adaptive sticks", "Sticks appear when touched near their saved positions and hide when released", c.adaptiveSticks, onChange = a.onAdaptiveSticks) SettingsRow("Layout", if (c.customLayout) "Custom positions saved" else "Placed for this screen's size and your grip") { Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { SecondaryButton("Edit") { a.onEditLayout() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt new file mode 100644 index 000000000..e1bce8375 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt @@ -0,0 +1,351 @@ +package com.droiddeck.launcher.ui + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.RadialGradient +import android.graphics.RectF +import android.graphics.Shader +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.view.Gravity +import android.view.HapticFeedbackConstants +import android.view.MotionEvent +import android.view.View +import android.widget.FrameLayout +import android.widget.LinearLayout +import android.widget.TextView +import com.droiddeck.launcher.input.DeckControls +import kotlin.math.min + +/** + * The Steam Deck controller's back grips and trackpads, on the second screen. + * + * Four tabs: the grips as a 2x2 grid (left grips on the left, upper above lower, as they sit on a + * Deck); either trackpad on its own with a bar to click it; and both trackpads with the grips in a + * row beneath. A trackpad clicks from its bar or from a second finger while the first is down. + * Drawn for OLED: true black, with outlines rather than filled surfaces, and the Steam blue only + * where something is being touched. + */ +@SuppressLint("ViewConstructor") +class DeckControlsPanel( + context: Context, + private val onClose: () -> Unit, + private val onSteamMenu: () -> Unit, + private val onQam: () -> Unit, +) : LinearLayout(context) { + private enum class Tab(val label: String) { GRIPS("Grips"), LEFT("Left pad"), RIGHT("Right pad"), BOTH("Both") } + + private val content = FrameLayout(context) + private val tabViews = HashMap() + + init { + orientation = VERTICAL + setBackgroundColor(Color.BLACK) + addView(topBar(), LayoutParams(LayoutParams.MATCH_PARENT, dp(64))) + addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f)) + select(selected) + } + + override fun onDetachedFromWindow() { + DeckControls.releaseAll() + super.onDetachedFromWindow() + } + + private fun topBar(): View = LinearLayout(context).apply { + orientation = HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(dp(12), dp(10), dp(12), dp(6)) + addView(roundButton("×", "Close second-screen controls", onClose)) + val tabs = LinearLayout(context).apply { + orientation = HORIZONTAL + background = outline(CORNER_PILL, SURFACE) + setPadding(dp(4), dp(4), dp(4), dp(4)) + for (tab in Tab.values()) { + val view = TextView(context).apply { + text = tab.label + textSize = 14f + typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) + gravity = Gravity.CENTER + isSingleLine = true + setPadding(dp(14), 0, dp(14), 0) + setOnClickListener { select(tab) } + } + tabViews[tab] = view + addView(view, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)) + } + } + val centre = FrameLayout(context).apply { + addView(tabs, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, dp(44), Gravity.CENTER)) + } + addView(centre, LayoutParams(0, LayoutParams.MATCH_PARENT, 1f)) + addView(roundButton("STEAM", "Open Steam menu", onSteamMenu, wide = true)) + addView(space(dp(8))) + addView(roundButton("•••", "Open Quick Access Menu", onQam, wide = true)) + } + + private fun select(tab: Tab) { + selected = tab + DeckControls.releaseAll() + for ((each, view) in tabViews) { + val on = each == tab + view.background = if (on) filled(CORNER_PILL, ACCENT) else null + view.setTextColor(if (on) ON_ACCENT else TEXT_DIM) + } + content.removeAllViews() + content.addView( + when (tab) { + Tab.GRIPS -> gripsGrid() + Tab.LEFT -> singlePad(right = false) + Tab.RIGHT -> singlePad(right = true) + Tab.BOTH -> bothPads() + }, + FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT), + ) + } + + private fun gripsGrid(): View = LinearLayout(context).apply { + orientation = HORIZONTAL + setPadding(dp(12), dp(6), dp(12), dp(12)) + fun column(upper: View, lower: View) = LinearLayout(context).apply { + orientation = VERTICAL + addView(upper, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { bottomMargin = dp(6) }) + addView(lower, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { topMargin = dp(6) }) + } + addView(column(GripButton(context, "L4", "Left · upper", DeckControls.L4), GripButton(context, "L5", "Left · lower", DeckControls.L5)), + LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { rightMargin = dp(6) }) + addView(column(GripButton(context, "R4", "Right · upper", DeckControls.R4), GripButton(context, "R5", "Right · lower", DeckControls.R5)), + LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { leftMargin = dp(6) }) + } + + private fun singlePad(right: Boolean): View = LinearLayout(context).apply { + orientation = VERTICAL + setPadding(dp(12), dp(6), dp(12), dp(12)) + addView(TrackpadView(context, right), LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { bottomMargin = dp(12) }) + addView(ClickBar(context, right), LayoutParams(LayoutParams.MATCH_PARENT, dp(76))) + } + + private fun bothPads(): View = LinearLayout(context).apply { + orientation = VERTICAL + setPadding(dp(12), dp(6), dp(12), dp(12)) + val pads = LinearLayout(context).apply { + orientation = HORIZONTAL + addView(TrackpadView(context, right = false), LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { rightMargin = dp(6) }) + addView(TrackpadView(context, right = true), LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { leftMargin = dp(6) }) + } + addView(pads, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f).apply { bottomMargin = dp(12) }) + // Mirrored, as hands hold them: the upper grips outside, the lower ones in the middle. + val grips = LinearLayout(context).apply { + orientation = HORIZONTAL + val row = listOf("L4" to DeckControls.L4, "L5" to DeckControls.L5, "R5" to DeckControls.R5, "R4" to DeckControls.R4) + row.forEachIndexed { index, (label, bit) -> + addView(GripButton(context, label, null, bit), LayoutParams(0, LayoutParams.MATCH_PARENT, 1f).apply { + if (index > 0) leftMargin = dp(6) + if (index < row.size - 1) rightMargin = dp(6) + }) + } + } + addView(grips, LayoutParams(LayoutParams.MATCH_PARENT, dp(84))) + } + + private fun roundButton(label: String, description: String, onClick: () -> Unit, wide: Boolean = false) = + TextView(context).apply { + text = label + contentDescription = description + textSize = if (wide) 13f else 20f + typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) + letterSpacing = if (wide) 0.08f else 0f + gravity = Gravity.CENTER + setTextColor(TEXT) + background = outline(CORNER_PILL, SURFACE) + setPadding(if (wide) dp(16) else 0, 0, if (wide) dp(16) else 0, 0) + minWidth = dp(44) + layoutParams = LayoutParams(if (wide) LayoutParams.WRAP_CONTENT else dp(44), dp(44)) + setOnClickListener { + performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) + onClick() + } + } + + private fun space(width: Int) = View(context).apply { layoutParams = LayoutParams(width, 1) } + + private fun outline(radius: Float, fill: Int) = GradientDrawable().apply { + cornerRadius = radius * resources.displayMetrics.density + setColor(fill) + setStroke(dp(1), LINE) + } + + private fun filled(radius: Float, fill: Int) = GradientDrawable().apply { + cornerRadius = radius * resources.displayMetrics.density + setColor(fill) + } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density + 0.5f).toInt() + + /** A surface drawn the same way everywhere on the panel; pressed, it lights up in the accent. */ + private abstract class Surface(context: Context) : View(context) { + protected val density = resources.displayMetrics.density + protected val rect = RectF() + private val fill = Paint(Paint.ANTI_ALIAS_FLAG) + private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + protected val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textAlign = Paint.Align.CENTER + typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) + } + protected val captionPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + textAlign = Paint.Align.CENTER + color = TEXT_DIM + } + + protected fun drawSurface(canvas: Canvas, lit: Boolean) { + val inset = density + rect.set(inset, inset, width - inset, height - inset) + val radius = CORNER * density + fill.color = if (lit) ACCENT_WASH else SURFACE + canvas.drawRoundRect(rect, radius, radius, fill) + stroke.color = if (lit) ACCENT else LINE + stroke.strokeWidth = (if (lit) 2f else 1f) * density + canvas.drawRoundRect(rect, radius, radius, stroke) + } + } + + /** A held button: down while a finger is on it. */ + private open class HoldButton( + context: Context, + private val label: String, + private val caption: String?, + private val onChange: (Boolean) -> Unit, + ) : Surface(context) { + private var down = false + + override fun onDraw(canvas: Canvas) { + drawSurface(canvas, down) + val cx = width / 2f + labelPaint.textSize = min(height * 0.3f, 30 * density) + labelPaint.color = if (down) ACCENT else TEXT + val labelY = height / 2f + labelPaint.textSize * (if (caption == null) 0.35f else 0.1f) + canvas.drawText(label, cx, labelY, labelPaint) + if (caption != null) { + captionPaint.textSize = 12 * density + canvas.drawText(caption, cx, labelY + 22 * density, captionPaint) + } + } + + @SuppressLint("ClickableViewAccessibility") + override fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> set(true) + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> set(false) + } + return true + } + + private fun set(pressed: Boolean) { + if (down == pressed) return + down = pressed + if (pressed) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) + onChange(pressed) + invalidate() + } + } + + private class GripButton(context: Context, label: String, caption: String?, bit: Int) : + HoldButton(context, label, caption, { DeckControls.setGrip(bit, it) }) + + private class ClickBar(context: Context, right: Boolean) : + HoldButton(context, "Click", if (right) "Right trackpad" else "Left trackpad", { DeckControls.setClick(right, it) }) + + /** + * One trackpad: where the first finger is, as the Deck reports it (-1..1, y up), and a click + * while a second finger is down. + */ + private class TrackpadView(context: Context, private val right: Boolean) : Surface(context) { + private var touching = false + private var clicked = false + private var fingerX = 0f + private var fingerY = 0f + private val guide = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; color = GUIDE } + private val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = ACCENT } + private val glow = Paint(Paint.ANTI_ALIAS_FLAG) + + override fun onDraw(canvas: Canvas) { + drawSurface(canvas, clicked) + val cx = width / 2f + val cy = height / 2f + guide.strokeWidth = density + val reach = min(width, height) / 2f - 24 * density + canvas.drawCircle(cx, cy, reach, guide) + canvas.drawCircle(cx, cy, reach / 2f, guide) + canvas.drawLine(cx - reach, cy, cx + reach, cy, guide) + canvas.drawLine(cx, cy - reach, cx, cy + reach, guide) + captionPaint.textSize = 12 * density + captionPaint.color = if (touching) ACCENT else TEXT_DIM + canvas.drawText(if (right) "RIGHT TRACKPAD" else "LEFT TRACKPAD", cx, 28 * density, captionPaint) + if (touching) { + val radius = 56 * density + glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP) + canvas.drawCircle(fingerX, fingerY, radius, glow) + canvas.drawCircle(fingerX, fingerY, (if (clicked) 16 else 12) * density, dot) + } + } + + @SuppressLint("ClickableViewAccessibility") + override fun onTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> { + touch(event.getX(0), event.getY(0)) + click(event.pointerCount > 1) + } + MotionEvent.ACTION_POINTER_DOWN -> click(true) + MotionEvent.ACTION_POINTER_UP -> { + // The finger that lifted may be the first; the pad follows whichever stays. + val stays = if (event.actionIndex == 0) 1 else 0 + touch(event.getX(stays), event.getY(stays)) + click(event.pointerCount - 1 > 1) + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + click(false) + touching = false + DeckControls.setPad(right, touching = false) + invalidate() + } + } + return true + } + + private fun touch(x: Float, y: Float) { + fingerX = x.coerceIn(0f, width.toFloat()) + fingerY = y.coerceIn(0f, height.toFloat()) + touching = true + DeckControls.setPad(right, true, (fingerX - width / 2f) / (width / 2f), -(fingerY - height / 2f) / (height / 2f)) + invalidate() + } + + private fun click(down: Boolean) { + if (clicked == down) return + clicked = down + if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) + DeckControls.setClick(right, down) + invalidate() + } + } + + companion object { + /** The tab last shown, kept for the session so reopening the panel lands where it was. */ + private var selected = Tab.BOTH + + private const val CORNER = 20f + private const val CORNER_PILL = 22f + private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF) + private val ACCENT_WASH = Color.argb(0x2E, 0x1A, 0x9F, 0xFF) + private val ACCENT_GLOW = Color.argb(0x66, 0x1A, 0x9F, 0xFF) + private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F) + private val SURFACE = Color.rgb(0x0A, 0x0B, 0x0D) + private val LINE = Color.rgb(0x26, 0x29, 0x2E) + private val GUIDE = Color.rgb(0x16, 0x18, 0x1B) + private val TEXT = Color.rgb(0xF2, 0xF4, 0xF7) + private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt index df76a1e81..7b6722ccd 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DriverPage.kt @@ -92,7 +92,7 @@ fun DriverPage( contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).clip(RoundedCornerShape(10.dp)) .background(if (refreshHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) - .border(if (refreshHot) 2.dp else 1.dp, if (refreshHot) pal.signal else pal.line, RoundedCornerShape(10.dp)) + .glideBorder(refreshHot, RoundedCornerShape(10.dp), pal.signal, pal.line) .focusRequester(refreshFocus) .hoverable(refreshSrc) .clickable(interactionSource = refreshSrc, indication = null, enabled = !checking, onClick = onRefresh), @@ -141,6 +141,7 @@ fun DriverPage( text = { Text( if (row.tag == DriverRow.BUNDLED) "It is built into the app, so this removes its unpacked files and hides it. \"Restore built-in drivers\" brings it back, and Auto still uses it on a GPU that needs it." + else if (row.tag == DriverRow.BUNDLE) "It is one half of an Android + Linux bundle, so its runtime and display drivers are both removed. A driver in use goes back to the default." else "Its files are removed from the app." + if (row.id == selected) " It is the driver in use, so the default takes its place." else "", fontSize = 13.sp, ) @@ -173,7 +174,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(3.dp).clip(shape) .background(if (hot) pal.signal.copy(alpha = 0.14f) else if (selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent) - .border(2.dp, if (hot) pal.signal else Color.Transparent, shape), + .glideBorder(hot, shape, pal.signal), ) { Row( verticalAlignment = Alignment.CenterVertically, @@ -209,7 +210,7 @@ private fun InstalledRow(row: DriverRow, selected: Boolean, onSelect: () -> Unit contentAlignment = Alignment.Center, modifier = Modifier.padding(end = 8.dp).size(40.dp).clip(RoundedCornerShape(10.dp)) .background(if (delHot) colors.error.copy(alpha = 0.16f) else Color.Transparent) - .border(2.dp, if (delHot) colors.error else Color.Transparent, RoundedCornerShape(10.dp)) + .glideBorder(delHot, RoundedCornerShape(10.dp), colors.error) .focusRequester(delFocus) .focusProperties { left = mainFocus } .hoverable(delSrc).clickable(interactionSource = delSrc, indication = null, onClick = onDelete), @@ -229,7 +230,7 @@ internal fun FocusText(text: String, color: Color, modifier: Modifier = Modifier text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = color, modifier = modifier.clip(shape) .background(if (hot) color.copy(alpha = 0.14f) else Color.Transparent) - .border(2.dp, if (hot) color else Color.Transparent, shape) + .glideBorder(hot, shape, color) .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt new file mode 100644 index 000000000..6779032e1 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt @@ -0,0 +1,253 @@ +package com.droiddeck.launcher.ui + +import android.view.View +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.AnimationSpec +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch +import kotlin.math.abs + +// One focus ring for a whole screen that slides from control to control. When focus moves, the +// edge on the side it is heading springs ahead and the trailing edge catches up a beat later, so +// the ring stretches like a drop and snaps into the new control's shape. + +/** A control that can show the ring: where it is and what its ring looks like there. */ +internal class GlideSource { + var coords: LayoutCoordinates? = null + var shape: Shape by mutableStateOf(androidx.compose.ui.graphics.RectangleShape) + var color by mutableStateOf(Color.Transparent) + var width by mutableStateOf(2.dp) +} + +internal class FocusGlide(val view: View) { + var host: LayoutCoordinates? = null + /** Controls that are hot, the latest last: focus and a hovering pointer can each hold one. */ + val hot = mutableStateListOf() + /** Bumped when the current control moves (a scroll, a relayout). */ + var moves by mutableIntStateOf(0) + + val current: GlideSource? get() = hot.lastOrNull() + + fun claim(s: GlideSource) { hot.remove(s); hot.add(s) } + fun release(s: GlideSource) { hot.remove(s) } + fun moved(s: GlideSource) { if (hot.lastOrNull() === s) moves++ } + + /** [s]'s bounds in the host, cut to what is on screen; null when it is not laid out or is scrolled away. */ + fun boundsOf(s: GlideSource): Rect? { + val h = host ?: return null + val c = s.coords ?: return null + if (!h.isAttached || !c.isAttached) return null + val b = h.localBoundingBoxOf(c, clipBounds = true) + return if (b.width < 1f || b.height < 1f) null else b + } +} + +internal val LocalFocusGlide = staticCompositionLocalOf { null } + +private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float = + when (val o = shape.createOutline(size, dir, density)) { + is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x + is Outline.Rectangle -> 0f + is Outline.Generic -> minOf(size.width, size.height) / 2f + } + +/** + * A control's outline: [restColor] at [restWidth] always, and [hotColor] at [hotWidth] while [hot]. + * Under a [FocusGlideHost] the hot outline is the host's one sliding ring; elsewhere (a dialog, a + * popup, a screen with no host) it is drawn here, as a plain border. + */ +@Composable +internal fun Modifier.glideBorder( + hot: Boolean, + shape: Shape, + hotColor: Color, + restColor: Color = Color.Transparent, + hotWidth: Dp = 2.dp, + restWidth: Dp = 1.dp, +): Modifier { + val glide = LocalFocusGlide.current + if (glide == null || glide.view !== LocalView.current) { + return border(if (hot) hotWidth else restWidth, if (hot) hotColor else restColor, shape) + } + val src = remember { GlideSource() } + src.shape = shape + src.color = hotColor + src.width = hotWidth + DisposableEffect(glide, hot) { + if (hot) glide.claim(src) + onDispose { glide.release(src) } + } + val base = if (restColor.alpha > 0f) border(restWidth, restColor, shape) else this + return base.onGloballyPositioned { src.coords = it; glide.moved(src) } +} + +/** Leading edge on a focus move: quick and a little loose. */ +private fun lead(): AnimationSpec = Motion.sp(0.62f, 700f) +/** Trailing edge: slower, settles without a bounce to speak of. */ +private fun trail(): AnimationSpec = Motion.sp(0.78f, 360f) +/** Following a control that moves under the ring (a scroll): tight, no wobble. */ +private fun follow(): AnimationSpec = Motion.sp(1f, 2400f) + +/** How long after a focus move the ring keeps its stretchy springs and keeps checking where it is. */ +private const val SETTLE_MS = 450L + +/** + * Hosts the sliding focus ring for everything inside it. The ring is drawn over [content], in the + * host's space, so put the host inside anything that moves as a whole (a sheet that slides in). + */ +@Composable +internal fun FocusGlideHost(modifier: Modifier = Modifier, content: @Composable () -> Unit) { + val view = LocalView.current + val density = LocalDensity.current + val dir = LocalLayoutDirection.current + val glide = remember(view) { FocusGlide(view) } + val edges = remember { List(4) { Animatable(0f) } } // left, top, right, bottom + val corner = remember { Animatable(0f) } + val alpha = remember { Animatable(0f) } + val scope = rememberCoroutineScope() + val jobs = remember { arrayOfNulls(5) } + val cur = glide.current + var lastColor by remember { mutableStateOf(Color.Transparent) } + if (cur != null) lastColor = cur.color + val color by animateColorAsState(cur?.color ?: lastColor, Motion.tw(160), label = "glideColor") + var width by remember { mutableStateOf(2.dp) } + if (cur != null) width = cur.width + + LaunchedEffect(glide) { + var shown: GlideSource? = null + var movedAt = 0L + var dirSpecs: List> = List(4) { follow() } + var delays = LongArray(4) + fun go(i: Int, v: Float, spec: AnimationSpec, wait: Long) { + jobs[i]?.cancel() + jobs[i] = scope.launch { + if (wait > 0) delay(Motion.ms(wait.toInt()).toLong()) + edges[i].animateTo(v, spec) + } + } + fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) { + val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size + val r = cornerOf(s.shape, size, dir, density) + jobs[4]?.cancel() + jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) } + } + snapshotFlow { glide.current to glide.moves }.collectLatest { (src, _) -> + if (src == null) { + // Focus passing between two controls can let go of one a moment before the next + // takes it: wait a beat, so that reads as a move and not a fade out and back in. + delay(60) + scope.launch { alpha.animateTo(0f, Motion.tw(140)) } + shown = null + return@collectLatest + } + var first = src !== shown + val start = System.nanoTime() + var last: Rect? = null + while (true) { + val b = glide.boundsOf(src) + if (b == null) { + if (first) scope.launch { alpha.animateTo(0f, Motion.tw(140)) } + } else if (first) { + val prev = shown + val wasShowing = prev != null && alpha.targetValue > 0f + shown = src + first = false + if (!wasShowing) { + // Appearing: a hair bigger, pulled in onto the control as it fades up. + val out = with(density) { 3.dp.toPx() } + val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out) + jobs.forEach { it?.cancel() } + scope.launch { edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join() + dirSpecs = List(4) { Motion.sp(0.6f, 700f) } + delays = LongArray(4) + cornerTo(src, b, snap = true) + scope.launch { alpha.animateTo(1f, Motion.tw(140)) } + } else { + // Moving: the edges on the side it is heading lead. + val dx = b.center.x - (edges[0].value + edges[2].value) / 2f + val dy = b.center.y - (edges[1].value + edges[3].value) / 2f + val horizontal = abs(dx) >= abs(dy) + val leadIdx = if (horizontal) (if (dx >= 0) 2 else 0) else (if (dy >= 0) 3 else 1) + val trailIdx = (leadIdx + 2) % 4 + dirSpecs = List(4) { i -> when (i) { leadIdx -> lead(); trailIdx -> trail(); else -> Motion.sp(0.7f, 520f) } } + delays = LongArray(4) { i -> if (i == trailIdx) 30L else 0L } + cornerTo(src, b, snap = false) + scope.launch { alpha.animateTo(1f, Motion.tw(120)) } + } + movedAt = System.nanoTime() + listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> go(i, v, dirSpecs[i], delays[i]) } + last = b + } else if (b != last) { + // It moved under the ring: keep the stretch while the move is fresh, else follow. + val fresh = (System.nanoTime() - movedAt) / 1_000_000 < SETTLE_MS + listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> go(i, v, if (fresh) dirSpecs[i] else follow(), 0L) } + if (last == null) scope.launch { alpha.animateTo(1f, Motion.tw(120)) } + last = b + } + // Layer animations (a tile growing, a row sliding) move it without a relayout, so + // look again each frame for a moment after anything changes. + if ((System.nanoTime() - start) / 1_000_000 > SETTLE_MS) break + withFrameNanos { } + } + } + } + + Box( + modifier + .onGloballyPositioned { glide.host = it } + .drawWithContent { + drawContent() + val a = alpha.value + if (a <= 0.01f) return@drawWithContent + val w = width.toPx() + val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value + val sw = (r - l - w).coerceAtLeast(0f) + val sh = (b - t - w).coerceAtLeast(0f) + val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f) + drawRoundRect( + color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh), + cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a, + ) + }, + ) { + CompositionLocalProvider(LocalFocusGlide provides glide) { content() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt index 2d533fd52..1ec0fbfad 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -1,22 +1,48 @@ package com.droiddeck.launcher.ui import androidx.compose.runtime.Composable +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.Lossless /** * The frame generation picker, anchored to whatever opened it (host key "fg"). One copy for Setup, - * a game's launch settings and the session drawer, so they say the same thing. + * a game's launch settings and the session drawer, so they say the same thing. Importing a + * Lossless.dll is offered once the account is known to own Lossless Scaling. */ @Composable internal fun FrameGenMenu( - host: MenuHost, engine: String, multiplier: Int, lsfgReady: Boolean, - onPick: (engine: String, multiplier: Int) -> Unit, + host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State, + onPick: (FrameGen.Mode) -> Unit, + onImportLossless: () -> Unit, ) { - AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus -> - val need = if (lsfgReady) null else "Needs Lossless Scaling installed in Steam" - fun pick(e: String, m: Int) { onPick(e, m); host.open = null } - MenuItem("Off", checked = engine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { pick(FrameGen.ENGINE_OFF, 2) } - for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_WINFG, m), checked = engine == FrameGen.ENGINE_WINFG && multiplier == m) { pick(FrameGen.ENGINE_WINFG, m) } - for (m in 2..4) MenuItem(FrameGen.label(FrameGen.ENGINE_LSFG, m), checked = engine == FrameGen.ENGINE_LSFG && multiplier == m, enabled = lsfgReady, detail = need) { pick(FrameGen.ENGINE_LSFG, m) } + val context = LocalContext.current + AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = stringResource(R.string.frame_gen_title)) { firstItemFocus -> + val need = when { + lossless.ready -> null + lossless.owned -> stringResource(R.string.lsfg_needs_install) + else -> stringResource(R.string.lsfg_needs_steam) + } + @Composable + fun item(m: FrameGen.Mode, enabled: Boolean = true, detail: String? = null, focus: FocusRequester? = null) = + MenuItem(FrameGen.label(context, m), checked = mode == m, enabled = enabled, detail = detail, focusRequester = focus) { + onPick(m); host.open = null + } + item(FrameGen.Mode.OFF, focus = firstItemFocus) + for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_WINFG, m)) + val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } + + FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) } + lsfg.forEachIndexed { i, m -> item(m, enabled = lossless.ready, detail = need.takeIf { i == 0 }) } + if (lossless.owned) { + val using = when (lossless.source) { + Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam) + Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import) + Lossless.Source.NONE -> null + } + MenuItem(stringResource(R.string.lsfg_import), checked = false, detail = using) { host.open = null; onImportLossless() } + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt index a49df3698..64e1bfc60 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndArt.kt @@ -118,13 +118,12 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera val lift by animateFloatAsState(if (hot) -5f else 0f, Motion.sp(0.6f), label = "tileLift") val elev by animateFloatAsState(if (hot) 18f else 2f, Motion.tw(300), label = "tileElev") val pal = LocalPalette.current - val ring by animateColorAsState(if (hot) pal.signal else Color.Transparent, Motion.tw(220), label = "tileRing") Column( modifier = track .graphicsLayer { scaleX = scale; scaleY = scale; translationY = lift.dp.toPx(); shadowElevation = elev.dp.toPx(); shape = Shape12; clip = false; ambientShadowColor = if (hot) pal.signal else Color.Black; spotShadowColor = if (hot) pal.signal else Color.Black; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, 0.9f) } .clip(Shape12) .background(colors.surface) - .border(2.5.dp, ring, Shape12) + .glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp) .alpha(if (t.dim && !hot) 0.55f else 1f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = t.onClick), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 3d6424001..ccfe357ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -149,11 +149,20 @@ private fun Content( } return } + if (selected == "updates") { + UpdatesPage(s, a, modifier.padding(horizontal = padH, vertical = padV)) + return + } // Steam is a full-bleed wall of the library with Play over it. if (selected == "steam") { SteamHome(s, a, modifier) return } + // The Store scrolls and navigates inside itself (its tabs and an app's page). + if (selected == "store" && s.storeEnabled) { + StorePage(s, a, modifier) + return + } // The Games tab lays out its own list and detail. if (selected == "games" || selected.startsWith("app:")) { GamesPage(s, a, selected, onSelect, modifier) @@ -192,6 +201,8 @@ private fun Content( Rise(3) { SectionTitle("Emulators", "${installed.size} installed") } Rise(4) { EmulatorGrid(installed, first = true, onSelect = onSelect) } } + if (s.storeEnabled) Rise(5) { InstalledAppsGrid(a) } + if (s.appImagesEnabled) Rise(5) { AppImagesSection(a, s.ready) } if (available.isNotEmpty()) { Rise(5) { SectionTitle("Available to install", available.size.toString()) } Rise(6) { EmulatorGrid(available, first = installed.isEmpty(), onSelect = onSelect) } @@ -392,7 +403,7 @@ private fun EmulatorTile(e: Library.Emulator, modifier: Modifier, isFirst: Boole .graphicsLayer { scaleX = scale; scaleY = scale } .clip(Shape14) .background(if (hot) pal.signal.copy(alpha = 0.10f) else if (e.installed) colors.surface else Color.Transparent) - .border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, Shape14) + .glideBorder(hot, Shape14, pal.signal, pal.line) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) .padding(horizontal = 12.dp, vertical = 10.dp), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt index 523ce958a..ea67f9cd7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt @@ -120,11 +120,56 @@ private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActio } g.protonPrefix?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton("Proton prefix", compact = true) { a.onBrowseFiles(dir) } + // Only games added to the library; Steam titles keep their saves with Steam Cloud. + if (g.library == Library.ADDED) ManageSaves(g, dir, a) } BusyChip(s) } } +/** + * Manage saves: import a GameHub or Winlator save zip into this game's prefix, export its saves as + * either, or open the save folder found for it. The saves are looked for when the menu opens. + */ +@Composable +private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndActions) { + var open by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) } + val saves by androidx.compose.runtime.produceState?>(null, g.gameId, open) { + if (open) value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + runCatching { com.droiddeck.launcher.session.GameSaves.locate(prefix, g) }.getOrDefault(emptyList()) + } + } + val found = saves + val summary = when { + found == null -> "Looking for this game's saves…" + found.isEmpty() -> "No save folder found by name: an export takes the whole user folder." + else -> { + val mb = found.sumOf { it.bytes } / 1048576.0 + (if (found.size == 1) found[0].relPath else "${found.size} save folders") + " · ${found.sumOf { it.files }} files · " + + (if (mb < 1) "${(mb * 1024).toInt()} KB" else String.format("%.1f MB", mb)) + } + } + Box { + SecondaryButton("Manage saves", compact = true) { open = !open } + AnchoredMenu(open, onDismiss = { open = false }, title = "Game saves", note = summary) { first -> + MenuItem("Import saves…", checked = false, detail = "A GameHub or Winlator zip · the saves there now are backed up first", focusRequester = first) { + open = false; a.onSaveImport(g) + } + MenuItem("Export as GameHub zip…", checked = false, detail = "Saves under steamuser, for GameHub and BannerHub") { + open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.GAMEHUB) + } + MenuItem("Export as Winlator zip…", checked = false, detail = "Saves under xuser, for Winlator, WinNative and Bannerlator") { + open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.WINLATOR) + } + found?.firstOrNull()?.let { d -> + MenuItem("Open save folder", checked = false, detail = d.relPath) { + open = false; a.onBrowseFiles(java.io.File(prefix, "drive_c/users/steamuser/" + d.relPath)) + } + } + } + } +} + /** When it was last played (or where it is, if never) over its name, then room for Launch. */ @Composable private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) { @@ -175,7 +220,7 @@ private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Uni modifier = Modifier.fillMaxWidth().paneItem("game:${g.appId}") .clip(Shape12) .background(if (selected) pal.signal.copy(alpha = 0.14f) else if (hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent) - .border(2.dp, if (selected || focused) pal.signal else Color.Transparent, Shape12) + .glideBorder(focused, Shape12, pal.signal, if (selected) pal.signal else Color.Transparent, restWidth = 2.dp) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onSelect) .controllerConfirm(onClick = onLaunch) .padding(horizontal = 10.dp, vertical = 6.dp), @@ -234,7 +279,7 @@ private fun lastPlayedText(lastPlayed: Long): String? { private fun libraryLabel(library: String): String = when (library) { "internal" -> "Internal storage" - "added" -> "Added game" + Library.ADDED -> "Added game" else -> library } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 41f38fe41..18630a028 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -14,7 +14,6 @@ import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically -import androidx.compose.foundation.Image import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.background import androidx.compose.foundation.border @@ -26,10 +25,11 @@ import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.key import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding @@ -43,6 +43,8 @@ import androidx.compose.material.icons.outlined.Apps import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.Layers import androidx.compose.material.icons.outlined.SportsEsports +import androidx.compose.material.icons.outlined.Storefront +import androidx.compose.material.icons.outlined.SystemUpdate import androidx.compose.material.icons.outlined.Tune import androidx.compose.material.icons.outlined.VideoLibrary import androidx.compose.ui.graphics.vector.ImageVector @@ -65,15 +67,14 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.res.painterResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics 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.dp import androidx.compose.ui.unit.sp -import com.droiddeck.launcher.R import com.droiddeck.launcher.core.PhantomProcessLimit // The front end's side rail: the page list, the resume entry and the controller hints under it. @@ -134,21 +135,26 @@ internal fun SideRail( horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier.width(if (iconOnly) 64.dp else 92.dp).background(colors.surface).padding(vertical = if (compact) 8.dp else 12.dp), ) { - Image(painterResource(R.drawable.logo), contentDescription = "DroidDeck", modifier = Modifier.size(if (compact) 28.dp else 34.dp)) - Spacer(Modifier.height(if (compact) 6.dp else 12.dp)) + // Every section on screen at once: items shrink (to 44dp, still a touch target) before the rail scrolls. + val count = 6 + (if (s.storeEnabled) 1 else 0) + (if (s.isHomeApp) 1 else 0) + BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { + val fit = (maxHeight / count - 4.dp).coerceIn(44.dp, if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp) Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp), - modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()), + modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()), ) { - RailItem("Steam", Icons.Outlined.SportsEsports, "steam", selected == "steam", compact, iconOnly, onFocus = { onFocusSelect("steam") }) { onSelect("steam") } + RailItem("Steam", Icons.Outlined.SportsEsports, "steam", selected == "steam", compact, iconOnly, fit, onFocus = { onFocusSelect("steam") }) { onSelect("steam") } // Always there, so the items below it never move; an empty library says how to fill it. - RailItem("Games", Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, onFocus = { onFocusSelect("games") }) { onSelect("games") } - RailItem("Desktop", Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") } - RailItem("Components", Icons.Outlined.Layers, "components", selected == "components", compact, iconOnly, onFocus = { onFocusSelect("components") }) { onSelect("components") } + RailItem("Games", Icons.Outlined.VideoLibrary, "games", selected == "games", compact, iconOnly, fit, onFocus = { onFocusSelect("games") }) { onSelect("games") } + RailItem("Desktop", Icons.Outlined.DesktopWindows, "desktop", selected == "desktop", compact, iconOnly, fit, onFocus = { onFocusSelect("desktop") }) { onSelect("desktop") } + if (s.storeEnabled) RailItem("Store", Icons.Outlined.Storefront, "store", selected == "store", compact, iconOnly, fit, onFocus = { onFocusSelect("store") }) { onSelect("store") } + RailItem("Components", Icons.Outlined.Layers, "components", selected == "components", compact, iconOnly, fit, onFocus = { onFocusSelect("components") }) { onSelect("components") } // Home mode's extra section goes last, so it shifts nothing above it. - if (s.isHomeApp) RailItem("Apps", Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") } - RailItem("Setup", Icons.Outlined.Tune, "setup", selected == "setup", compact, iconOnly, badge = setupNeedsAttention, onFocus = { onFocusSelect("setup") }) { onSelect("setup") } + if (s.isHomeApp) RailItem("Apps", Icons.Outlined.Apps, "android-apps", selected == "android-apps", compact, iconOnly, fit, onFocus = { onFocusSelect("android-apps") }) { onSelect("android-apps") } + RailItem("Setup", Icons.Outlined.Tune, "setup", selected == "setup", compact, iconOnly, fit, badge = setupNeedsAttention, onFocus = { onFocusSelect("setup") }) { onSelect("setup") } + RailItem("Updates", Icons.Outlined.SystemUpdate, "updates", selected == "updates", compact, iconOnly, fit, badge = s.updates.hasUpdate, onFocus = { onFocusSelect("updates") }) { onSelect("updates") } + } } AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(bottom = 8.dp)) { @@ -170,7 +176,7 @@ internal fun SideRail( @Composable private fun RailItem( - label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, + label: String, icon: ImageVector, key: String, current: Boolean, compact: Boolean, iconOnly: Boolean, height: Dp, badge: Boolean = false, onFocus: () -> Unit = {}, onClick: () -> Unit, ) { val colors = MaterialTheme.colorScheme @@ -195,24 +201,23 @@ private fun RailItem( if (current) pal.signal.copy(alpha = 0.14f) else if (focused || hovered) Color.White.copy(alpha = 0.05f) else Color.Transparent, Motion.tw(220), label = "railFill", ) - val ring by animateColorAsState(if (focused) pal.signal else Color.Transparent, Motion.tw(180), label = "railRing") val scale by animateFloatAsState(if (pressed) 0.95f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "railScale") Box( contentAlignment = Alignment.Center, modifier = Modifier .then(if (frontFocus != null) Modifier.focusRequester(frontFocus.railFor(key)) else Modifier) .graphicsLayer { scaleX = scale; scaleY = scale } - .size(width = if (iconOnly) 52.dp else 80.dp, height = if (iconOnly) 48.dp else if (compact) 52.dp else 60.dp) + .size(width = if (iconOnly) 52.dp else 80.dp, height = height) .clip(Shape14) .background(fill) - .border(2.dp, ring, Shape14) + .glideBorder(focused, Shape14, pal.signal) .hoverable(src) .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) .then(if (iconOnly) Modifier.semantics { contentDescription = label } else Modifier), ) { if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp)) else Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) { - Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (compact) 20.dp else 22.dp)) + Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (height < 56.dp) 20.dp else 22.dp)) Text(label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = fg, maxLines = 1, softWrap = false) } if (badge) Box( @@ -242,7 +247,7 @@ private fun ResumeRailItem(name: String, compact: Boolean, iconOnly: Boolean, on .width(if (iconOnly) 52.dp else 80.dp) .clip(Shape14) .background(pal.good.copy(alpha = if (focused || hovered) 0.20f else 0.12f)) - .border(2.dp, if (focused) pal.signal else Color.Transparent, Shape14) + .glideBorder(focused, Shape14, pal.signal) .hoverable(src) .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onResume) .semantics { contentDescription = "Resume $name" } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index ee5153f0d..74f5caaf3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -68,6 +68,7 @@ import androidx.compose.ui.unit.sp import com.droiddeck.launcher.HomeApp import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.core.PhantomProcessLimit import com.droiddeck.launcher.core.PhantomProcessStatus @@ -91,9 +92,8 @@ class FrontEndState( val steamGames: List, val emulators: List, val running: String?, - val frameGenEngine: String = FrameGen.ENGINE_OFF, - val frameGenMultiplier: Int = 2, - val lsfgReady: Boolean = false, + val frameGen: FrameGen.Mode = FrameGen.Mode.OFF, + val lossless: Lossless.State = Lossless.State.NONE, val pageKey: String? = null, val theme: String = Themes.GRAPHITE, val isHomeApp: Boolean = false, @@ -114,6 +114,11 @@ class FrontEndState( val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE, val showPhantomGate: Boolean = false, val launcherFullscreen: Boolean = true, + /** Beta features the user turns on in Setup: the Flathub Store and AppImage import. */ + val storeEnabled: Boolean = false, + val appImagesEnabled: Boolean = false, + /** The Updates page: DroidDeck's own builds and the channel followed. */ + val updates: UpdatesState = UpdatesState(), ) class FrontEndActions( @@ -122,6 +127,11 @@ class FrontEndActions( val onSteamGame: (Library.SteamGame) -> Unit, val onDesktop: () -> Unit, val onEmulator: (Library.Emulator) -> Unit, + /** A Flatpak app by id and name, from the Store. */ + val onFlatpakApp: (String, String) -> Unit = { _, _ -> }, + /** Pick an AppImage to import; open an imported one by its directory and name. */ + val onImportAppImage: () -> Unit = {}, + val onAppImage: (String, String) -> Unit = { _, _ -> }, val onRom: (Library.Rom) -> Unit, val onResume: () -> Unit, val onSteamSettings: () -> Unit, @@ -129,10 +139,14 @@ class FrontEndActions( val onInstallPackage: (String) -> Unit, val onRemovePackage: (String) -> Unit, val onRuntime: () -> Unit, - val onFrameGenPick: (engine: String, multiplier: Int) -> Unit, + val onFrameGenPick: (FrameGen.Mode) -> Unit, + val onImportLossless: () -> Unit, val onProtons: () -> Unit, /** The Components page: FEX / DXVK / VKD3D-Proton per Proton. */ val onComponents: (focusContent: Boolean) -> Unit, + /** A game page's Manage saves: import a save zip into this game, or export its saves in a layout. */ + val onSaveImport: (Library.SteamGame) -> Unit = {}, + val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> }, val onPerformance: () -> Unit, val onRoms: () -> Unit, val onFiles: () -> Unit, @@ -140,15 +154,15 @@ class FrontEndActions( val onLogs: () -> Unit, val onShareLogs: () -> Unit = {}, val onOffline: () -> Unit, - val onCredits: () -> Unit, val onPageBack: () -> Unit = {}, val onTheme: (String) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {}, + val onStoreEnabled: (Boolean) -> Unit = {}, + val onAppImagesEnabled: (Boolean) -> Unit = {}, val onHomeApp: () -> Unit = {}, val onHomeScreen: (Boolean) -> Unit = {}, val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> }, val onBackActionsInverted: (Boolean) -> Unit = {}, - val onCheckLatestBuild: () -> Unit = {}, val onRefreshPhantomStatus: () -> Unit = {}, val onOpenDeveloperOptions: (Int?) -> Unit = {}, val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless debugging is unavailable") }, @@ -157,7 +171,10 @@ class FrontEndActions( val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit = { _, done -> done("Wireless debugging is unavailable") }, val onCopyPhantomCommand: (Boolean) -> Unit = {}, val onDismissPhantomGate: () -> Unit = {}, + val onStartWirelessAdbPairing: () -> Unit = {}, + val onOpenNotificationSettings: () -> Unit = {}, val controller: ControllerActions? = null, + val updates: UpdatesActions = UpdatesActions(), ) internal object Motion { @@ -348,6 +365,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com selected = if (selected.startsWith("emu:")) "desktop" else "emu:" + selected.removePrefix("rom:").substringBefore(':') } LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" } + // The Store turned off in Setup takes its page with it. + LaunchedEffect(s.storeEnabled) { if (!s.storeEnabled && selected == "store") selected = "steam" } // The last game uninstalled leaves the Games tab on its empty state. LaunchedEffect(s.steamGames.isEmpty()) { if (s.steamGames.isEmpty() && selected.startsWith("app:")) selected = "games" @@ -469,7 +488,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com status = s.phantomProcessStatus, onDismiss = a.onDismissPhantomGate, onOpenDeveloperOptions = requestDeveloperOptions, - onSetUpWirelessAdb = { requestWirelessAdbFix(false) }, + onFixWithWirelessDebugging = { + a.onStartWirelessAdbPairing() + requestDeveloperOptions() + }, + onEnterAddressManually = { requestWirelessAdbFix(false) }, + onCopyCommand = { a.onCopyPhantomCommand(false) }, + onOpenNotificationSettings = a.onOpenNotificationSettings, ) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index a8a225dfe..697e04b3c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -59,6 +59,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.stringResource import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalInputModeManager @@ -73,6 +74,7 @@ import com.droiddeck.launcher.core.DeviceSupport import com.droiddeck.launcher.core.PhantomProcessLimit import com.droiddeck.launcher.core.PhantomProcessStatus import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.R // The Setup page: runtime and device checks, tools, frame generation and launch settings. @@ -151,15 +153,18 @@ internal fun SetupPanel( } val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - val gpuOk = remember { DeviceSupport.adreno() } + // Tested hardware passes; an Adreno below it (a 610, say) warns rather than claiming support. + val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() } + val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED val gpuName = remember { DeviceSupport.gpuName() } val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) val signedIn = s.offlineAccount != null var showLimitDetails by rememberSaveable { mutableStateOf(false) } val checks = 4 val readyCount = listOf(gpuOk, s.ready && !s.busy, !limitBlocks, signedIn).count { it } - // Five tabs instead of one long scroll; LB and RB turn them from anywhere on the page. - val tabs = listOf("Overview", "Controller", "Session", "Launcher", "About") + // Four tabs instead of one long scroll; LB and RB turn them from anywhere on the page. Build + // and credits are on the Updates page. + val tabs = listOf("Overview", "Controller", "Session", "Launcher") var tab by rememberSaveable { mutableStateOf(0) } val tabFocus = remember { List(tabs.size) { FocusRequester() } } var tabTurned by remember { mutableStateOf(false) } @@ -192,8 +197,16 @@ internal fun SetupPanel( Column(modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) { CheckRow( if (gpuOk) CheckState.OK else CheckState.WARN, - if (gpuOk) "Device supported" else "GPU not supported", - if (gpuOk) gpuName else "Steam draws with an Adreno driver; $gpuName may show a black screen", + when (gpu.support) { + com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> "Device supported" + com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> "Untested GPU" + else -> "GPU not supported" + }, + when (gpu.support) { + com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> "${gpu.name} · $gpuName" + com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> "${gpu.name}: ${gpu.supportText.replaceFirstChar { it.lowercase() }}" + else -> "Steam draws with an Adreno driver; $gpuName may show a black screen" + }, ) CheckRow( when { s.busy -> CheckState.BUSY; !s.ready -> CheckState.WARN; else -> CheckState.OK }, @@ -268,7 +281,7 @@ internal fun SetupPanel( true to SessionPrefs.BACK_QAM_THEN_MENU, ), s.backActionsInverted, onPick = a.onBackActionsInverted, ) - SettingsRow("Frame generation", "Select the frame generation mode") { + SettingsRow(stringResource(R.string.frame_gen_title), stringResource(R.string.frame_gen_hint)) { Box { ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" } FrameGenMenu(s, a, host) @@ -312,11 +325,19 @@ internal fun SetupPanel( ActionRow("Default Home app", s.defaultHomeLabel ?: "Choose a Home app", "Choose", a.onHomeApp) } } - } - else -> { - SettingsGroup("About") { - ActionRow("Build", s.buildLabel, "Check for newer", a.onCheckLatestBuild) - ActionRow("Credits", "The people and projects DroidDeck builds on", "View", a.onCredits) + SettingsGroup("Linux apps (beta)") { + ToggleRow( + host, "store-enabled", "Flathub Store", + if (s.storeEnabled) "The Store is in the menu. Some apps may not start; logs are in Download/DroidDeck" + else "Off: install Linux apps and games from Flathub with Flatpak", + s.storeEnabled, + ) { a.onStoreEnabled(it) } + ToggleRow( + host, "appimages-enabled", "AppImages", + if (s.appImagesEnabled) "Add AppImage is on the Desktop page. ARM64 (aarch64) AppImages only" + else "Off: import ARM64 AppImages from your storage", + s.appImagesEnabled, + ) { a.onAppImagesEnabled(it) } } } } @@ -361,7 +382,7 @@ private fun ToolCard(t: ToolSpec, modifier: Modifier) { .graphicsLayer { scaleX = scale; scaleY = scale } .clip(Shape14) .background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) - .border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, Shape14) + .glideBorder(hot, Shape14, pal.signal, pal.line) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = t.onClick) .controllerConfirm(onClick = t.onClick) .padding(horizontal = 14.dp, vertical = 12.dp), @@ -374,7 +395,7 @@ private fun ToolCard(t: ToolSpec, modifier: Modifier) { @Composable private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) { - FrameGenMenu(host, s.frameGenEngine, s.frameGenMultiplier, s.lsfgReady, a.onFrameGenPick) + FrameGenMenu(host, s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless) } /** @@ -390,7 +411,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost add { m -> SettingCard("Components", "FEX, DXVK, VKD3D", "card:components", m) { a.onComponents(true) } } add { m -> Box(m) { - SettingCard("Frame generation", s.frameGenLabel, "card:fg", Modifier.fillMaxSize()) { + SettingCard(stringResource(R.string.frame_gen_title), s.frameGenLabel, "card:fg", Modifier.fillMaxSize()) { host.open = if (host.open == "fg") null else "fg" } FrameGenMenu(s, a, host) @@ -416,14 +437,13 @@ private fun SettingCard(label: String, value: String, id: String, modifier: Modi val hot = rememberHot(src) val pressed by src.collectIsPressedAsState() val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "cardScale") - val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(220), label = "cardEdge") Column( verticalArrangement = Arrangement.spacedBy(3.dp), modifier = modifier.paneItem(id) .graphicsLayer { scaleX = scale; scaleY = scale } .clip(Shape14) .background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) - .border(if (hot) 2.dp else 1.dp, edge, Shape14) + .glideBorder(hot, Shape14, pal.signal, pal.line2) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(horizontal = 14.dp, vertical = 12.dp), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index 7d034a138..8f1f8b3e8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -116,7 +116,7 @@ internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Un modifier = Modifier.paneItem("back:$label").heightIn(min = if (compact) 44.dp else 48.dp) .clip(shape) .background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.04f)) - .border(2.dp, if (hot) pal.signal else Color.Transparent, shape) + .glideBorder(hot, shape, pal.signal) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(start = 8.dp, end = 16.dp), @@ -180,7 +180,7 @@ internal fun PrimaryButton( .shine(hot, 0.45f) // The grow and shine alone barely show on the light fill: outline it when a // controller is on it, as the other controls are. - .border(2.dp, if (hot) pal.signal else Color.Transparent, Shape12) + .glideBorder(hot, Shape12, pal.signal) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled) { placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) } onClick() @@ -209,11 +209,10 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo val pressed by src.collectIsPressedAsState() val scale by animateFloatAsState(if (pressed) 0.955f else if (hot) 1.02f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "secScale") val pal = LocalPalette.current - val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "secEdge") val fill by animateColorAsState(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f), Motion.tw(250), label = "secFill") Box( contentAlignment = Alignment.Center, - modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12) + modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).glideBorder(hot, Shape12, pal.signal, pal.line2) .alpha(if (enabled) 1f else 0.5f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) @@ -228,10 +227,9 @@ internal fun Cog(size: androidx.compose.ui.unit.Dp = 48.dp, onClick: () -> Unit) val hot = rememberHot(src) val rot by animateFloatAsState(if (hot) 90f else 0f, Motion.sp(0.55f), label = "cog") val pal = LocalPalette.current - val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "cogEdge") Box( contentAlignment = Alignment.Center, - modifier = Modifier.paneItem("cog").downToFirstTile().size(size).clip(if (size > 48.dp) Shape14 else Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, if (size > 48.dp) Shape14 else Shape12) + modifier = Modifier.paneItem("cog").downToFirstTile().size(size).clip(if (size > 48.dp) Shape14 else Shape12).background(Color.White.copy(alpha = 0.03f)).glideBorder(hot, if (size > 48.dp) Shape14 else Shape12, pal.signal, pal.line2) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick), ) { Icon(Icons.Filled.Settings, "Settings", tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(if (size > 48.dp) 20.dp else 18.dp).rotate(rot)) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt new file mode 100644 index 000000000..c871ac847 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt @@ -0,0 +1,234 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.core.GameEnvironment +import com.droiddeck.launcher.core.GameEnvironmentOptions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.ui.text.input.KeyboardType +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.session.GameEnvironmentStore +import com.droiddeck.launcher.session.SessionPrefs +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +@Composable +fun GameEnvironmentRow(modifier: Modifier = Modifier) { + var open by remember { mutableStateOf(false) } + SettingsRow(stringResource(R.string.game_env_title), stringResource(R.string.game_env_hint)) { + TextButton(onClick = { open = true }, modifier = modifier.controllerConfirm { open = true }) { + Text(stringResource(R.string.game_env_edit)) + } + } + if (open) GameEnvironmentEditor { open = false } +} + +@Composable +private fun GameEnvironmentEditor(onClose: () -> Unit) { + val context = LocalContext.current + val coroutine = rememberCoroutineScope() + var config by remember { mutableStateOf(null) } + var games by remember { mutableStateOf(emptyList>()) } + var scope by remember { mutableStateOf("") } + var appId by remember { mutableStateOf("") } + var scopeMenu by remember { mutableStateOf(false) } + var addMenu by remember { mutableStateOf(false) } + var busy by remember { mutableStateOf(false) } + var error by remember { mutableStateOf(false) } + var editing by remember { mutableStateOf?>(null) } + val preset = SessionPrefs.fexPreset(context) + LaunchedEffect(Unit) { + runCatching { + withContext(Dispatchers.IO) { + GameEnvironmentStore.read(context) to Library.steamGames(context).map { it.appId.toString() to it.name } + } + }.onSuccess { (settings, installed) -> config = settings; games = installed } + .onFailure { error = true } + } + fun save(next: GameEnvironment.Config) { + busy = true + coroutine.launch { + val result = runCatching { withContext(Dispatchers.IO) { GameEnvironmentStore.save(context, next) } } + result.onSuccess { config = next; error = false }.onFailure { error = true } + busy = false + } + } + AlertDialog( + onDismissRequest = { if (!busy) onClose() }, + title = { Text(stringResource(R.string.game_env_title)) }, + confirmButton = { TextButton(onClick = onClose, enabled = !busy) { Text(stringResource(R.string.game_env_close)) } }, + text = { + Column(Modifier.heightIn(max = 460.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text(stringResource(R.string.game_env_hint)) + Text(stringResource(R.string.game_env_defaults), style = MaterialTheme.typography.bodySmall) + if (error) Text(stringResource(R.string.game_env_error), color = MaterialTheme.colorScheme.error) + if (config == null && !error) Text(stringResource(R.string.game_env_loading)) + val current = config + if (current != null) { + val profileName = if (scope.isEmpty()) stringResource(R.string.game_env_shared) + else games.firstOrNull { it.first == scope }?.second ?: stringResource(R.string.game_env_profile, scope) + Text(stringResource(R.string.game_env_scope), style = MaterialTheme.typography.labelMedium) + Box { + TextButton(onClick = { scopeMenu = true }, enabled = !busy) { Text(profileName) } + DropdownMenu(expanded = scopeMenu, onDismissRequest = { scopeMenu = false }, modifier = Modifier.heightIn(max = 280.dp)) { + DropdownMenuItem(text = { Text(stringResource(R.string.game_env_shared)) }, onClick = { scope = ""; scopeMenu = false }) + val profiles = (games + current.games.keys.filter { id -> games.none { it.first == id } }.map { it to it }).distinctBy { it.first } + for ((id, name) in profiles) DropdownMenuItem(text = { Text(name) }, onClick = { scope = id; scopeMenu = false }) + } + } + OutlinedTextField(value = appId, onValueChange = { appId = it }, singleLine = true, enabled = !busy, + label = { Text(stringResource(R.string.game_env_app_id)) }, modifier = Modifier.fillMaxWidth()) + TextButton(onClick = { scope = appId.toLong().toString(); appId = "" }, enabled = !busy && appId.isNotEmpty() && GameEnvironment.validScope(appId)) { + Text(stringResource(R.string.game_env_open)) + } + Text(stringResource(R.string.game_env_overrides), style = MaterialTheme.typography.bodySmall) + val entries = GameEnvironment.effective(current, preset, scope).toSortedMap() + if (entries.isEmpty()) Text(stringResource(R.string.game_env_empty)) + for ((name, value) in entries) { + HorizontalDivider() + Text(name, style = MaterialTheme.typography.titleSmall) + Text(value ?: stringResource(R.string.game_env_unset)) + if (!current.entries(scope).containsKey(name)) Text(stringResource(R.string.game_env_inherited), style = MaterialTheme.typography.labelSmall) + Row { + TextButton(onClick = { editing = name to (value ?: "") }, enabled = !busy) { Text(stringResource(R.string.game_env_edit)) } + if (value != null) TextButton(onClick = { save(current.withEntries(scope, current.entries(scope) + (name to null))) }, enabled = !busy) { + Text(stringResource(R.string.game_env_remove)) + } + } + if (current.entries(scope).containsKey(name)) TextButton(onClick = { save(current.withEntries(scope, current.entries(scope) - name)) }, enabled = !busy) { + Text(stringResource(R.string.game_env_restore)) + } + } + Box { + TextButton(onClick = { addMenu = true }, enabled = !busy) { Text(stringResource(R.string.game_env_add)) } + DropdownMenu(expanded = addMenu, onDismissRequest = { addMenu = false }, modifier = Modifier.heightIn(max = 280.dp)) { + DropdownMenuItem(text = { Text(stringResource(R.string.game_env_custom)) }, onClick = { editing = "" to ""; addMenu = false }) + for (option in GameEnvironmentOptions.all) DropdownMenuItem(text = { Text(option.name) }, onClick = { editing = option.name to option.value; addMenu = false }) + } + } + TextButton(onClick = { save(current.withEntries(scope, emptyMap())) }, enabled = !busy && current.entries(scope).isNotEmpty()) { + Text(stringResource(R.string.game_env_reset)) + } + } + if (busy) LinearProgressIndicator(Modifier.fillMaxWidth()) + } + }, + ) + editing?.let { (name, value) -> + VariableDialog(name, value, onDismiss = { editing = null }) { key, content -> + config?.let { + val entries = it.entries(scope).toMutableMap() + if (name.isNotEmpty() && name != key) entries[name] = null + entries[key] = content + save(it.withEntries(scope, entries)) + } + editing = null + } + } +} + +@Composable +private fun VariableDialog(initialName: String, initialValue: String, onDismiss: () -> Unit, onSave: (String, String) -> Unit) { + var name by remember { mutableStateOf(initialName) } + var value by remember { mutableStateOf(initialValue) } + val valid = GameEnvironment.validName(name) && GameEnvironment.validValue(value) + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.game_env_edit)) }, + confirmButton = { TextButton(onClick = { onSave(name, value) }, enabled = valid) { Text(stringResource(R.string.game_env_save)) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.game_env_cancel)) } }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + VariableNamePicker(name) { selected -> + name = selected + value = GameEnvironmentOptions.find(selected)?.value.orEmpty() + } + VariableValueEditor(name, value) { value = it } + GameEnvironmentOptions.find(name)?.takeIf { it.detail != 0 }?.let { + Text(stringResource(it.detail), style = MaterialTheme.typography.bodySmall) + } + if (!GameEnvironment.supported(name)) Text(stringResource(R.string.game_env_unused)) + if (!valid && name.isNotEmpty()) Text(stringResource(R.string.game_env_invalid), color = MaterialTheme.colorScheme.error) + } + }, + ) +} + +@Composable +private fun VariableNamePicker(name: String, onChange: (String) -> Unit) { + var expanded by remember { mutableStateOf(false) } + var custom by remember { mutableStateOf(name.isEmpty() || GameEnvironmentOptions.find(name) == null) } + Text(stringResource(R.string.game_env_name), style = MaterialTheme.typography.labelMedium) + Box { + OutlinedButton(onClick = { expanded = true }, modifier = Modifier.fillMaxWidth()) { + Text(if (custom) stringResource(R.string.game_env_custom) else name) + } + DropdownMenu(expanded, onDismissRequest = { expanded = false }, modifier = Modifier.heightIn(max = 280.dp)) { + DropdownMenuItem(text = { Text(stringResource(R.string.game_env_custom)) }, onClick = { + custom = true; onChange(""); expanded = false + }) + for (option in GameEnvironmentOptions.all.sortedBy { it.name.uppercase(java.util.Locale.ROOT) }) { + DropdownMenuItem(text = { Text(option.name) }, onClick = { + custom = false; onChange(option.name); expanded = false + }) + } + } + } + if (custom) OutlinedTextField(value = name, onValueChange = onChange, singleLine = true, + label = { Text(stringResource(R.string.game_env_name)) }, modifier = Modifier.fillMaxWidth()) +} + +@Composable +private fun VariableValueEditor(name: String, value: String, onChange: (String) -> Unit) { + val option = GameEnvironmentOptions.find(name) + var expanded by remember(name) { mutableStateOf(false) } + var custom by remember(name) { mutableStateOf(option == null || value !in option.choices && option.type != GameEnvironmentOptions.Type.MULTIPLE) } + when { + option?.type == GameEnvironmentOptions.Type.TOGGLE -> Row( + Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, + ) { + Text(stringResource(R.string.game_env_value)) + Switch(checked = value == option.choices.last(), onCheckedChange = { + onChange(if (it) option.choices.last() else option.choices.first()) + }) + } + option != null && option.choices.isNotEmpty() -> { + Box { + OutlinedButton(onClick = { expanded = true }, modifier = Modifier.fillMaxWidth()) { + Text(if (custom) stringResource(R.string.game_env_custom_value) else value.ifEmpty { stringResource(R.string.game_env_select_value) }) + } + DropdownMenu(expanded, onDismissRequest = { expanded = false }, modifier = Modifier.heightIn(max = 280.dp)) { + DropdownMenuItem(text = { Text(stringResource(R.string.game_env_custom_value)) }, onClick = { custom = true; expanded = false }) + for (choice in option.choices) { + val selected = choice in value.split(',') + DropdownMenuItem(text = { Text(choice) }, leadingIcon = { + if (option.type == GameEnvironmentOptions.Type.MULTIPLE) Checkbox(checked = selected, onCheckedChange = null) + }, onClick = { + custom = false + if (option.type == GameEnvironmentOptions.Type.MULTIPLE) { + onChange(GameEnvironmentOptions.toggle(value, choice)) + } else { + onChange(choice); expanded = false + } + }) + } + } + } + if (custom) OutlinedTextField(value = value, onValueChange = onChange, singleLine = true, + label = { Text(stringResource(R.string.game_env_value)) }, modifier = Modifier.fillMaxWidth()) + } + else -> OutlinedTextField(value = value, onValueChange = onChange, singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = if (option?.type == GameEnvironmentOptions.Type.NUMBER) KeyboardType.Number else KeyboardType.Text), + label = { Text(stringResource(R.string.game_env_value)) }, modifier = Modifier.fillMaxWidth()) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt new file mode 100644 index 000000000..bedab4c2b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GpuDriversPanel.kt @@ -0,0 +1,312 @@ +package com.droiddeck.launcher.ui + +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.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.AutoAwesome +import androidx.compose.material.icons.outlined.Memory +import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +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 + +/** One matched driver pair in the list (DriverPairs), and what this device makes of it. */ +class PairRow( + val key: String, + val name: String, + val version: String, + val detail: String, + val recommended: Boolean, + /** Built for this GPU's family; the others only show when asked. */ + val suits: Boolean, + val complete: Boolean, + val installed: Boolean, + val active: Boolean, +) + +class GpuDriversState( + val gpuName: String = "", + val gpuFamily: String = "", + val soc: String = "", + val supportText: String = "", + val supported: Boolean = true, + val unsupported: Boolean = false, + val auto: Boolean = true, + val pairs: List = emptyList(), + /** The pair key being installed, and how far along (-1 = unknown). */ + val busy: String? = null, + val percent: Int = -1, + val autoStatus: String = "", + val releaseStatus: String = "", + val checking: Boolean = false, + // Advanced: each driver on its own. + val linuxRows: List = emptyList(), + val linuxSelected: String = "", + val androidRows: List = emptyList(), + val androidSelected: String = "", + val linuxDownloads: List = emptyList(), + val androidDownloads: List = emptyList(), + val canRestoreBundled: Boolean = false, + /** The Android + Linux bundle both drivers are set to ("DD-Turnip 0.1.0"), or null. */ + val activeBundle: String? = null, +) { + /** The pair both drivers are set to, if they make one. */ + val activePair: PairRow? get() = pairs.firstOrNull { it.active } +} + +class GpuDriversActions( + val onAuto: (Boolean) -> Unit = {}, + val onPair: (String) -> Unit = {}, + val onRefresh: () -> Unit = {}, + val onSelectLinux: (String) -> Unit = {}, + val onSelectAndroid: (String) -> Unit = {}, + val onRemoveLinux: (String) -> Unit = {}, + val onRemoveAndroid: (String) -> Unit = {}, + val onDownloadDriver: (String) -> Unit = {}, + val onImportLinux: () -> Unit = {}, + val onImportAndroid: () -> Unit = {}, + /** The tab's own import: a bundle, or a single driver of either kind. */ + val onImportZip: () -> Unit = {}, + val onRestoreBundled: () -> Unit = {}, +) + +/** + * The GPU drivers tab: this GPU, and the drivers it draws with - a runtime (Linux) driver for the + * games and a display (Android) driver for the screen, set together as one matched pair. Auto keeps + * the pair recommended for the GPU installed and current; Manual picks a pair from the list; the + * two lists each on their own, and imports, are under Advanced. + */ +@Composable +internal fun GpuDriversPanel(s: GpuDriversState, a: GpuDriversActions, onAdvanced: (String) -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var showAll by rememberSaveable { mutableStateOf(false) } + Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 12.dp)) { + DeviceCard(s) + if (!s.unsupported) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + ModeCard(Icons.Outlined.AutoAwesome, "Auto", "The best pair for this GPU, kept up to date", s.auto, Modifier.weight(1f)) { a.onAuto(true) } + ModeCard(Icons.Outlined.Tune, "Manual", "Pick a pair yourself", !s.auto, Modifier.weight(1f)) { a.onAuto(false) } + } + if (s.auto) AutoCard(s) + else { + val shown = s.pairs.filter { it.suits || showAll } + if (shown.isEmpty()) Text( + if (s.checking) "Checking for drivers…" else "No drivers listed yet. Tap refresh to look for them.", + fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 8.dp), + ) + for (p in shown) PairLine(p, s.busy == p.key, s.percent, enabled = s.busy == null) { a.onPair(p.key) } + if (s.pairs.any { !it.suits }) FocusText( + if (showAll) "Hide drivers for other GPUs" else "Show drivers for other GPUs", pal.signal, + ) { showAll = !showAll } + } + } + SettingsGroup("Advanced") { + val together = s.activeBundle?.let { "Set together with the %s driver: $it carries both." } + SettingsRow("Runtime driver", together?.format("display") ?: "Games and the desktop draw with it.") { + DriverDropdown(s.linuxRows, s.linuxSelected, "Runtime default", a.onSelectLinux) { onAdvanced("rt") } + } + SettingsRow("Display driver", together?.format("runtime") ?: "Puts frames on the screen. Changes apply after DroidDeck restarts.") { + DriverDropdown(s.androidRows, s.androidSelected, "Auto - picked by GPU", a.onSelectAndroid) { onAdvanced("panel") } + } + } + } +} + +/** + * One driver list as a drop-down: the installed drivers to pick from, and the full page for + * downloading and deleting them. An Android + Linux bundle's row is tagged, and picking it sets both. + */ +@Composable +private fun DriverDropdown(rows: List, selected: String, fallback: String, onSelect: (String) -> Unit, onManage: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var open by remember { mutableStateOf(false) } + Box { + SecondaryButton((rows.firstOrNull { it.id == selected }?.name ?: fallback) + " ▾", compact = true) { open = true } + DropdownMenu(open, onDismissRequest = { open = false }, modifier = Modifier.heightIn(max = 360.dp)) { + for (row in rows) DropdownMenuItem( + leadingIcon = { Radio(row.id == selected) }, + text = { + Column { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(row.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (row.id == selected) pal.signal else colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (row.tag == DriverRow.BUNDLE) Text(row.tag, fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = colors.onSurfaceVariant) + } + if (row.detail.isNotEmpty()) Text(row.detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + }, + onClick = { open = false; if (row.id != selected) onSelect(row.id) }, + ) + HorizontalDivider(color = pal.line) + DropdownMenuItem(text = { Text("Download, import or delete…", fontSize = 14.sp, color = pal.signal) }, onClick = { open = false; onManage() }) + } + } +} + +@Composable +private fun DeviceCard(s: GpuDriversState) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val tint = when { + s.unsupported -> pal.error + s.supported -> pal.good + else -> AttentionAmber + } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp), + modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(14.dp), + ) { + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(44.dp).clip(Shape12).background(tint.copy(alpha = 0.14f))) { + Icon(Icons.Outlined.Memory, contentDescription = null, tint = tint, modifier = Modifier.size(24.dp)) + } + Column(Modifier.weight(1f)) { + Text(s.gpuName, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) + Text(listOf(s.soc, s.gpuFamily).filter { it.isNotEmpty() }.joinToString(" · "), fontSize = 13.sp, color = colors.onSurfaceVariant) + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Box(Modifier.size(7.dp).clip(CircleShape).background(tint)) + Text(s.supportText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 2) + } + } +} + +/** What Auto has set and what it is doing. */ +@Composable +private fun AutoCard(s: GpuDriversState) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val active = s.activePair + val recommended = s.pairs.firstOrNull { it.recommended } + Column( + verticalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(14.dp), + ) { + Text("IN USE", fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = colors.onSurfaceVariant) + Text( + active?.let { "${it.name} ${it.version}" } ?: s.activeBundle ?: "The drivers built into DroidDeck", + fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, + ) + Text( + if (active != null || s.activeBundle != null) "Runtime and display drivers set together as a matched pair." + else recommended?.let { "Recommended for this GPU: ${it.name}." } ?: "Tap refresh to look for drivers for this GPU.", + fontSize = 13.sp, color = colors.onSurfaceVariant, + ) + if (s.busy != null) { + LinearProgressIndicator( + progress = { (s.percent.coerceAtLeast(0)) / 100f }, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape), + ) + } + if (s.autoStatus.isNotEmpty()) Text(s.autoStatus, fontSize = 13.sp, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp)) + } +} + +@Composable +private fun ModeCard(icon: ImageVector, title: String, hint: String, selected: Boolean, modifier: Modifier, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val fill = if (hot) pal.signal.copy(alpha = 0.14f) else if (selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = modifier.paneItem("gpu-mode:$title").heightIn(min = 56.dp) + .clip(Shape14).background(colors.surface).background(fill) + .border(if (hot) 2.dp else 1.dp, if (hot || selected) pal.signal else pal.line, Shape14) + .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(onClick = onClick) + .padding(horizontal = 14.dp, vertical = 10.dp), + ) { + Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) + Column(Modifier.weight(1f)) { + Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Radio(selected) + } +} + +@Composable +private fun PairLine(p: PairRow, busy: Boolean, percent: Int, enabled: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val usable = enabled && p.complete && !p.active + val fill = if (hot) pal.signal.copy(alpha = 0.14f) else if (p.active) pal.signal.copy(alpha = 0.08f) else Color.Transparent + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().paneItem("pair:${p.key}").heightIn(min = 56.dp) + .clip(Shape12).background(colors.surface).background(fill) + .border(if (hot) 2.dp else 1.dp, if (hot || p.active) pal.signal else pal.line, Shape12) + .hoverable(src).clickable(interactionSource = src, indication = null, enabled = usable, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(enabled = usable, onClick = onClick) + .padding(horizontal = 14.dp, vertical = 8.dp), + ) { + Radio(p.active) + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(p.name, fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + if (p.recommended) Text( + "RECOMMENDED", fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = pal.good, + modifier = Modifier.clip(RoundedCornerShape(5.dp)).background(pal.good.copy(alpha = 0.12f)).padding(horizontal = 6.dp, vertical = 2.dp), + ) + } + Text("${p.version} · ${p.detail}", fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + when { + busy -> Column(horizontalAlignment = Alignment.End, modifier = Modifier.width(96.dp)) { + Text(if (percent >= 0) "$percent%" else "…", fontSize = 12.sp, color = colors.onSurfaceVariant) + LinearProgressIndicator(progress = { percent.coerceAtLeast(0) / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) + } + p.active -> Text("In use", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal) + !p.complete -> Text("Unavailable", fontSize = 13.sp, color = colors.onSurfaceVariant) + p.installed -> Text("Use", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + else -> Text("Download", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + } + } +} + +@Composable +private fun Radio(selected: Boolean) { + val pal = LocalPalette.current + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).border(2.dp, if (selected) pal.signal else pal.line2, CircleShape)) { + if (selected) Box(Modifier.size(10.dp).clip(CircleShape).background(pal.signal)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LaunchFlood.kt b/app/src/main/java/com/droiddeck/launcher/ui/LaunchFlood.kt index ad43b536b..59d257273 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LaunchFlood.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LaunchFlood.kt @@ -36,9 +36,18 @@ import kotlinx.coroutines.coroutineScope import androidx.compose.ui.layout.onSizeChanged import androidx.compose.runtime.snapshotFlow import androidx.compose.animation.core.spring +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.unit.Dp +import java.lang.ref.WeakReference +import kotlin.math.PI +import kotlin.math.sin // Starting a session from a blue button: the button grows until the page is its blue, and the // loading screen opens on that blue and gathers it into the ball of the throbber. +// Stopping one from the drawer runs it the other way: Stop grows until the page is blue, and the +// front end opens on that blue and draws it back down into the button the session came from. /** Carries the flood's colour to the session, which opens on it. */ const val EXTRA_FLOOD = "com.droiddeck.launcher.FLOOD" @@ -48,6 +57,8 @@ internal object LaunchOrigin { private var bounds: Rect? = null private var button: Any? = null private var at = 0L + /** The last button a session was started from, for a stop to return into. */ + private var last: WeakReference? = null /** The button a flood is growing out of: it steps aside so only the flood shows. */ var flooding by mutableStateOf(null) @@ -55,9 +66,22 @@ internal object LaunchOrigin { fun mark(r: Rect, key: Any) { bounds = r button = key + last = WeakReference(key) at = SystemClock.uptimeMillis() } + /** + * Where the button the running session was started from sits now, if it is still on screen; + * it hides for the return, as for the flood. + */ + fun takeReturn(): Rect? { + val key = last?.get() as? Array<*> ?: return null + val c = key.getOrNull(0) as? LayoutCoordinates ?: return null + if (!c.isAttached) return null + flooding = key + return c.boundsInRoot() + } + /** The button behind a launch starting now, if one was pressed just before; it hides for the flood. */ fun take(): Rect? { val b = bounds?.takeIf { SystemClock.uptimeMillis() - at < 1_500 } @@ -68,6 +92,23 @@ internal object LaunchOrigin { } } +/** A session stopped behind a flood: the blue the front end opens on, for a few seconds. */ +internal object QuitFlood { + private var color: Int? = null + private var at = 0L + + fun mark(argb: Int) { + color = argb + at = SystemClock.uptimeMillis() + } + + fun take(): Int? { + val c = color?.takeIf { SystemClock.uptimeMillis() - at < 3_000 } + color = null + return c + } +} + /** The page a flood grows over, sinking back a touch as it is covered; [progress] is the flood's. */ @Composable internal fun FloodBehind(progress: () -> Float, content: @Composable () -> Unit) { @@ -87,9 +128,17 @@ private val Gather = CubicBezierEasing(0.6f, 0f, 0.15f, 1f) * Swallows touches while it runs. */ @Composable -internal fun LaunchFlood(from: Rect, onProgress: (Float) -> Unit, onCovered: () -> Unit) { +internal fun LaunchFlood( + from: Rect, + onProgress: (Float) -> Unit, + /** The button's own colours, where it is not the page's blue one (a red Stop). */ + fromColors: Pair? = null, + cornerAtRest: Dp = 12.dp, + onCovered: () -> Unit, +) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current + val start = fromColors ?: (colors.primary to pal.primary2) // Left, top, right, bottom: 0 on the button, 1 on the page's edge. Springs overshoot past the // edge, off the page, so the wobble is felt in the pull and never seen as a shrink. val edges = remember { List(4) { Animatable(0f) } } @@ -117,30 +166,83 @@ internal fun LaunchFlood(from: Rect, onProgress: (Float) -> Unit, onCovered: () } } Canvas(Modifier.fillMaxSize().onSizeChanged { page = Size(it.width.toFloat(), it.height.toFloat()) }.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) { - val (l, t, r, b) = edges.map { it.value } - val mean = edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f - // The button sinks with the page behind (FloodBehind), so the flood leaves from where it is now. - val k = sinkScale(mean) - val cx = size.width / 2f - val cy = size.height / 2f - val left = lerp(cx + (from.left - cx) * k, 0f, l) - val top = lerp(cy + (from.top - cy) * k, 0f, t) - val right = lerp(cx + (from.right - cx) * k, size.width, r) - val bottom = lerp(cy + (from.bottom - cy) * k, size.height, b) - val w = (right - left).coerceAtLeast(0f) - val h = (bottom - top).coerceAtLeast(0f) - // A button's corners at rest, a blob in flight, square once it fills the page. - val blob = kotlin.math.sin(Math.PI * mean).toFloat().coerceAtLeast(0f) - val corner = lerp(12.dp.toPx() * (1f - mean), minOf(w, h) * 0.42f, blob) - // The button's gradient gives way to the ball's flat blue in the first half. - val mix = (mean * 2f).coerceAtMost(1f) - drawRoundRect( - Brush.linearGradient( - listOf(lerp(colors.primary, pal.signal, mix), lerp(pal.primary2, pal.signal, mix)), - start = Offset(left, top), end = Offset(right, bottom), - ), - topLeft = Offset(left, top), size = Size(w, h), cornerRadius = CornerRadius(corner), - ) + drawFlood(from, edges.map { it.value }, start, pal.signal, cornerAtRest.toPx()) + } +} + +/** + * The flood from a button at [from] with its edges [v] of the way to the page's (left, top, right, + * bottom): the button sinking with the page behind, blobby in flight, its colours [start] giving + * way to the flat [signal] in the first half. + */ +private fun DrawScope.drawFlood(from: Rect, v: List, start: Pair, signal: Color, cornerAtRest: Float) { + val (l, t, r, b) = v + val mean = v.sumOf { it.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f + // The button sinks with the page behind (FloodBehind), so the flood leaves from where it is now. + val k = sinkScale(mean) + val cx = size.width / 2f + val cy = size.height / 2f + val left = lerp(cx + (from.left - cx) * k, 0f, l) + val top = lerp(cy + (from.top - cy) * k, 0f, t) + val right = lerp(cx + (from.right - cx) * k, size.width, r) + val bottom = lerp(cy + (from.bottom - cy) * k, size.height, b) + val w = (right - left).coerceAtLeast(0f) + val h = (bottom - top).coerceAtLeast(0f) + // A button's corners at rest, a blob in flight, square once it fills the page. + val blob = sin(PI * mean).toFloat().coerceAtLeast(0f) + val corner = lerp(cornerAtRest * (1f - mean), minOf(w, h) * 0.42f, blob) + // The button's gradient gives way to the ball's flat blue in the first half. + val mix = (mean * 2f).coerceAtMost(1f) + val brush = Brush.linearGradient( + listOf(lerp(start.first, signal, mix), lerp(start.second, signal, mix)), + start = Offset(left, top), end = Offset(right, bottom), + ) + drawRoundRect(brush, topLeft = Offset(left, top), size = Size(w, h), cornerRadius = CornerRadius(corner)) +} + +/** + * The front end's first frames after a stop: the page in [flood] after a beat, drawn back down + * into the button at [to] (root px, measured before the page sank) on critically damped springs, + * the far edges first, so it sets down on the button without a bounce. [onProgress] (1 to 0) lets + * the page behind rise back. No button to return to: the blue fades. Calls [onLanded] at the end. + */ +@Composable +internal fun FloodReturn(flood: Color, to: Rect?, onProgress: (Float) -> Unit, onLanded: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val edges = remember { List(4) { Animatable(1f) } } + val fade = remember { Animatable(1f) } + val landed by rememberUpdatedState(onLanded) + val progress by rememberUpdatedState(onProgress) + var page by remember { mutableStateOf(Size.Zero) } + LaunchedEffect(page != Size.Zero) { + if (page == Size.Zero) return@LaunchedEffect + progress(1f) + // A beat of plain blue first, so the change of screen does not read as a cut. + delay(Motion.ms(220).toLong()) + if (to == null || Motion.scale == 0f) { + fade.animateTo(0f, tween(Motion.ms(240).coerceAtLeast(1))) + } else { + val travel = listOf(to.left, to.top, page.width - to.right, page.height - to.bottom).map { it.coerceAtLeast(0f) } + val far = travel.max().coerceAtLeast(1f) + coroutineScope { + edges.mapIndexed { i, edge -> + val lead = travel[i] / far + launch { + delay(Motion.ms((180 * (1f - lead)).toInt()).toLong()) + edge.animateTo(0f, spring(dampingRatio = 1f, stiffness = lerp(110f, 190f, lead))) { + progress(edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f) + } + } + }.forEach { it.join() } + } + } + progress(0f) + landed() + } + Canvas(Modifier.fillMaxSize().onSizeChanged { page = Size(it.width.toFloat(), it.height.toFloat()) }.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) { + if (to == null) drawRect(flood, alpha = fade.value) + else drawFlood(to, edges.map { it.value }, colors.primary to pal.primary2, flood, 12.dp.toPx()) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt index f70136020..94c6f593d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt @@ -51,25 +51,3 @@ fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () -> dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, ) } - -@Composable -fun CreditsDialog(onDismiss: () -> Unit) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Credits") }, - text = { - Column(modifier = Modifier.verticalScroll(rememberScrollState())) { - Text("The412Banner: app, compositor, runtime, and Steam session.", style = MaterialTheme.typography.bodyMedium) - Spacer(Modifier.height(10.dp)) - Text("maxjivi05: gamescope runtime and controller support, based on WinNative.", style = MaterialTheme.typography.bodyMedium) - Spacer(Modifier.height(10.dp)) - Text( - "GPL-3.0. Steam, Steam Deck, and Proton are Valve trademarks. Not affiliated with Valve. Third-party software remains under its authors' licenses.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - }, - confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } }, - ) -} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 2bdea340f..d9f26e6b4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -16,6 +16,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R import androidx.compose.ui.Modifier import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.unit.dp @@ -31,6 +33,8 @@ class DriverRow(val id: String, val name: String, val detail: String, val remova const val BUNDLED = "BUNDLED" const val DOWNLOADED = "DOWNLOADED" const val IMPORTED = "IMPORTED" + /** One half of an Android + Linux bundle: picked and deleted together with the other. */ + const val BUNDLE = "ANDROID + LINUX" } } @@ -45,10 +49,10 @@ class ModeSettings( val shapeMode: String, val hdr: Boolean, val hdrReason: String?, - val linuxRows: List, - val linuxSelected: String, - val androidRows: List, - val androidSelected: String, + /** The GPU drivers in use, as the row that opens them on the Components page says it. */ + val gpuDrivers: String = "Auto", + /** Frames per second the session is capped at; 0 = none. */ + val fpsLimit: Int = 0, val touchMode: String, val suspendPolicy: String, /** Steam only. */ @@ -66,6 +70,12 @@ class ModeSettings( val forceFullscreen: 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. */ + val steamDeckMode: Boolean = false, + /** Steam, Deck mode: the QAM's performance overlay (mangoapp) is started. */ + val mangoapp: Boolean = true, + /** Steam only: what the pad is to the client (SessionPrefs.CONTROLLER_*); null outside Steam. */ + val steamController: String? = null, /** Steam only: start a Steam session when DroidDeck opens. */ val runSteamAtStartup: Boolean = false, /** Steam only: the user's chosen Games folders; null outside Steam. */ @@ -73,12 +83,6 @@ class ModeSettings( val addedGames: List = emptyList(), val addedGamesArt: Boolean = true, /** Latest Banners-Turnip release: what each driver menu offers to download, and the refresh line. */ - val linuxDownloads: List = emptyList(), - val androidDownloads: List = emptyList(), - val releaseStatus: String = "Not checked yet - tap refresh to look for new drivers", - val releaseChecking: Boolean = false, - /** A bundled display driver was deleted: the page offers to restore it. */ - val canRestoreBundled: Boolean = false, /** Steam only: Decky Loader is managed from the Steam session settings. */ val deckyInstalled: String? = null, val deckyLatestRelease: DeckyManager.Release? = null, @@ -98,16 +102,9 @@ class ModeSettingsActions( val onCustomResolution: (Pair?) -> Unit = {}, val onShape: (String) -> Unit, val onHdr: (Boolean) -> Unit, - val onSelectLinux: (String) -> Unit, - val onImportLinux: () -> Unit, - val onRemoveLinux: (String) -> Unit, - val onRefreshReleases: () -> Unit = {}, - /** Asset name of the release driver to download. */ - val onDownloadDriver: (String) -> Unit = {}, - val onRestoreBundled: () -> Unit = {}, - val onSelectAndroid: (String) -> Unit, - val onImportAndroid: () -> Unit, - val onRemoveAndroid: (String) -> Unit, + /** Opens the GPU drivers on the Components page: they are shared by every session. */ + val onGpuDrivers: () -> Unit = {}, + val onFpsLimit: (Int) -> Unit = {}, val onTouch: (String) -> Unit, val onSuspendPolicy: (String) -> Unit, val onOsc: (String) -> Unit, @@ -121,6 +118,9 @@ class ModeSettingsActions( val onFexPreset: (String) -> Unit = {}, val onForceFullscreen: (Boolean) -> Unit = {}, val onSteamChannel: (String) -> Unit = {}, + val onSteamDeckMode: (Boolean) -> Unit = {}, + val onMangoapp: (Boolean) -> Unit = {}, + val onSteamController: (String) -> Unit = {}, val onRunSteamAtStartup: (Boolean) -> Unit = {}, val onPickAddedGamesDir: () -> Unit = {}, val onForgetAddedGamesDir: (path: String) -> Unit = {}, @@ -139,51 +139,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { val steam = s.mode == SessionService.MODE_STEAM val host = rememberMenuHost() var confirmDeckyRemoval by remember { mutableStateOf(false) } - // The two driver lists open as full pages over this one ("rt" = runtime, "panel" = display). - // Coming back restores this page as it was left: the same scroll position, and controller focus - // on the driver box that opened the page. - var driverPage by remember { mutableStateOf(null) } - var returnTo by remember { mutableStateOf(null) } val pageScroll = androidx.compose.foundation.rememberScrollState() - val runtimeChip = remember { androidx.compose.ui.focus.FocusRequester() } - val displayChip = remember { androidx.compose.ui.focus.FocusRequester() } val firstChip = remember { androidx.compose.ui.focus.FocusRequester() } - fun openDriverPage(key: String) { returnTo = key; driverPage = key } - androidx.compose.runtime.LaunchedEffect(driverPage) { - if (driverPage == null) { - // One frame first: the box has to be laid out before it can take focus. Opened from the - // cog, focus starts on the first control (Resolution) so the d-pad works at once; back - // from a driver page, it returns to the driver box that opened it. - androidx.compose.runtime.withFrameNanos { } - val target = when (returnTo) { "rt" -> runtimeChip; "panel" -> displayChip; else -> firstChip } - runCatching { target.requestFocus() } - } - } - when (driverPage) { - "rt" -> { - DriverPage( - title = "Runtime driver", - hint = (if (steam) "Used by Steam and games." else "Used by desktop apps.") + " Applies next session.", - rows = s.linuxRows, selected = s.linuxSelected, downloads = s.linuxDownloads, - status = s.releaseStatus, checking = s.releaseChecking, importLabel = "Import Turnip zip…", canRestore = false, - onSelect = a.onSelectLinux, onDelete = a.onRemoveLinux, onRefresh = a.onRefreshReleases, - onDownload = a.onDownloadDriver, onImport = a.onImportLinux, onRestore = {}, onBack = { driverPage = null }, - ) - return - } - "panel" -> { - DriverPage( - title = "Display driver", - hint = "Used by the compositor in both modes. Restart the app to apply.", - rows = s.androidRows, selected = s.androidSelected, downloads = s.androidDownloads, - status = s.releaseStatus, checking = s.releaseChecking, importLabel = "Import an AdrenoTools zip…", - canRestore = s.canRestoreBundled, - onSelect = a.onSelectAndroid, onDelete = a.onRemoveAndroid, onRefresh = a.onRefreshReleases, - onDownload = a.onDownloadDriver, onImport = a.onImportAndroid, onRestore = a.onRestoreBundled, - onBack = { driverPage = null }, - ) - return - } + androidx.compose.runtime.LaunchedEffect(Unit) { + // One frame first: the box has to be laid out before it can take focus. Opened from the + // cog, focus starts on the first control (Resolution) so the d-pad works at once. + androidx.compose.runtime.withFrameNanos { } + runCatching { firstChip.requestFocus() } } SettingsPage( host, @@ -209,6 +171,12 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { if (custom != null) "Set by the custom resolution." else "Auto uses at least 16:9.", com.droiddeck.launcher.session.SessionPrefs.shapeChoices, s.shapeMode, enabled = custom == null, onPick = a.onShape, ) + ChoiceRow( + host, "fps", "Frame limit", "Applies next session.", + com.droiddeck.launcher.session.SessionPrefs.fpsLimitChoices, s.fpsLimit, + note = "Caps the whole session. The screen switches to a rate the cap divides evenly.", + onPick = a.onFpsLimit, + ) if (editCustom) CustomResolutionDialog( initial = custom, onSave = { size -> editCustom = false; a.onCustomResolution(size) }, @@ -224,17 +192,8 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { ) } SettingsGroup("Drivers") { - SettingsRow("Runtime driver", (if (steam) "Used by Steam and games." else "Used by desktop apps.") + " Applies next session.") { - ValueChip( - s.linuxRows.firstOrNull { it.id == s.linuxSelected }?.name ?: "Runtime default", open = false, - modifier = androidx.compose.ui.Modifier.focusRequester(runtimeChip), - ) { openDriverPage("rt") } - } - SettingsRow("Display driver", "Used by the compositor in both modes. Restart the app to apply.") { - ValueChip( - s.androidRows.firstOrNull { it.id == s.androidSelected }?.name ?: "Auto - picked by GPU", open = false, - modifier = androidx.compose.ui.Modifier.focusRequester(displayChip), - ) { openDriverPage("panel") } + SettingsRow("GPU drivers", "Shared by Steam and the desktop, on the Components page.") { + ValueChip(s.gpuDrivers, open = false) { a.onGpuDrivers() } } } SettingsGroup(if (steam) "Touch & controls" else "Touch") { @@ -254,6 +213,16 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { ), s.oscMode, note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc, ) + if (steam && s.steamController != null) ChoiceRow( + host, "controller", "Controller", "What your controller is to Steam. Applies next session.", + listOf( + SessionPrefs.CONTROLLER_DECK to "Steam Deck controller", + SessionPrefs.CONTROLLER_XBOX360 to "Xbox 360 controller", + ), s.steamController, + note = "Steam Deck controller: Steam reads it as a Deck's own, with its Quick Access button and the device's gyro. " + + "Xbox 360 controller: the plain pad of earlier versions; Quick Access opens with Guide+A.", + onPick = a.onSteamController, + ) if (steam) ChoiceRow( host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted), listOf( @@ -336,10 +305,22 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { } } if (steam && s.steamChannel != null) SettingsGroup("Client") { - ChoiceRow( + ToggleRow( + host, "steamdeck", "Steam Deck mode", + "Enables Steam's Deck interface and Quick Access performance overlay controls. Applies next session.", + s.steamDeckMode, onChange = a.onSteamDeckMode, + ) + if (s.steamDeckMode) ToggleRow( + host, "mangoapp", "Performance overlay", + "The Quick Access Menu's frame-rate and usage overlay. Turn off if games crash or go black with Deck mode on. Applies next session.", + s.mangoapp, onChange = a.onMangoapp, + ) + // Deck mode fixes the branch (SessionPrefs.steamChannel); the choice is for Deck mode off. + if (s.steamDeckMode) SettingsRow("Client branch", "Steam Deck public beta: Deck mode needs it, so Steam doesn't keep offering an update") {} + else ChoiceRow( host, "channel", "Client branch", "The Steam client build the session forces. Applies at the next session start; the client may update itself once.", listOf("publicbeta" to "Public beta", "steamdeck_publicbeta" to "Steam Deck public beta"), s.steamChannel, - note = "Public beta is what every session ran on before. Steam Deck public beta is the channel Deck mode needs (on public beta it reinstalls the same client at every start) and the one Armada bootstraps from; Deck mode picks it unless you choose here.", + note = "Public beta is what every session ran on before. Steam Deck public beta is the one Armada bootstraps from, and the one Deck mode always uses.", onPick = a.onSteamChannel, ) } @@ -347,13 +328,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { for (dir in s.addedGamesDirs) { val n = s.addedGames.count { it.folderPath.startsWith("$dir/") } ActionRow( - dir.substringAfterLast('/').ifEmpty { dir }, dir + " · " + (if (n == 0) "no game folders with a .exe found" else "$n game${if (n == 1) "" else "s"}") + ". Forget: the games leave the client's library at the next session start; nothing on disk is touched.", + dir.substringAfterLast('/').ifEmpty { dir }, dir + " · " + (if (n == 0) "no game folders with a .exe found" else "$n game${if (n == 1) "" else "s"}") + ". " + stringResource(R.string.added_games_forget_hint), "Forget", onClick = { a.onForgetAddedGamesDir(dir) }, ) } ActionRow( if (s.addedGamesDirs.isEmpty()) "Games folder" else "Another games folder", - "Your own Windows games, one subfolder each, anywhere: internal storage, the SD card, a USB drive. As many folders as you like. Each game goes into the client's library as a non-Steam game under the ARM64 Proton, at the next session start.", + stringResource(R.string.added_games_import_hint), "Add…", onClick = a.onPickAddedGamesDir, ) ToggleRow( @@ -368,12 +349,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) }, ) } - if (steam && s.fexPreset != null) SettingsGroup("Games") { + if (steam && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) { ChoiceRow( - host, "fex", "FEX preset", "Applies on next game launch.", - FexPreset.all.map { it.id to it.label }, s.fexPreset, - note = FexPreset.byId(s.fexPreset).detail, onPick = a.onFexPreset, + host, "fex", stringResource(R.string.fex_preset_title), stringResource(R.string.fex_next_launch), + FexPreset.all.map { it.id to stringResource(it.label) }, s.fexPreset, + note = stringResource(FexPreset.byId(s.fexPreset).detail), onPick = a.onFexPreset, ) + GameEnvironmentRow() if (s.forceFullscreen != null) ToggleRow( host, "fill", "Stretch games to fill the screen", "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.", @@ -400,7 +382,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { val open = host.open == "storage" SettingsRow( "Second library", - "Adds a library location in Steam. Applies next session.", + stringResource(R.string.second_library_import_hint), highlighted = open, ) { androidx.compose.foundation.layout.Box { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt index ad3b34405..3f7a03558 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt @@ -202,12 +202,11 @@ private fun RowScope.KeyCap( else -> Color.White.copy(alpha = 0.07f) }, label = "keyFill", ) - val edge = if (focused) pal.signal else if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f) Box( contentAlignment = Alignment.Center, modifier = modifier.weight(weight).fillMaxHeight() .background(fill, RoundedCornerShape(7.dp)) - .border(if (focused) 2.dp else 1.dp, edge, RoundedCornerShape(7.dp)) + .glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f)) .pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume() @@ -244,7 +243,7 @@ private fun HeaderButton(text: String, onClick: () -> Unit) { contentAlignment = Alignment.Center, modifier = Modifier.fillMaxHeight() .background(Color.White.copy(alpha = 0.08f), RoundedCornerShape(7.dp)) - .border(if (focused) 2.dp else 1.dp, if (focused) pal.signal else Color.White.copy(alpha = 0.14f), RoundedCornerShape(7.dp)) + .glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, Color.White.copy(alpha = 0.14f)) .clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) .padding(horizontal = 12.dp), ) { Text(text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = Color.White) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt index 7fac4329b..fb441ef06 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt @@ -7,15 +7,22 @@ import androidx.compose.foundation.layout.Spacer 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.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.session.SessionPrefs class CoreRow(val core: Int, val label: String) @@ -29,18 +36,22 @@ fun PerformancePage( zinkLazy: Boolean, glThread: Boolean, noGlError: Boolean, - steamDeckMode: Boolean, noXalia: Boolean, + gamescopeRealtime: Boolean, + gpuClockPin: Boolean, prootNoSeccomp: Boolean, + guestHostname: String, phantomWarning: String?, onClientOverride: (Boolean) -> Unit, onTuSysmem: (Boolean) -> Unit, onZinkLazy: (Boolean) -> Unit, onGlThread: (Boolean) -> Unit, onNoGlError: (Boolean) -> Unit, - onSteamDeckMode: (Boolean) -> Unit, onNoXalia: (Boolean) -> Unit, + onGamescopeRealtime: (Boolean) -> Unit, + onGpuClockPin: (Boolean) -> Unit, onProotNoSeccomp: (Boolean) -> Unit, + onGuestHostname: (String) -> Unit, onClientCore: (Int, Boolean) -> Unit, onGameCore: (Int, Boolean) -> Unit, onDismiss: () -> Unit, @@ -50,7 +61,7 @@ fun PerformancePage( val coreItems = cores.map { it.core to it.label } SettingsPage( host, title = "Performance", - lede = "CPU cores and session fixes. Applies next session.", + lede = "CPU cores, session fixes and the host name. Applies next session.", onBack = onDismiss, ) { SettingsGroup("Steam client cores") { @@ -79,7 +90,7 @@ fun PerformancePage( ) ToggleRow( host, "zink", "Zink: lazy descriptors", - "Recommended for drivers without descriptor buffers.", + "Lazy, compact descriptors. Recommended for drivers without descriptor buffers.", zinkLazy, onChange = onZinkLazy, ) ToggleRow( @@ -88,20 +99,27 @@ fun PerformancePage( noGlError, onChange = onNoGlError, ) ToggleRow( - host, "deck", "Steam Deck mode", - "Runs the client with -droiddeck. SteamOS helpers and battery info are provided.", - steamDeckMode, onChange = onSteamDeckMode, + host, "gsrealtime", "gamescope: realtime GPU queue", + "Gives the compositor's GPU work priority over the game's. Can smooth frame pacing, but can cost games GPU time.", + gamescopeRealtime, onChange = onGamescopeRealtime, + ) + } + SettingsGroup("GPU") { + ToggleRow( + host, "gpuclock", "Hold the GPU at its top clock", + "Adreno only. Fewer hitches from the clock ramping up, at the cost of battery and heat. Released when the session ends.", + gpuClockPin, onChange = onGpuClockPin, ) } SettingsGroup("Session fixes") { ToggleRow( host, "sysmem", "Turnip: sysmem rendering", - "Required on Adreno 710/720/722. May fix corruption on other Adreno GPUs, but can reduce performance.", + "On by default: faster for the Steam interface and most games. Required on Adreno 710/720/722.", tuSysmem, onChange = onTuSysmem, ) ToggleRow( host, "xalia", "Skip Steam's xalia helper", - "Disables Proton's gamepad navigation helper. Try if sessions crash at startup.", + "Disables Proton's gamepad navigation helper, which costs every game CPU time. Turn off only if a game needs it.", noXalia, onChange = onNoXalia, ) ToggleRow( @@ -110,6 +128,25 @@ fun PerformancePage( prootNoSeccomp, onChange = onProotNoSeccomp, ) } + SettingsGroup("Session identity") { + var draft by remember(guestHostname) { mutableStateOf(guestHostname) } + val valid = SessionPrefs.validGuestHostname(draft) != null + SettingsRow( + "Host name", + if (valid || draft.isBlank()) "What the session and Steam report as this machine's name. Blank restores ${SessionPrefs.DEFAULT_GUEST_HOSTNAME}." + else "Letters, digits and inner hyphens only, up to 63 characters. Not saved until it is valid.", + ) { + OutlinedTextField( + draft, { v -> + draft = v.take(63) + if (draft.isBlank() || SessionPrefs.validGuestHostname(draft) != null) onGuestHostname(draft) + }, + singleLine = true, isError = !valid && draft.isNotBlank(), + placeholder = { Text(SessionPrefs.DEFAULT_GUEST_HOSTNAME) }, + modifier = Modifier.width(220.dp), + ) + } + } if (phantomWarning != null) { Spacer(Modifier.height(16.dp)) Column( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt index 36d880365..cae45fa48 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -1,64 +1,96 @@ package com.droiddeck.launcher.ui +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Build import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable -import androidx.compose.ui.text.font.FontFamily +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +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.platform.LocalContext +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.core.PhantomProcessLimit import com.droiddeck.launcher.core.PhantomProcessStatus +import com.droiddeck.launcher.core.WirelessAdbPairingService +import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage @Composable fun PhantomProcessGatePage( status: PhantomProcessStatus, onDismiss: () -> Unit, onOpenDeveloperOptions: () -> Unit, - onSetUpWirelessAdb: () -> Unit, + onFixWithWirelessDebugging: () -> Unit, + onEnterAddressManually: () -> Unit, + onCopyCommand: () -> Unit, + onOpenNotificationSettings: () -> Unit, ) { BackHandler(onBack = onDismiss) + val context = LocalContext.current + val stage by WirelessAdbPairingService.stage.collectAsState() + val environment by produceState(GateEnvironment.read(context)) { + while (true) { + value = GateEnvironment.read(context) + kotlinx.coroutines.delay(2_000) + } + } + val hasToggle = PhantomProcessLimit.hasDeveloperToggle() BoxWithConstraints(Modifier.fillMaxWidth()) { val compact = maxWidth < 620.dp && maxHeight < 500.dp SettingsPage( host = rememberMenuHost(), - title = if (compact) "Steam paused" else "Steam cannot start yet", + title = "One Android setting to change", eyebrow = "Steam", - lede = if (compact) compactStatus(status) else "${PhantomProcessLimit.title(status)} · checking again every two seconds", + lede = if (compact) null else "Android stops apps that start lots of background processes, and Steam starts dozens. " + + "Until this is changed, games close with no error.", onBack = onDismiss, - // Scrolls, so the larger text never pushes the ADB command off a short screen. scrollContent = true, compactLayout = compact, ) { BoxWithConstraints(Modifier.fillMaxWidth()) { val wide = maxWidth >= 620.dp - Column( - modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - when { - compact -> CompactGateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb) - wide -> Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) { - Column(Modifier.weight(1f)) { - GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb) - } - Column(Modifier.weight(1f)) { AdbFallback() } - } - else -> { - GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb) - AdbFallback() - } + val fix: @Composable ColumnScope.() -> Unit = { + FixGroup(hasToggle, stage, environment, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, + onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) }) + } + val side: @Composable ColumnScope.() -> Unit = { + StatusGroup(status, compact) + OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand) + } + if (wide) { + Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) { + Column(Modifier.weight(1.2f), content = fix) + Column(Modifier.weight(1f), content = side) + } + } else { + Column(Modifier.widthIn(max = 600.dp).fillMaxWidth()) { + fix() + side() } } } @@ -66,97 +98,168 @@ fun PhantomProcessGatePage( } } -private fun compactStatus(status: PhantomProcessStatus): String { - val state = when (status) { - PhantomProcessStatus.ENABLED -> "Child-process limit is on" - PhantomProcessStatus.UNSET -> "Child-process limit is unset" - PhantomProcessStatus.UNREADABLE -> "Child-process limit is unreadable" - else -> PhantomProcessLimit.title(status) +private data class GateEnvironment(val onWifi: Boolean, val notifications: Boolean) { + companion object { + fun read(context: Context): GateEnvironment { + val connectivity = context.getSystemService(ConnectivityManager::class.java) + val wifi = runCatching { + connectivity?.getNetworkCapabilities(connectivity.activeNetwork) + ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true + }.getOrDefault(true) + return GateEnvironment(wifi, WirelessAdbPairingService.notificationsEnabled(context)) + } } - return "$state · retrying every 2 sec" } @Composable -private fun CompactGateInstructions( - status: PhantomProcessStatus, +private fun FixGroup( + hasToggle: Boolean, + stage: Stage, + environment: GateEnvironment, + compact: Boolean, onOpenDeveloperOptions: () -> Unit, - onSetUpWirelessAdb: () -> Unit, + onFixWithWirelessDebugging: () -> Unit, + onOpenNotificationSettings: () -> Unit, + onCancel: () -> Unit, ) { - SettingsGroup("1 · Developer options", compact = true) { + val pairing = stage is Stage.Waiting || stage is Stage.CodeNeeded || stage is Stage.Working + SettingsGroup(if (hasToggle) "Developer options" else "Fix it for me", compact = compact) { Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp), - verticalArrangement = Arrangement.spacedBy(5.dp), + modifier = Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), ) { - Text( - PhantomProcessLimit.gateInstructions(status), - style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { - PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions) - SecondaryButton("Use Wireless debugging", compact = true, onClick = onSetUpWirelessAdb) + when { + pairing -> PairingProgress(stage, onCancel) + hasToggle -> { + Body("Turn on “Disable child process restrictions”, then come back. Keep Developer options on afterwards: turning them off turns the switch back off.") + PrimaryButton("Open Developer options", compact = compact, onClick = onOpenDeveloperOptions) + } + else -> { + Body("This Android version has no switch for it, so DroidDeck changes it over Wireless debugging on this device. About a minute, no computer needed.") + (stage as? Stage.Failed)?.let { Body(it.error, error = true) } + PrimaryButton( + if (stage is Stage.Failed) "Try again" else "Fix it for me", + compact = compact, + enabled = environment.onWifi && environment.notifications, + onClick = onFixWithWirelessDebugging, + ) + } + } + if (!hasToggle && !pairing) { + if (!environment.onWifi) { + Body("Wireless debugging needs Wi-Fi. Connect to any network first; it doesn't need internet.", warn = true) + } + if (!environment.notifications) { + Body("The pairing code is entered in a notification. Allow notifications for DroidDeck, or use Other ways.", warn = true) + SecondaryButton("Allow notifications", compact = compact, onClick = onOpenNotificationSettings) + } } } } - SettingsGroup("3 · Computer ADB last resort", compact = true) { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp), - verticalArrangement = Arrangement.spacedBy(3.dp), - ) { - Text( - "If the setting is missing and Wireless debugging is unavailable, run this from a computer:", - style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - PhantomProcessLimit.ADB_COMMAND, - style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) +} + +@Composable +private fun PairingProgress(stage: Stage, onCancel: () -> Unit) { + val steps = listOf( + "Open Settings → Developer options → Wireless debugging and turn it on", + "Tap “Pair device with pairing code”", + "Type the code into the DroidDeck notification", + ) + val active = when (stage) { + Stage.Waiting -> 1 + is Stage.CodeNeeded -> 2 + else -> 3 + } + steps.forEachIndexed { index, step -> + val done = index < active + val current = index == active + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(if (done) "✓" else "${index + 1}", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, + color = if (done) LocalPalette.current.good else MaterialTheme.colorScheme.onSurfaceVariant) + Text(step, style = MaterialTheme.typography.bodySmall, + color = if (current) MaterialTheme.colorScheme.onBackground else MaterialTheme.colorScheme.onSurfaceVariant) + } + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + Text( + when (stage) { + Stage.Waiting -> "Waiting for the pairing pop-up…" + is Stage.CodeNeeded -> stage.error ?: "Pop-up found. Enter its code in the notification." + is Stage.Working -> stage.step + else -> "" + }, + style = MaterialTheme.typography.bodySmall, + color = if (stage is Stage.CodeNeeded && stage.error != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + SecondaryButton("Cancel", compact = true, onClick = onCancel) + } +} + +@Composable +private fun StatusGroup(status: PhantomProcessStatus, compact: Boolean) { + SettingsGroup("Status", compact = compact) { + Column(Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(PhantomProcessLimit.title(status), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground) + Body("Checking every 2 seconds. This page closes when it's off.") } } } @Composable -private fun GateInstructions( - status: PhantomProcessStatus, +private fun OtherWays( + hasToggle: Boolean, + compact: Boolean, onOpenDeveloperOptions: () -> Unit, - onSetUpWirelessAdb: () -> Unit, + onFixWithWirelessDebugging: () -> Unit, + onEnterAddressManually: () -> Unit, + onCopyCommand: () -> Unit, ) { - SettingsGroup("1 · Developer options first") { - Column( - modifier = Modifier.fillMaxWidth().padding(14.dp), + var open by rememberSaveable { mutableStateOf(false) } + SettingsGroup("Other ways", compact = compact) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().clickable { open = !open }.padding(horizontal = 14.dp, vertical = 10.dp), + ) { + Body(if (hasToggle) "Wireless debugging, manual address, computer ADB" else "Manual address, computer ADB, Developer options", modifier = Modifier.weight(1f)) + Text(if (open) "▴" else "▾", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + if (open) Column( + modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { + if (hasToggle) { + SecondaryButton("Use Wireless debugging instead", compact = true, onClick = onFixWithWirelessDebugging) + } else { + Body("Some ROMs add the switch anyway. Look for “child process” in Developer options.") + SecondaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions) + } + Body("If the notification doesn't work, enter the pop-up's address and code yourself.") + SecondaryButton("Enter address manually", compact = true, onClick = onEnterAddressManually) + Body("From a computer with ADB:") Text( - PhantomProcessLimit.gateInstructions(status), + PhantomProcessLimit.adbCommand(), + style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp), color = MaterialTheme.colorScheme.onSurfaceVariant, ) - PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions) - SecondaryButton("Use Wireless debugging", onClick = onSetUpWirelessAdb) + SecondaryButton("Copy command", compact = true, onClick = onCopyCommand) } } } @Composable -private fun AdbFallback() { - SettingsGroup("3 · Computer ADB last resort") { - Column( - modifier = Modifier.fillMaxWidth().padding(14.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - "Use this only if Developer options has no setting and Wireless debugging is unavailable. Connect this device to a computer with ADB and run:", - color = MaterialTheme.colorScheme.onSurfaceVariant, - style = MaterialTheme.typography.bodySmall, - ) - Text( - PhantomProcessLimit.ADB_COMMAND, - style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } +private fun Body(text: String, modifier: Modifier = Modifier, error: Boolean = false, warn: Boolean = false) { + Text( + text, + modifier = modifier, + style = MaterialTheme.typography.bodySmall, + color = when { + error -> MaterialTheme.colorScheme.error + warn -> androidx.compose.ui.graphics.Color(0xFFFFB86B) + else -> MaterialTheme.colorScheme.onSurfaceVariant + }, + ) } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 3a4bdb2ef..4ad50ed2e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -112,6 +112,7 @@ class SecondScreenPresentation( when (currentMode) { SecondScreenMode.KEYBOARD_TRACKPAD -> renderKeyboardAndTrackpad() SecondScreenMode.TERMINAL -> renderTerminal() + SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam), weightParams()) SecondScreenMode.NONE -> Unit } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index a9efc01c9..af38940f0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -1,6 +1,28 @@ package com.droiddeck.launcher.ui import androidx.compose.ui.draw.alpha +import androidx.compose.animation.core.Animatable +import androidx.compose.foundation.Canvas +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.util.lerp +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import kotlin.math.roundToInt +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.offset @@ -42,9 +64,7 @@ import androidx.compose.foundation.ScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment @@ -85,12 +105,19 @@ import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.InputMode import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.platform.LocalContext +import com.droiddeck.launcher.R import com.droiddeck.launcher.core.FexPreset import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.ComponentsManager import com.droiddeck.launcher.input.SecondScreenDisplay @@ -132,9 +159,8 @@ class DrawerActions( val isHomeApp: Boolean, val androidApps: List, val hudOn: Boolean, - val frameGenEngine: String, - val frameGenMultiplier: Int, - val lsfgReady: Boolean, + val frameGen: FrameGen.Mode, + val lossless: Lossless.State, val oscMode: String, val suspendPolicy: String, val backActionsInverted: Boolean, @@ -148,7 +174,8 @@ class DrawerActions( val secondScreenDisplays: List, val selectedSecondScreenDisplay: Int, val onHud: (Boolean) -> Unit, - val onFrameGenPick: (engine: String, multiplier: Int) -> Unit, + val onFrameGenPick: (FrameGen.Mode) -> Unit, + val onImportLossless: () -> Unit, /** The Android keyboard (text, turned into key presses). */ val onKeyboard: () -> Unit, /** The on-screen PC keyboard: real keys, Esc, F1-F12, Ctrl, Alt... */ @@ -170,6 +197,8 @@ class DrawerActions( val onBackground: () -> Unit, val onShareLogs: () -> Unit, val onStop: () -> Unit, + /** Stop with the dialog's button's bounds on screen, for the flood to grow out of; null falls back to [onStop]. */ + val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null, val onClose: () -> Unit, /** Components tab: every Proton with what it uses; null until first read. */ val components: ComponentsManager.Snapshot? = null, @@ -188,6 +217,8 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha var androidAppsExpanded by rememberSaveable { mutableStateOf(false) } var appToChooseDisplay by remember { mutableStateOf(null) } var confirmStop by remember { mutableStateOf(false) } + var sheetCoords by remember { mutableStateOf(null) } + var stopCoords by remember { mutableStateOf(null) } val pageScroll = remember { List(DRAWER_PAGES) { ScrollState(0) } } val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil") val focus = remember { DrawerFocus() } @@ -233,10 +264,10 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha enter = slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)), exit = slideOutHorizontally(Motion.tw(240)) { it } + fadeOut(Motion.tw(200)), ) { + FocusGlideHost(Modifier.fillMaxHeight().width(sheetWidth)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) { Column( modifier = Modifier - .fillMaxHeight() - .width(sheetWidth) + .fillMaxSize() .background(pal.background.copy(alpha = 0.97f)) .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} .focusGroup() @@ -248,7 +279,7 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().heightIn(min = if (short) 40.dp else 44.dp)) { Text(a.title ?: if (a.steam) "Steam" else "Desktop", fontSize = if (short) 18.sp else 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) - StopSessionButton(modifier = focus.track(page, "stop")) { host.open = null; confirmStop = true } + StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } } if (a.onSteamMenu != null && a.onQam != null) { val qamInteraction = remember { MutableInteractionSource() } @@ -316,11 +347,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen, ) val fgOpen = host.open == "fg" - val fgLabel = FrameGen.label(a.frameGenEngine, a.frameGenMultiplier) - SettingsRow("Frame generation", null, highlighted = fgOpen) { + val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) + SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) { Box { ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" } - FrameGenMenu(host, a.frameGenEngine, a.frameGenMultiplier, a.lsfgReady, a.onFrameGenPick) + FrameGenMenu(host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless) } } } @@ -350,7 +381,9 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha } if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") { ChoiceRow(host, "second-screen-mode", "Shows", null, - listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL).map { it to it.label }, + (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 }, 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, @@ -405,9 +438,12 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha ChoiceRow(host, "shape", "Screen ratio", null, SessionPrefs.shapeChoices, a.shapeMode, chipModifier = focus.track(page, "shape"), onPick = a.onShape) - if (a.steam) ChoiceRow(host, "fex", "FEX preset", null, - FexPreset.all.map { it.id to it.label }, a.fexPreset, + } + if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) { + ChoiceRow(host, "fex", stringResource(R.string.fex_preset_title), stringResource(R.string.fex_next_launch), + FexPreset.all.map { it.id to stringResource(it.label) }, a.fexPreset, chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset) + GameEnvironmentRow(modifier = focus.track(page, "game-env")) } SettingsGroup("Support") { SettingsRow("Session logs", "Send this session's logs with a bug report") { @@ -425,6 +461,18 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha } } } } + StopConfirm( + open = confirmStop, + pill = sheetCoords?.let { sc -> stopCoords?.takeIf { it.isAttached && sc.isAttached }?.let { sc.localBoundingBoxOf(it, clipBounds = false) } }, + controllerActive = controllerActive, + onCancel = { confirmStop = false }, + onStop = { onScreen -> + confirmStop = false + val from = a.onStopFrom + if (from != null) from(onScreen) else a.onStop() + }, + ) + } } } } @@ -445,33 +493,6 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha onDismiss = { appToChooseDisplay = null }, ) } - if (confirmStop) { - val cancelFocus = remember { FocusRequester() } - val cancel = { confirmStop = false } - val stop = { confirmStop = false; a.onStop() } - LaunchedEffect(controllerActive) { - if (controllerActive) { - androidx.compose.runtime.withFrameNanos { } - runCatching { cancelFocus.requestFocus() } - } - } - AlertDialog( - onDismissRequest = cancel, - modifier = Modifier.controllerBack(onBack = cancel), - title = { Text("Stop session?") }, - confirmButton = { - TextButton( - onClick = stop, - modifier = Modifier.controllerConfirm(onClick = stop), - colors = ButtonDefaults.textButtonColors(contentColor = colors.error), - ) { Text("Stop") } - }, - dismissButton = { - TextButton(onClick = cancel, modifier = Modifier.focusRequester(cancelFocus) - .controllerConfirm(onClick = cancel)) { Text("Cancel") } - }, - ) - } } @Composable @@ -501,7 +522,7 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier.heightIn(min = 44.dp).semantics { contentDescription = "Stop session" } - .clip(shape).background(fill).border(if (hot) 2.dp else 1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.55f), shape) + .clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f)) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick) .padding(start = 12.dp, end = 14.dp), @@ -526,7 +547,7 @@ private fun QuickAction( val shape = RoundedCornerShape(12.dp) val tile = modifier.height(if (compact) 44.dp else 64.dp).clip(shape) .background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface) - .border(if (hot) 2.dp else 1.dp, if (hot) pal.signal else pal.line, shape) + .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(interactionSource) .clickable(interactionSource = interactionSource, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onConfirm ?: onClick) @@ -557,7 +578,7 @@ private fun DrawerBumper(label: String, description: String, modifier: Modifier Box( contentAlignment = Alignment.Center, modifier = modifier.size(44.dp).clip(ring) - .border(2.dp, if (hot) pal.signal else Color.Transparent, ring) + .glideBorder(hot, ring, pal.signal) .hoverable(src).clickable(interactionSource = src, indication = null, onClick = onClick) .controllerConfirm(onClick = onClick) .semantics { contentDescription = description }, @@ -616,7 +637,7 @@ private fun DrawerPageTabs(page: Int, modifier: Modifier = Modifier, compact: Bo listOf(pal.signal.copy(alpha = 0.34f * glow), pal.signal.copy(alpha = 0.10f * glow), Color.Transparent), ), ) - .border(if (focused) 2.dp else 0.dp, if (focused) colors.onBackground else Color.Transparent, RoundedCornerShape(16.dp)) + .glideBorder(focused, RoundedCornerShape(16.dp), colors.onBackground) .semantics { contentDescription = "${drawerPageTitles[index]} page" } .hoverable(source) .clickable(interactionSource = source, indication = LocalIndication.current, onClick = select) @@ -765,3 +786,220 @@ private const val DRAWER_TAB_LEAN_DP = 12f private const val DRAWER_TAB_SIDE_SCALE = 0.5f private const val DRAWER_TAB_SIDE_ALPHA = 0.7f + +/** Room between the Stop pill and the box that steps out under it: the pull. */ +private val StepPull = 6.dp +private val StepBoxCorner = 16.dp +private val StepFillet = 10.dp +private val StepBoxMaxWidth = 264.dp + +/** + * The stair-step outline: the pill [p] on top, a box under it from [left] to the pill's right edge + * and down to [bottom], the pull between them [pullTop] (the box's top). Right edges are flush and + * the inside corner where the pull meets the box is rounded the other way. While the box is still + * no wider than the pill it is just the pill, stretched down. + */ +private fun stepPath(path: Path, p: Rect, left: Float, bottom: Float, pullTop: Float, box: Float, fillet: Float) { + path.reset() + val r = p.right; val tl = p.left; val tt = p.top + val pb = maxOf(bottom, p.bottom) + val l = minOf(left, tl) + val pt = minOf(pullTop, pb) + val sw = tl - l + val h = (pb - pt).coerceAtLeast(0f) + val rt = minOf(p.height / 2f, p.width / 2f) + val rbr = minOf(box, (pb - tt) / 2f) + val rbl = minOf(lerp(minOf(box, (pb - tt) / 2f), minOf(box, h / 2f), (sw / box).coerceIn(0f, 1f)), (r - l) / 2f) + val rpl = minOf(box, sw / 2f, h / 2f) + val f = minOf(fillet, sw / 2f) + val yl = minOf(pt + rpl, pb - rbl) + fun corner(rect: Rect, start: Float, sweep: Float, endX: Float, endY: Float) { + if (rect.width < 0.5f) path.lineTo(endX, endY) else path.arcTo(rect, start, sweep, false) + } + path.moveTo(tl + rt, tt) + path.lineTo(r - rt, tt) + corner(Rect(r - 2 * rt, tt, r, tt + 2 * rt), -90f, 90f, r, tt + rt) + path.lineTo(r, pb - rbr) + corner(Rect(r - 2 * rbr, pb - 2 * rbr, r, pb), 0f, 90f, r - rbr, pb) + path.lineTo(l + rbl, pb) + corner(Rect(l, pb - 2 * rbl, l + 2 * rbl, pb), 90f, 90f, l, pb - rbl) + path.lineTo(l, yl) + corner(Rect(l, pt, l + 2 * rpl, pt + 2 * rpl), 180f, 90f, l + rpl, pt) + path.lineTo(tl - f, pt) + corner(Rect(tl - 2 * f, pt - 2 * f, tl, pt), 90f, -90f, tl, pt - f) + path.lineTo(tl, tt + rt) + corner(Rect(tl, tt, tl + 2 * rt, tt + 2 * rt), 180f, 90f, tl + rt, tt) + path.close() +} + +/** + * Stop's confirm, grown out of the Stop pill at [pill] (px, in the sheet): a pull the pill's width + * drops out of it and a wider box steps out to the left under it for the choices, right edges + * flush, so Stop lands under the pill. Cancel, B and a tap outside fold it back into the pill, + * width first. [onStop] gets Stop's bounds on screen for the flood. + */ +@Composable +private fun StopConfirm( + open: Boolean, + pill: Rect?, + controllerActive: Boolean, + onCancel: () -> Unit, + onStop: (Rect?) -> Unit, +) { + val colors = MaterialTheme.colorScheme + val density = LocalDensity.current + val left = remember { Animatable(0f) } + val bottom = remember { Animatable(0f) } + val tint = remember { Animatable(0f) } + val dim = remember { Animatable(0f) } + val items = remember { List(3) { Animatable(0f) } } + // Composed from the first open until it has folded back into the pill. + var shown by remember { mutableStateOf(false) } + var grown by remember { mutableStateOf(false) } + var content by remember { mutableStateOf(null) } + val cancelFocus = remember { FocusRequester() } + var stopFocused by remember { mutableStateOf(false) } + var cancelFocused by remember { mutableStateOf(false) } + var stopCoords by remember { mutableStateOf(null) } + val view = LocalView.current + if (!open && !shown) return + val pull = with(density) { StepPull.toPx() } + + LaunchedEffect(open, pill, content) { + val p = pill ?: return@LaunchedEffect + val c = content ?: return@LaunchedEffect + val boxLeft = (p.right - c.width).coerceAtLeast(0f) + val boxBottom = p.bottom + pull + c.height + if (open) { + shown = true + if (!grown) { + left.snapTo(p.left); bottom.snapTo(p.bottom); tint.snapTo(0f) + items.forEach { it.snapTo(0f) } + grown = true + } + coroutineScope { + launch { dim.animateTo(1f, Motion.tw(260)) } + launch { tint.animateTo(1f, Motion.tw(200)) } + launch { bottom.animateTo(boxBottom, Motion.sp(0.7f, 380f)) } + launch { delay(Motion.ms(110).toLong()); left.animateTo(boxLeft, Motion.sp(0.55f, 300f)) } + items.forEachIndexed { i, a -> + launch { delay(Motion.ms(260 + i * 55).toLong()); a.animateTo(1f, Motion.tw(220)) } + } + if (controllerActive) launch { + delay(Motion.ms(300).toLong()) + withFrameNanos { } + runCatching { cancelFocus.requestFocus() } + } + } + } else if (grown) { + coroutineScope { + items.forEach { launch { it.animateTo(0f, Motion.tw(90)) } } + launch { delay(Motion.ms(60).toLong()); dim.animateTo(0f, Motion.tw(300)) } + launch { delay(Motion.ms(60).toLong()); left.animateTo(p.left, Motion.sp(1f, 420f)) } + launch { delay(Motion.ms(160).toLong()); bottom.animateTo(p.bottom, Motion.sp(1f, 380f)) } + launch { delay(Motion.ms(200).toLong()); tint.animateTo(0f, Motion.tw(200)) } + } + grown = false + shown = false + content = null + } + } + val p = pill ?: return + + Box(Modifier.fillMaxSize()) { + // The rest of the sheet dims behind it, and a tap there cancels. + Box( + Modifier.fillMaxSize().graphicsLayer { alpha = dim.value }.background(Color(0x59000000)) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, enabled = open, onClick = onCancel), + ) + val path = remember { Path() } + val boxCorner = with(density) { StepBoxCorner.toPx() } + val fillet = with(density) { StepFillet.toPx() } + val rim = with(density) { 1.4.dp.toPx() } + val restFill = colors.surface + val hotFill = lerp(colors.surface, colors.error, 0.22f) + Canvas(Modifier.fillMaxSize()) { + if (!grown) return@Canvas + stepPath(path, p, left.value, bottom.value, p.bottom + pull, boxCorner, fillet) + drawPath(path, lerp(hotFill, restFill, tint.value)) + drawPath(path, colors.error.copy(alpha = lerp(0.9f, 0.55f, tint.value)), style = Stroke(rim)) + } + // The pill's label rides on top, as the pull's handle. + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.offset { IntOffset(p.left.roundToInt(), p.top.roundToInt()) } + .size(with(density) { p.width.toDp() }, with(density) { p.height.toDp() }) + .padding(start = 12.dp, end = 14.dp), + ) { + Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp)) + Text("Stop", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error) + } + val maxW = with(density) { StepBoxMaxWidth.toPx() }.coerceAtMost(p.right) + Column( + modifier = Modifier + .offset { IntOffset((p.right - (content?.width ?: maxW.roundToInt())).roundToInt(), (p.bottom + pull).roundToInt()) } + .width(with(density) { maxW.toDp() }) + .onSizeChanged { if (content != it) content = it } + .controllerBack(onCancel) + .onPreviewKeyEvent { e -> + // Keep a controller in here, as the dialog's own window used to. + if (e.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false + when (e.key) { + Key.DirectionUp, Key.DirectionDown -> true + Key.DirectionLeft -> cancelFocused + Key.DirectionRight -> stopFocused + else -> false + } + } + .padding(start = 18.dp, end = 12.dp, top = 14.dp, bottom = 12.dp), + ) { + Text( + "Stop session?", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, + modifier = Modifier.graphicsLayer { alpha = items[0].value; translationY = (1f - items[0].value) * 6.dp.toPx() }, + ) + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + modifier = Modifier.fillMaxWidth().padding(top = 14.dp), + ) { + ConfirmChoice( + "Cancel", danger = false, enabled = open, + modifier = Modifier.graphicsLayer { alpha = items[1].value; translationY = (1f - items[1].value) * 6.dp.toPx() } + .focusRequester(cancelFocus).onFocusChanged { cancelFocused = it.isFocused }, + onClick = onCancel, + ) + ConfirmChoice( + "Stop", danger = true, enabled = open, + modifier = Modifier.graphicsLayer { alpha = items[2].value; translationY = (1f - items[2].value) * 6.dp.toPx() } + .onFocusChanged { stopFocused = it.isFocused } + .onGloballyPositioned { stopCoords = it }, + ) { + val at = IntArray(2).also { view.rootView.getLocationOnScreen(it) } + onStop(stopCoords?.takeIf { it.isAttached }?.boundsInWindow()?.translate(at[0].toFloat(), at[1].toFloat())) + } + } + } + } +} + +/** One of the confirm's two choices: a capsule that fills when focused; Stop in the danger red. */ +@Composable +private fun ConfirmChoice(label: String, danger: Boolean, enabled: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value + val shape = RoundedCornerShape(20.dp) + val accent = if (danger) colors.error else pal.signal + Box( + contentAlignment = Alignment.Center, + modifier = modifier.heightIn(min = 40.dp).clip(shape) + .background(if (hot) accent.copy(alpha = if (danger) 0.18f else 0.14f) else Color.Transparent) + .glideBorder(hot, shape, accent) + .hoverable(src) + .clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) + .padding(horizontal = 16.dp), + ) { + Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (danger) colors.error else colors.onBackground) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 1b36b1c4b..b332958d4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -148,7 +148,7 @@ internal fun TabStrip( .then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier) .clip(tabShape) .background(if (on) pal.signal else if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent) - .border(2.dp, if (!hot) Color.Transparent else if (on) colors.onBackground else pal.signal, tabShape) + .glideBorder(hot, tabShape, if (on) colors.onBackground else pal.signal) .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Tab, onClick = pick) .controllerConfirm(onClick = pick) .padding(horizontal = 16.dp, vertical = 12.dp), @@ -297,7 +297,6 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value val pal = LocalPalette.current - val edge by animateColorAsState(if (open || hot) pal.signal else pal.line2, Motion.tw(200), label = "chipEdge") val rot by animateFloatAsState(if (open) 180f else 0f, Motion.sp(0.6f), label = "chipCaret") Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, @@ -306,7 +305,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo .heightIn(min = 44.dp) .clip(RoundedCornerShape(10.dp)) .background(colors.surfaceVariant) - .border(1.dp, edge, RoundedCornerShape(10.dp)) + .glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, if (open) pal.signal else pal.line2) .alpha(if (enabled) 1f else 0.5f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) @@ -400,7 +399,6 @@ fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = nul val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value val track by animateColorAsState(if (checked) pal.signal else colors.surfaceVariant, Motion.tw(180), label = "switchTrack") - val edge by animateColorAsState(if (hot) pal.signal else if (checked) pal.signal else pal.line2, Motion.tw(180), label = "switchEdge") val knob by animateFloatAsState(if (checked) 1f else 0f, Motion.sp(0.7f), label = "switchKnob") val flip = { onChange(!checked) } val shape = RoundedCornerShape(99.dp) @@ -417,7 +415,7 @@ fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = nul ) { Box( Modifier.size(width = 52.dp, height = 30.dp).clip(shape).background(track) - .border(if (hot) 2.dp else 1.dp, if (hot && checked) colors.onBackground else edge, shape), + .glideBorder(hot, shape, if (checked) colors.onBackground else pal.signal, if (checked) pal.signal else pal.line2), ) { Box( Modifier.padding(4.dp).size(22.dp) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt new file mode 100644 index 000000000..5c6002f68 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt @@ -0,0 +1,556 @@ +package com.droiddeck.launcher.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Apps +import androidx.compose.material.icons.outlined.Verified +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.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.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +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.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import coil.compose.AsyncImage +import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.store.FlathubApi +import com.droiddeck.launcher.store.StoreState + +// The Store rail section: Flathub's apps for this device's architecture, installed into the +// Linux runtime with Flatpak, and the ones already installed. + +private val TABS = listOf("Discover", "Search", "Installed") + +@Composable +internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { + val ctx = LocalContext.current + val narrow = LocalNarrowPane.current + val padH = if (narrow) 16.dp else 22.dp + val padV = if (narrow) 12.dp else 18.dp + var tab by rememberSaveable { mutableStateOf(0) } + var openApp by rememberSaveable { mutableStateOf(null) } + var query by rememberSaveable { mutableStateOf("") } + var category by rememberSaveable { mutableStateOf(null) } + 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, + // a tab's contents - and would be lost with it. Each move says where focus goes next. + val ff = LocalFrontFocus.current + val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current + val tabFocus = remember { List(TABS.size) { androidx.compose.ui.focus.FocusRequester() } } + var focusMove by remember { mutableStateOf?>(null) } + var lastApp by remember { mutableStateOf(null) } + fun closeApp() { lastApp = openApp; openApp = null; focusMove = "tile" to (focusMove?.second ?: 0) + 1 } + fun switchTab(to: Int) { tab = to; focusMove = "tab" to (focusMove?.second ?: 0) + 1 } + BackHandler(enabled = openApp != null) { closeApp() } + val scroll = rememberScrollState() + LaunchedEffect(openApp, tab) { scroll.scrollTo(0) } + LaunchedEffect(focusMove, openApp) { + if (inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect + val target = when { + openApp != null -> ff?.primary + focusMove?.first == "tile" -> lastApp?.let { ff?.items?.get("tile:store:$it") } ?: tabFocus[tab] + focusMove?.first == "tab" -> tabFocus[tab] + else -> null + } ?: return@LaunchedEffect + var landed = false + focusWithinFrames({ landed }) { target.also { landed = runCatching { it.requestFocus() }.isSuccess } } + } + Column( + modifier = modifier.verticalScroll(scroll).padding(horizontal = padH, vertical = padV) + .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) { + AppDetail(s, a, id) { closeApp() } + return@Column + } + Rise(0) { + PageHeader("Store") { + Chip("Flathub · ARM64", ok = false) + if (StoreState.ready) Chip("● Flatpak ready", ok = true) + } + } + if (!s.ready) { + Rise(1) { Note("Install the Linux runtime from Setup first; the store installs apps into it.") } + return@Column + } + if (!StoreState.ready) Rise(1) { SetupCard() } + Rise(2) { + TabStrip( + TABS.mapIndexed { i, t -> if (i == 2 && StoreState.installed.isNotEmpty()) "$t · ${StoreState.installed.size}" else t }, + tab, { switchTab(it) }, modifier = Modifier.padding(top = 14.dp, bottom = 4.dp), focusRequesters = tabFocus, + ) + } + BusyBar() + when (tab) { + 0 -> Discover(onOpen = { openApp = it }, onCategory = { category = it; query = ""; tab = 1; StoreState.search("", it) }) + 1 -> Search(query, category, { query = it }, { category = it }, onOpen = { openApp = it }) + else -> Installed(a, onOpen = { openApp = it }) + } + } +} + +/** Flatpak is not in the runtime yet: one button puts it there. */ +@Composable +private fun SetupCard() { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val busy = StoreState.busy == "setup" + 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("Set up Flatpak", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + Text( + "Adds Flatpak to the Linux runtime and connects it to Flathub, about 20 MB. Apps then install " + + "with the runtimes they need; the first one is the biggest download.", + fontSize = 14.sp, color = colors.onSurfaceVariant, + ) + Actions { + PrimaryButton(if (busy) "Setting up…" else "Set up Flatpak", enabled = StoreState.busy == null, main = true) { StoreState.setup(ctx) } + } + } +} + +/** The running install, update or setup, whichever page it was started from. */ +@Composable +private fun BusyBar() { + val colors = MaterialTheme.colorScheme + val busy = StoreState.busy ?: return + val name = StoreState.installed.firstOrNull { it.id == busy }?.name ?: StoreState.details[busy]?.name + ?: when (busy) { "setup" -> "Flatpak"; "update-all" -> "Updates"; else -> busy.substringAfterLast('.') } + Column(modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 4.dp)) { + val stage = StoreState.stage + Text( + "$name · " + (if (stage != null && StoreState.percent >= 0) "$stage · ${StoreState.percent}%" else stage ?: "Starting…"), + fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(bottom = 6.dp), + ) + if (StoreState.percent >= 0) LinearProgressIndicator(progress = { StoreState.percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp)) + else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp)) + } +} + +@Composable +private fun Discover(onOpen: (String) -> Unit, onCategory: (String) -> Unit) { + Rise(3) { SectionTitle("Categories", null) } + Rise(3) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(vertical = 4.dp)) { + FlathubApi.categories.forEach { c -> PillButton(c.label, selected = false) { onCategory(c.id) } } + } + } + if (StoreState.sectionsFailed && StoreState.sections.values.all { it.isEmpty() }) { + Rise(4) { Note("Flathub could not be reached. Check the connection and open the Store again.") } + Actions { SecondaryButton("Try again") { StoreState.loadSections(force = true) } } + return + } + StoreState.SECTIONS.forEachIndexed { i, (key, title) -> + val apps = StoreState.sections[key] + Rise(4 + i) { SectionTitle(title, apps?.let { if (it.isEmpty()) null else it.size.toString() } ?: "loading…") } + if (apps != null && apps.isNotEmpty()) Rise(4 + i) { AppGrid(apps.take(12), first = i == 0, onOpen = onOpen) } + } +} + +@Composable +private fun Search(query: String, category: String?, onQuery: (String) -> Unit, onCategory: (String?) -> Unit, onOpen: (String) -> Unit) { + val view = androidx.compose.ui.platform.LocalView.current + val run = { + // The field is an Android EditText; Done leaves its keyboard over the results otherwise. + (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(view.windowToken, 0) + StoreState.search(query.trim(), category) + } + Rise(3) { + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 12.dp)) { + AdbTextField( + value = query, onValueChange = onQuery, label = "Search Flathub", keyboardType = KeyboardType.Text, + imeAction = ImeAction.Done, placeholder = "Firefox, games, emulators…", modifier = Modifier.weight(1f), onDone = run, + ) + PrimaryButton("Search", main = true, onClick = run) + } + } + Rise(4) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(top = 12.dp, bottom = 4.dp)) { + PillButton("All", selected = category == null) { onCategory(null); StoreState.search(query.trim(), null) } + FlathubApi.categories.forEach { c -> + PillButton(c.label, selected = category == c.id) { onCategory(c.id); StoreState.search(query.trim(), c.id) } + } + } + } + val results = StoreState.searchResults + when { + StoreState.searching -> Rise(5) { SectionTitle("Searching…", null) } + results == null -> Rise(5) { Note("Search Flathub by name, or pick a category. Only apps built for ARM64 are listed.") } + results.isEmpty() -> Rise(5) { Note("Nothing on Flathub for ARM64 matches that.") } + else -> { + Rise(5) { SectionTitle("Results", results.size.toString()) } + Rise(6) { AppGrid(results, first = true, onOpen = onOpen) } + } + } +} + +@Composable +private fun Installed(a: FrontEndActions, onOpen: (String) -> Unit) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val apps = StoreState.installed + Rise(3) { + Actions { + SecondaryButton(if (StoreState.checkingUpdates) "Checking…" else "Check for updates", enabled = StoreState.ready && !StoreState.checkingUpdates && StoreState.busy == null) { + StoreState.checkUpdates(ctx) + } + if (StoreState.updates.isNotEmpty()) PrimaryButton("Update all (${StoreState.updates.size})", enabled = StoreState.busy == null) { + StoreState.update(ctx, null, "Updates") + } else if (StoreState.updatesChecked && !StoreState.checkingUpdates) ActionChip("● Everything is up to date", ok = true) + } + } + if (apps.isEmpty()) { + Rise(4) { Box(Modifier.padding(top = 12.dp)) { Note(if (StoreState.ready) "No apps yet. Find some under Discover or Search." else "Set up Flatpak to install apps.") } } + return + } + Rise(4) { SectionTitle("Installed", apps.size.toString()) } + Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + apps.forEachIndexed { i, app -> + key(app.id) { + Rise(5 + i.coerceAtMost(6)) { + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(horizontal = 12.dp, vertical = 10.dp), + ) { + AppIcon(app.icon ?: StoreState.details[app.id]?.icon ?: FlathubApi.iconUrl(app.id), app.name, 44) + Column(modifier = Modifier.weight(1f)) { + Text(app.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + (if (app.id in StoreState.updates) "Update available · " else "") + (app.summary ?: app.id), + fontSize = 13.sp, color = if (app.id in StoreState.updates) pal.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + PrimaryButton("Open", compact = true, enabled = !s_busyFor(app.id)) { a.onFlatpakApp(app.id, app.name) } + if (app.id in StoreState.updates) SecondaryButton("Update", compact = true, enabled = StoreState.busy == null) { StoreState.update(ctx, app.id, app.name) } + SecondaryButton("Details", compact = true) { onOpen(app.id) } + } + } + } + } + } +} + +private fun s_busyFor(id: String) = StoreState.busy == id + +@Composable +private fun AppDetail(s: FrontEndState, a: FrontEndActions, id: String, onBack: () -> Unit) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val narrow = LocalNarrowPane.current + LaunchedEffect(id) { StoreState.loadDetails(id) } + val d = StoreState.details[id] + val local = StoreState.installed.firstOrNull { it.id == id } + val name = d?.name ?: local?.name ?: id + Rise(0) { BackLink("Store", onClick = onBack) } + Rise(1) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.padding(top = 12.dp, bottom = 8.dp)) { + AppIcon(d?.icon ?: local?.icon ?: FlathubApi.iconUrl(id), name, 72) + Column(modifier = Modifier.weight(1f)) { + Text(name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis) + d?.developer?.let { Text(it, fontSize = 14.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) } + (d?.summary ?: local?.summary)?.let { Text(it, fontSize = 14.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp)) } + } + } + } + val busyHere = StoreState.busy == id + val installed = local != null + // Remove asks twice: one stray press of A should not cost a download. The second press has + // to come within a few seconds; the app's own data in ~/.var/app stays either way. + var confirmRemove by remember(id) { mutableStateOf(false) } + LaunchedEffect(confirmRemove) { if (confirmRemove) { kotlinx.coroutines.delay(4000); confirmRemove = false } } + Rise(2) { + Actions { + if (installed) { + PrimaryButton("Open", enabled = !busyHere, main = true) { a.onFlatpakApp(id, name) } + if (id in StoreState.updates) SecondaryButton("Update", enabled = StoreState.busy == null) { StoreState.update(ctx, id, name) } + SecondaryButton(if (busyHere) "Working…" else if (confirmRemove) "Press again to remove" else "Remove", enabled = StoreState.busy == null) { + if (confirmRemove) { confirmRemove = false; StoreState.uninstall(ctx, id, name) } else confirmRemove = true + } + } else { + PrimaryButton( + if (busyHere) "Installing…" else "Install", main = true, + enabled = StoreState.ready && StoreState.busy == null && s.ready && (d == null || d.arches.isEmpty() || "aarch64" in d.arches), + ) { StoreState.install(ctx, id, name) } + if (!StoreState.ready) ActionChip("Set up Flatpak first", ok = false) + } + d?.version?.let { ActionChip("v$it", ok = false) } + if (d != null && d.downloadSize > 0) ActionChip("${FileUtils.sizeToString(d.downloadSize)} download", ok = false) + if (installed) ActionChip("● Installed", ok = true) + } + } + if (busyHere) BusyBar() + if (d == null) { + Rise(3) { + Box(Modifier.padding(top = 14.dp)) { + Note(if (StoreState.detailsFailed[id] == true) "Flathub's page for this app could not be loaded." else "Loading from Flathub…") + } + } + return + } + if (d.arches.isNotEmpty() && "aarch64" !in d.arches) Rise(3) { Box(Modifier.padding(top = 12.dp)) { Note("Flathub has no ARM64 build of this app, so it cannot be installed here.") } } + if (d.screenshots.isNotEmpty()) { + Rise(3) { SectionTitle("Screenshots", null) } + Rise(3) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) { + d.screenshots.take(6).forEach { shot -> + AsyncImage( + model = shot.thumb, contentDescription = null, contentScale = ContentScale.Crop, + modifier = Modifier.height(if (narrow) 150.dp else 190.dp).aspectRatio(16f / 9f).clip(Shape12).background(colors.surface), + ) + } + } + } + } + if (d.description.isNotEmpty()) { + Rise(4) { SectionTitle("About", null) } + Rise(4) { Text(d.description, fontSize = 14.sp, lineHeight = 20.sp, color = colors.onBackground, modifier = Modifier.fillMaxWidth()) } + } + Rise(5) { SectionTitle("Details", null) } + Rise(5) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.padding(bottom = 16.dp)) { + listOfNotNull( + "App ID" to d.id, + d.license?.let { "License" to it }, + d.runtime?.let { "Runtime" to it.replace("/x86_64/", "/aarch64/") }, + if (d.installedSize > 0) "Installed size" to FileUtils.sizeToString(d.installedSize) + " (plus its runtime, shared between apps)" else null, + d.homepage?.let { "Website" to it }, + ).forEach { (k, v) -> + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text(k, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(110.dp)) + Text(v, fontSize = 13.sp, color = colors.onBackground, modifier = Modifier.weight(1f)) + } + } + } + } +} + +/** Apps as wide tiles: icon, name, summary - three across, or a list on a narrow page. */ +@Composable +private fun AppGrid(apps: List, first: Boolean, onOpen: (String) -> Unit) { + val columns = if (LocalNarrowPane.current) 1 else 3 + Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) { + apps.chunked(columns).forEachIndexed { r, row -> + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) { + row.forEachIndexed { i, app -> + key(app.id) { + AppTile(app, Modifier.weight(1f).fillMaxHeight(), isFirst = first && r == 0 && i == 0) { onOpen(app.id) } + } + } + repeat(columns - row.size) { Spacer(Modifier.weight(1f)) } + } + } + } +} + +@Composable +private fun AppTile(app: FlathubApi.AppSummary, modifier: Modifier, isFirst: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val pressed by src.collectIsPressedAsState() + val scale by animateFloatAsState(if (pressed) 0.97f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "appScale") + val installed = StoreState.installed.any { it.id == app.id } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = modifier.paneItem("tile:store:${app.id}").then(if (isFirst) Modifier.firstTile() else Modifier) + .graphicsLayer { scaleX = scale; scaleY = scale } + .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, onClick = onClick) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + AppIcon(app.icon, app.name, 44) + Column(modifier = Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Text(app.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + if (app.verified) Icon(Icons.Outlined.Verified, contentDescription = "Verified", tint = pal.signal, modifier = Modifier.size(14.dp)) + } + Text(if (installed) "Installed" else app.summary, fontSize = 13.sp, color = if (installed) pal.good else colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } +} + +/** An app's icon from Flathub (a URL) or from its installed files; a placeholder until it loads. */ +@Composable +private fun AppIcon(model: Any?, name: String, size: Int) { + val colors = MaterialTheme.colorScheme + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(size.dp).clip(RoundedCornerShape((size / 5).dp)).background(if (model == null) colors.surfaceVariant else Color.Transparent)) { + if (model == null) Icon(Icons.Outlined.Apps, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size((size / 2).dp)) + else AsyncImage(model = model, contentDescription = name, contentScale = ContentScale.Fit, modifier = Modifier.size(size.dp)) + } +} + +/** A category pill: small, focusable, and filled when it is the one in use. */ +@Composable +private fun PillButton(label: String, selected: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val shape = RoundedCornerShape(99.dp) + Text( + label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, + color = if (selected) pal.onSignal else if (hot) colors.onBackground else colors.onSurfaceVariant, + modifier = Modifier.paneItem("pill:$label").clip(shape) + .background(if (selected) pal.signal else if (hot) pal.signal.copy(alpha = 0.16f) else colors.surfaceVariant) + .glideBorder(hot, shape, pal.signal, pal.line) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) + .controllerConfirm(onClick = onClick) + .padding(horizontal = 14.dp, vertical = 9.dp), + ) +} + +/** The apps installed from the Store, as launch tiles - on the Desktop page beside the emulators. */ +@Composable +internal fun InstalledAppsGrid(a: FrontEndActions) { + val ctx = LocalContext.current + LaunchedEffect(Unit) { StoreState.refresh(ctx) } + val apps = StoreState.installed + if (apps.isEmpty()) return + 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(bottom = 8.dp)) { + SectionTitle("Apps from the Store", apps.size.toString()) + apps.chunked(columns).forEach { row -> + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min)) { + row.forEach { app -> + key(app.id) { + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.weight(1f).fillMaxHeight().paneItem("tile:flatpak:${app.id}") + .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) { a.onFlatpakApp(app.id, app.name) } + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + AppIcon(app.icon ?: StoreState.details[app.id]?.icon ?: FlathubApi.iconUrl(app.id), app.name, 44) + Column(modifier = Modifier.weight(1f)) { + Text(app.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(app.summary ?: "Flatpak", fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } + } + repeat(columns - row.size) { Spacer(Modifier.weight(1f)) } + } + } + } +} + +/** + * The user's own AppImages on the Desktop page: an Add button, each one to open, and Remove + * (pressed twice, like the store's). The picker, the check and the extraction live elsewhere + * (MainActivity, AppImageManager); this only shows them. + */ +@Composable +internal fun AppImagesSection(a: FrontEndActions, runtimeReady: Boolean) { + val ctx = LocalContext.current + LaunchedEffect(Unit) { com.droiddeck.launcher.store.AppImageState.refresh(ctx) } + val state = com.droiddeck.launcher.store.AppImageState + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) { + SectionTitle("AppImages", state.items.size.takeIf { it > 0 }?.toString()) + Actions { + SecondaryButton(if (state.importing != null) "Importing…" else "Add AppImage", enabled = runtimeReady && state.importing == null) { a.onImportAppImage() } + if (!runtimeReady) ActionChip("Runtime required", ok = false) + } + state.importing?.let { name -> + Text("$name · ${state.stage ?: "Starting…"}", fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp)) + } + state.lastError?.let { Note(it) } + if (state.items.isEmpty() && state.importing == null && state.lastError == null) { + Note("Add an ARM64 (aarch64) AppImage from your storage. It is unpacked into the Linux runtime once, then opens full screen from here or from the desktop's menu.") + } + state.items.forEach { item -> + key(item.id) { + var confirm by remember(item.id) { mutableStateOf(false) } + LaunchedEffect(confirm) { if (confirm) { kotlinx.coroutines.delay(4000); confirm = false } } + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(end = 12.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.weight(1f).paneItem("tile:appimage:${item.id}").clip(Shape14) + .background(if (hot) pal.signal.copy(alpha = 0.10f) else Color.Transparent) + .glideBorder(hot, Shape14, pal.signal) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { a.onAppImage(item.guestDir, item.name) } + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + AppIcon(item.icon, item.name, 44) + Column(modifier = Modifier.weight(1f)) { + Text(item.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(item.comment ?: "AppImage", fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + SecondaryButton(if (confirm) "Press again to remove" else "Remove", compact = true) { + if (confirm) { confirm = false; com.droiddeck.launcher.store.AppImageState.remove(ctx, item.id) } else confirm = true + } + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt new file mode 100644 index 000000000..6d824a604 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -0,0 +1,344 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Bolt +import androidx.compose.material.icons.outlined.CheckCircle +import androidx.compose.material.icons.outlined.Code +import androidx.compose.material.icons.outlined.Download +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material.icons.outlined.Refresh +import androidx.compose.material.icons.outlined.Science +import androidx.compose.material.icons.outlined.SwapHoriz +import androidx.compose.material.icons.outlined.Sync +import androidx.compose.material.icons.outlined.Verified +import androidx.compose.material3.Icon +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +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 com.droiddeck.launcher.update.AppUpdates +import com.droiddeck.launcher.update.AppUpdates.Channel +import com.droiddeck.launcher.update.AppUpdates.Follow +import com.droiddeck.launcher.update.AppUpdates.Offer +import com.droiddeck.launcher.update.AppUpdates.Release + +/** The Updates page: the latest build of each channel, the one followed, and an update in progress. */ +class UpdatesState( + val catalog: AppUpdates.Catalog? = null, + val follow: Follow = Follow(Channel.STABLE), + val checking: Boolean = false, + val error: String? = null, + /** "Downloading", "Installing", ... while an update is under way; [percent] is -1 when unknown. */ + val stage: String? = null, + val percent: Int = -1, + /** Explain "Install unknown apps" before sending the user to it. */ + val askPermission: Boolean = false, +) { + val hasUpdate: Boolean get() = AppUpdates.hasUpdate(catalog, follow) +} + +class UpdatesActions( + val onCheck: () -> Unit = {}, + val onFollow: (Follow) -> Unit = {}, + val onInstall: (Release) -> Unit = {}, + val onAllowInstalls: () -> Unit = {}, + val onDismissPermission: () -> Unit = {}, +) + +@Composable +internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { + val u = s.updates + val ua = a.updates + val me = remember { AppUpdates.installed() } + val colors = MaterialTheme.colorScheme + Column(modifier = modifier) { + PageHeader("Updates") { + // The build that is running, beside the title where it is always in view. + Text( + "DroidDeck ${me.version} · ${s.buildLabel}", fontSize = 12.5.sp, color = colors.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f).padding(top = 6.dp), + ) + val checked = u.catalog?.checkedAt?.takeIf { it > 0 } + if (!LocalNarrowPane.current) Text( + if (u.checking) "Checking…" else if (checked != null) "Checked ${ago(checked)}" else "Not checked yet", + fontSize = 13.sp, color = colors.onSurfaceVariant, + ) + ToolIcon(Icons.Outlined.Refresh, "Check for updates", busy = u.checking, enabled = !u.checking && u.stage == null, onClick = ua.onCheck) + } + Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { + // Landscape has the width for channels and status side by side; a narrow pane stacks them. + if (LocalNarrowPane.current) { + StatusPanel(s, u, ua, me) + Box(Modifier.height(18.dp)) + ChannelPicker(u, ua) + } else Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) { + Box(Modifier.weight(1f)) { ChannelPicker(u, ua) } + Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) } + } + } + } + if (u.askPermission) AlertDialog( + onDismissRequest = ua.onDismissPermission, + title = { Text("Let DroidDeck update itself") }, + text = { + Text( + "Android asks once before an app may install updates. On the next screen, turn on " + + "\"Allow from this source\", then come back - the update carries on by itself.", + ) + }, + confirmButton = { TextButton(onClick = ua.onAllowInstalls) { Text("Open settings") } }, + dismissButton = { TextButton(onClick = ua.onDismissPermission) { Text("Not now") } }, + ) +} + +/** Where things stand, as a system updater says it: a status line, what you'd get, and one button. */ +@Composable +private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val catalog = u.catalog + val release = catalog?.let { AppUpdates.release(it, u.follow) } + 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) + class Look(val tint: Color, val status: String, val headline: String, val detail: String?) + val look = when { + !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 Nightly to keep getting the newest fixes.") + else -> Look(pal.good, "Up to date", "You have the latest $name", null) + } + Column( + modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) { + Box(Modifier.size(7.dp).clip(CircleShape).background(look.tint)) + Text(look.status, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = look.tint) + if (offered) Text("· ${ago(release!!.publishedAt)}", fontSize = 13.sp, color = colors.onSurfaceVariant) + } + Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp)) + if (offered) { + 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 (u.error != null) Text(u.error, fontSize = 13.sp, color = pal.error, modifier = Modifier.padding(top = 12.dp)) + 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 { + u.stage != null -> Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(if (u.percent >= 0) "${u.stage}… ${u.percent}%" else "${u.stage}…", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + if (u.percent >= 0) LinearProgressIndicator(progress = { u.percent / 100f }, modifier = Modifier.fillMaxWidth().height(6.dp).clip(CircleShape)) + else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(6.dp).clip(CircleShape)) + } + 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 -> 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)) { + Text("Stop the running session to update.", fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp)) + } + } +} + +/** The change and its notes, two lines each; More opens the rest when either is cut short. */ +@Composable +private fun ReleaseNotes(title: String, notes: String, key: String) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var open by rememberSaveable(key) { mutableStateOf(false) } + var cut by remember(key) { mutableStateOf(false) } + Text( + title, fontSize = 15.sp, color = colors.onBackground, maxLines = if (open) Int.MAX_VALUE else 2, overflow = TextOverflow.Ellipsis, + onTextLayout = { if (it.hasVisualOverflow) cut = true }, modifier = Modifier.padding(top = 10.dp), + ) + if (notes.isNotBlank()) Text( + notes, fontSize = 13.5.sp, color = colors.onSurfaceVariant, maxLines = if (open) Int.MAX_VALUE else 1, overflow = TextOverflow.Ellipsis, + onTextLayout = { if (it.hasVisualOverflow) cut = true }, modifier = Modifier.padding(top = 4.dp), + ) + if (cut || open) { + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val toggle = { open = !open } + Text( + if (open) "Less" else "More", fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, + modifier = Modifier.padding(top = 2.dp).offset(x = (-6).dp).paneItem("notes:more") + .clip(Shape12).glideBorder(hot, Shape12, pal.signal) + .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle) + .controllerConfirm(onClick = toggle) + .padding(horizontal = 6.dp, vertical = 4.dp), + ) + } +} + +/** 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 Nightly build" + Channel.TEST -> "PR #${r.pr} test build" +} + +/** A PR title as a sentence: "fix(steam): keep the client alive" -> "Keep the client alive". */ +private fun changeTitle(t: String): String = + t.replace(Regex("""^[a-z]+(\([^)]*\))?!?:\s*"""), "").replaceFirstChar { it.uppercase() } + +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 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, "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", + when (tests.size) { 0 -> "None right now"; 1 -> "1 to try"; else -> "${tests.size} to try" }, + u.follow.channel == Channel.TEST, enabled = tests.isNotEmpty() || u.follow.channel == Channel.TEST, + ) { tests.firstOrNull()?.let { ua.onFollow(Follow(Channel.TEST, it.pr)) } } + AnimatedVisibility(u.follow.channel == Channel.TEST && tests.isNotEmpty(), enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { + Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + tests.forEach { t -> TestRow(t, u.follow.pr == t.pr) { ua.onFollow(Follow(Channel.TEST, t.pr)) } } + } + } + } +} + +@Composable +private fun ChannelCard( + icon: ImageVector, title: String, hint: String, latest: String?, selected: Boolean, + enabled: Boolean = true, onClick: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + // Focus shows at once, as on the Components page: no ripple, no fade. + val fill = if (hot) pal.signal.copy(alpha = 0.14f) else if (selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + modifier = Modifier.fillMaxWidth().paneItem("channel:$title") + .clip(Shape14).background(colors.surface).background(fill).glideBorder(hot, Shape14, pal.signal, if (selected) pal.signal else pal.line) + .alpha(if (enabled) 1f else 0.55f) + .hoverable(src) + .clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) + .padding(horizontal = 14.dp, vertical = 10.dp), + ) { + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(38.dp).clip(Shape12).background(if (selected) pal.signal.copy(alpha = 0.18f) else colors.surfaceVariant)) { + Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) + } + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + if (latest != null) Text(latest, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = if (selected) pal.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(22.dp).clip(CircleShape).border(2.dp, if (selected) pal.signal else pal.line2, CircleShape)) { + if (selected) Box(Modifier.size(11.dp).clip(CircleShape).background(pal.signal)) + } + } +} + +/** One test build under Test builds: its PR, what it fixes, and how fresh it is. */ +@Composable +private fun TestRow(t: Release, selected: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}") + .heightIn(min = 52.dp) + .clip(Shape12) + .background(colors.surface).background(if (hot) pal.signal.copy(alpha = 0.14f) else if (selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent) + .glideBorder(hot, Shape12, pal.signal, if (selected) pal.signal else pal.line) + .hoverable(src) + .clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(onClick = onClick) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) { + Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant) + Column(Modifier.weight(1f)) { + Text(t.title.ifBlank { "PR #${t.pr}" }, fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(if (t.apk == null) "Not built for this copy of DroidDeck" else "Updated ${ago(t.publishedAt)}", fontSize = 12.sp, color = colors.onSurfaceVariant) + } + } +} + +private fun channelName(f: Follow) = when (f.channel) { + Channel.STABLE -> "Stable" + Channel.NIGHTLY -> "Nightly" + Channel.TEST -> "the PR #${f.pr} test" +} + +private fun ago(millis: Long): String { + if (millis <= 0) return "a while ago" + if (System.currentTimeMillis() - millis in 0 until 60_000) return "just now" + return android.text.format.DateUtils.getRelativeTimeSpanString( + millis, System.currentTimeMillis(), android.text.format.DateUtils.MINUTE_IN_MILLIS, + ).toString() +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt index 2d944ab41..a067ef020 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt @@ -344,7 +344,7 @@ private fun WirelessStepForm( } @Composable -private fun AdbTextField( +internal fun AdbTextField( value: String, onValueChange: (String) -> Unit, label: String, @@ -381,7 +381,7 @@ private fun AdbTextField( .fillMaxWidth() .height(inputHeight) .background(colors.surfaceVariant, shape) - .border(1.dp, if (focused) palette.signal else palette.line2, shape) + .glideBorder(focused, shape, palette.signal, palette.line2) .padding(horizontal = 10.dp), contentAlignment = Alignment.CenterStart, ) { diff --git a/app/src/main/java/com/droiddeck/launcher/update/AppUpdates.kt b/app/src/main/java/com/droiddeck/launcher/update/AppUpdates.kt new file mode 100644 index 000000000..955ea2b1e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/update/AppUpdates.kt @@ -0,0 +1,297 @@ +package com.droiddeck.launcher.update + +import android.content.Context +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.time.Instant + +/** + * DroidDeck's own builds, on three channels: Stable (the org repo's latest release), Nightly (the + * newest `main-` release on DroidDeck-CI, one per merge to main) and Test (a `pr-` 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. + * + * 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 PREFS = "app_updates" + private const val KEY_CATALOG = "catalog" + private const val KEY_CHANNEL = "channel" + + 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) + + /** + * 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 publishedAt: Long, val url: String, val apk: Apk?, + ) + + class Catalog(val stable: Release?, val nightly: Release?, val tests: List, val checkedAt: Long) + + /** 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, + } + + 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.nightly + Channel.TEST -> catalog.tests.firstOrNull { it.pr == follow.pr } + } + + fun offer(catalog: Catalog, follow: Follow, me: Installed = installed()): Offer { + val r = release(catalog, follow) ?: return Offer.GONE + if (isRunning(r, me)) return Offer.CURRENT + return when (follow.channel) { + Channel.STABLE -> when { + me.pr != 0 -> Offer.SWITCH + compareVersions(r.version ?: "", me.version) > 0 -> Offer.UPDATE + else -> Offer.AHEAD + } + Channel.NIGHTLY -> if (me.pr != 0) Offer.SWITCH else Offer.UPDATE + Channel.TEST -> if (me.pr == r.pr) Offer.UPDATE else Offer.SWITCH + } + } + + /** 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) + } + + /** + * 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() + val inferred = when { + 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.ci -> Follow(Channel.NIGHTLY) + else -> Follow(Channel.STABLE) + } + setFollow(context, inferred) + return inferred + } + + fun setFollow(context: Context, follow: Follow) { + val value = if (follow.channel == Channel.TEST) "test:${follow.pr}" else follow.channel.name.lowercase() + prefs(context).edit().putString(KEY_CHANNEL, value).apply() + } + + private fun stored(context: Context): Follow? { + val v = prefs(context).getString(KEY_CHANNEL, null) ?: return null + return when { + v == "stable" -> Follow(Channel.STABLE) + 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 { readCatalog(JSONObject(raw)) }.getOrNull() + } + + /** Read every channel now and remember the result: three small requests, four for an annotated tag. */ + fun refresh(context: Context): Catalog { + 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() + 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 + } + + 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 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 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 published(r: JSONObject): Long = + runCatching { Instant.parse(r.optString("published_at")).toEpochMilli() }.getOrDefault(0L) + + /** The apk for this package: `.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) + } + return null + } + + private fun variantSuffixes(): Map = 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 { + 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 = + name to lines(paragraphs(body).firstOrNull { !it.startsWith("#") && !it.startsWith("![") && !it.startsWith("<") }.orEmpty()) + + private fun paragraphs(body: String): List = + 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 } + for (i in 0 until maxOf(x.size, y.size)) { + val c = (x.getOrElse(i) { 0 }).compareTo(y.getOrElse(i) { 0 }) + if (c != 0) return c + } + return 0 + } + + private fun get(url: String): String { + val c = URL(url).openConnection() as HttpURLConnection + c.connectTimeout = 15_000 + c.readTimeout = 20_000 + c.setRequestProperty("Accept", "application/vnd.github+json") + c.setRequestProperty("User-Agent", "DroidDeck-app") + try { + val code = c.responseCode + 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 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("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 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("nightly", c.nightly?.let(::writeRelease)) + .put("tests", JSONArray().apply { c.tests.forEach { put(writeRelease(it)) } }).put("checkedAt", c.checkedAt) + + private fun readCatalog(o: JSONObject): Catalog { + val tests = o.optJSONArray("tests") ?: JSONArray() + return Catalog( + 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) +} diff --git a/app/src/main/java/com/droiddeck/launcher/update/SelfInstaller.kt b/app/src/main/java/com/droiddeck/launcher/update/SelfInstaller.kt new file mode 100644 index 000000000..3a6e36fed --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/update/SelfInstaller.kt @@ -0,0 +1,108 @@ +package com.droiddeck.launcher.update + +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageInstaller +import android.net.Uri +import android.os.Build +import android.provider.Settings +import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.core.Hashes +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL + +/** + * Installs one of DroidDeck's own builds over itself: download into the cache, check the file + * against GitHub's sha256, then hand it to PackageInstaller. Android shows its own "Update this + * app?" prompt, and the app is restarted on the new build. + */ +object SelfInstaller { + /** The broadcast PackageInstaller answers on; the launcher registers for it while it is open. */ + const val ACTION_STATUS = "com.droiddeck.launcher.update.INSTALL_STATUS" + + /** Android lets an app install packages only once the user allows it in "Install unknown apps". */ + fun canInstall(context: Context): Boolean = + Build.VERSION.SDK_INT < 26 || context.packageManager.canRequestPackageInstalls() + + fun permissionIntent(context: Context): Intent = + Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}")) + + /** Downloads [apk] into the cache and checks it; a download left from before is replaced. */ + fun download(context: Context, apk: AppUpdates.Apk, progress: (Int) -> Unit): File { + val dir = File(context.cacheDir, "updates") + FileUtils.delete(dir) + dir.mkdirs() + val target = File(dir, apk.name) + val c = URL(apk.url).openConnection() as HttpURLConnection + c.connectTimeout = 15_000 + c.readTimeout = 60_000 + c.setRequestProperty("User-Agent", "DroidDeck-app") + c.instanceFollowRedirects = true + try { + if (c.responseCode != 200) throw IOException("The download answered HTTP ${c.responseCode}") + val total = c.contentLengthLong.takeIf { it > 0 } ?: apk.size + c.inputStream.use { input -> + FileOutputStream(target).use { out -> + val buf = ByteArray(1 shl 16) + var done = 0L + var last = -1 + while (true) { + val r = input.read(buf) + if (r <= 0) break + out.write(buf, 0, r) + done += r + val pct = if (total > 0) (done * 100 / total).toInt() else -1 + if (pct != last) { last = pct; progress(pct) } + } + } + } + if (!apk.sha256.equals(Hashes.sha256(target), ignoreCase = true)) { + throw IOException("The download didn't match its checksum and was discarded - try again") + } + return target + } catch (e: Exception) { + FileUtils.delete(target) + throw e + } finally { + c.disconnect() + } + } + + /** 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 + val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply { + setAppPackageName(context.packageName) + setSize(apk.length()) + // Skips Android's prompt where it allows that (the app installed its current build itself). + if (Build.VERSION.SDK_INT >= 31) setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + } + val id = installer.createSession(params) + installer.openSession(id).use { session -> + apk.inputStream().use { input -> + session.openWrite("base.apk", 0, apk.length()).use { out -> + input.copyTo(out, 1 shl 16) + session.fsync(out) + } + } + val status = Intent(ACTION_STATUS).setPackage(context.packageName) + val flags = PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0) + session.commit(PendingIntent.getBroadcast(context, id, status, flags).intentSender) + } + } + + /** What went wrong, in words for the user, from PackageInstaller's status and message. */ + fun describeFailure(status: Int, message: String?): String = when { + message?.contains("VERSION_DOWNGRADE") == true -> + "Android won't install an older version over a newer one. Stay on this build until the channel catches up." + status == PackageInstaller.STATUS_FAILURE_CONFLICT || message?.contains("UPDATE_INCOMPATIBLE") == true -> + "This copy of DroidDeck is signed differently (a local build?), so Android won't update it in place." + status == PackageInstaller.STATUS_FAILURE_STORAGE -> "There isn't enough free space for the update." + status == PackageInstaller.STATUS_FAILURE_ABORTED -> "The update was cancelled." + else -> "The update didn't install" + (message?.let { ": $it" } ?: ".") + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 8f72523d9..a19bd858a 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -32,7 +32,9 @@ object CompositorHost { outputWidth: Int, outputHeight: Int, refreshHz: Float, + fpsLimit: Int, ): Boolean { + pace(refreshHz, fpsLimit) if (started) { attached = surface WaylandCompositor.nativeSetSurface(surface) @@ -50,6 +52,19 @@ object CompositorHost { return true } + /** + * The session's frame cap, on every attach: the compositor outlives sessions, and the next one + * may have a different cap. The release pacer hands a game one buffer back per capped frame + * (per refresh without a cap), and the zero-copy layer votes for the same cadence. Left at 0 + * the vote is inferred from the rate already being achieved, and on a phone whose vendor picks + * clocks from that a session that has been slowed reads as one that wants to be. (WinNative, + * WaylandSession.) + */ + private fun pace(refreshHz: Float, fpsLimit: Int) { + WaylandCompositor.nativeSetFpsLimit(fpsLimit) + WaylandCompositor.nativeSetLayerFrameRate(if (fpsLimit > 0) fpsLimit.toFloat() else refreshHz) + } + /** * The Surface changed size under the compositor (a foldable opening or closing). Android does * not always recreate the Surface for that, and a swapchain built for the old size keeps @@ -65,7 +80,7 @@ object CompositorHost { // came back stretched with an engine on and right with it off. Disarmed, the window is // rebound and the swapchain rebuilt; the caller re-arms once that has settled, and every // engine-side object is made again for the new size. - WaylandCompositor.nativeSetFrameGenArmed(false, 0) + WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) WaylandCompositor.nativeLog("screen", "surface resized: rebinding the window, frame generation re-armed after") WaylandCompositor.nativeSetSurface(null) attached = surface @@ -81,7 +96,7 @@ object CompositorHost { */ fun rearmFrameGen(rearm: () -> Unit) { if (!started) return - WaylandCompositor.nativeSetFrameGenArmed(false, 0) + WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) WaylandCompositor.nativeLog("screen", "presenting window changed: frame generation re-armed") android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(rearm, 600) } diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 7b7717869..71c7172a0 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -67,10 +67,30 @@ public final class WaylandCompositor { if (l != null) l.onGameSurface(window, gpuName); } + private static volatile long lastFrameNanos; + private static volatile long frameIntervalNanos; + + /** + * How long frames are taking to arrive right now, in ms, or -1 before the first: the smoothed + * interval, or the time since the last frame when that is longer (a session that has stalled). + */ + public static long recentFrameIntervalMs() { + long last = lastFrameNanos; + if (last == 0) return -1; + return Math.max(frameIntervalNanos, System.nanoTime() - last) / 1_000_000; + } + /** Invoked from native (banner_on_game_frame) for every frame of the HUD's window. */ @SuppressWarnings("unused") static void onGameFrame() { - com.droiddeck.launcher.session.PerfHints.onFrame(); + long now = System.nanoTime(); + long previous = lastFrameNanos; + lastFrameNanos = now; + if (previous != 0) { + long interval = now - previous; + long smoothed = frameIntervalNanos; + frameIntervalNanos = smoothed == 0 ? interval : (smoothed * 3 + interval) / 4; + } GameListener l = gameListener; if (l != null) l.onGameFrame(); } @@ -187,6 +207,9 @@ public final class WaylandCompositor { */ public static native int nativeCursorSnapshot(int[] out); + /** The serial {@link #nativeCursorSnapshot} would report, without copying the image. */ + public static native int nativeCursorSerial(); + /** Enough for the header plus a 256x256 cursor, the largest the compositor snapshots. */ public static final int CURSOR_BUF_INTS = 6 + 256 * 256; @@ -197,7 +220,7 @@ public final class WaylandCompositor { * once per tick, so games run unthrottled and the screen shows their latest frame. */ public static native void nativeVsync(long frameTimeNanos); - /** The compositor thread's Linux tid, or 0 before it has started (see PerfHints). */ + /** The compositor thread's Linux tid, or 0 before it has started. */ public static native int nativeCompositorTid(); /** Shortcut launches: don't draw explorer's windows (desktop, taskbar, Start menu), matching the @@ -414,6 +437,14 @@ public final class WaylandCompositor { * back to the game, like the X11 IdleNotify pacer, so the game itself slows to the cap. */ public static native void nativeSetFpsLimit(int fps); + /** KGSL power control off (true: the GPU held at its top clock) or back on. Device-wide and + * outlives the process; see {@code GpuClockPin}. A no-op without /dev/kgsl-3d0. */ + public static native void nativeSetGpuTurbo(boolean on); + + /** setpriority() on one of our own processes or threads, only ever raising it (no cgroup move, + * unlike android.os.Process.setThreadPriority). Returns the nice it is left at; 100 = unknown. */ + public static native int nativeRaisePriority(int tid, int nice); + /** Inject the app's X-server input in scene (virtual desktop) pixels. type 2 = move to a,b; * 3 = evdev button a (BTN_LEFT=0x110…) pressed (b=1) or released (b=0); 4 = a wheel steps, * negative = up. */ @@ -430,10 +461,12 @@ public final class WaylandCompositor { public static native void nativeSetFrameGenEngine(int kind); /** Arm (multiplier 2..4: one real frame plus multiplier-1 interpolated ones per game frame) or - * disarm. Generated frames are presented ahead of the real frame on consecutive vblanks. */ - public static native void nativeSetFrameGenArmed(boolean armed, int multiplier); + * disarm. A targetFps above 0 makes LSFG adaptive instead: it generates 0..3 frames per game + * frame, whatever reaches that rate. Generated frames are presented ahead of the real frame + * on consecutive vblanks. */ + public static native void nativeSetFrameGenArmed(boolean armed, int multiplier, int targetFps); - /** LSFG Native: the SPIR-V cache built from the user's Lossless.dll ({@code LsfgNative.cacheFile}). */ + /** LSFG Native: the SPIR-V cache built from the user's Lossless.dll ({@code Lossless.cacheFile}). */ public static native void nativeSetLsfgCachePath(String path); /** Flow scale (0.25-1.0) and the panel's real refresh rate (the pacer never generates above it). */ diff --git a/app/src/main/res/drawable/ic_stat_session.xml b/app/src/main/res/drawable/ic_stat_session.xml index 3b3415de2..0efa80f6c 100644 --- a/app/src/main/res/drawable/ic_stat_session.xml +++ b/app/src/main/res/drawable/ic_stat_session.xml @@ -1,11 +1,8 @@ - - + android:viewportWidth="239.92" android:viewportHeight="239.92"> + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c46d83f86..cfa4435bd 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -19,4 +19,93 @@ Resume Stop session Frame generation + Select the frame generation mode + Off + Win-FG %1$d× + LSFG %1$d× + LSFG Adaptive %1$d + Needs Lossless Scaling on Steam + Install Lossless Scaling in Steam or import Lossless.dll + Import Lossless.dll… + Using the copy from Steam + Using an imported copy + Choose Lossless.dll + Lossless.dll imported + This Lossless.dll is already in use + Lossless Scaling is not owned on this Steam account + This file is not Lossless Scaling\'s Lossless.dll + Could not prepare LSFG from this Lossless.dll + LSFG needs Lossless Scaling from Steam or an imported Lossless.dll + LSFG could not prepare its shaders from Lossless.dll + %1$s: unsupported + %1$s: engine failed + %1$s: needs Lossless Scaling + %1$s %2$s · starting + Choose Windows games with one subfolder per game. Steam checks ownership while signed in. Confirmed games use their Steam library entries after restarting Steam; other games stay as non-Steam shortcuts. Steam may verify or download files for imported games. + Adds a Steam library and scans Windows game folders here and in steamapps/common. After the ownership check and a Steam restart, owned games use Steam entries; other games use non-Steam shortcuts. + Forget removes non-Steam shortcuts next session. Manage Steam installations in Steam. Files stay on disk. + Game environment + Shared defaults and per-game overrides for games using Proton. Applies on the next game launch. + Edit variables + All Proton games + Game profile + Steam app ID or non-Steam compatibility ID + Open profile + Game %1$s + Add variable + Variable name + Value + Save + Cancel + Close + Remove + Restore inherited settings + Reset this profile + Unset for this profile + No variables set. Driver and Proton defaults apply. + Inherited + Custom variable + D3D12 feature level defaults to 12_2 and shader model to 6_9. Both can be changed or removed for each game. + Could not load or apply the settings. Check available storage and try again. + Use a valid variable name and a value without NUL characters (up to 8192 characters). + The standard Linux Proton runtime does not use this variable; it may require a custom component. + Loading… + Settings in this profile override shared settings and matching Steam launch-option variables. Remove unsets a variable; restore uses its inherited value. + D3D12 feature-level override. 12_2 reports DirectX 12 Ultimate capabilities; unsupported features can fail. Leave unset for automatic detection. + D3D12 shader-model override. 6_9 requires a sufficiently recent VKD3D and matching GPU features. Leave unset for automatic detection. + Keep Mesa shader caching enabled to reduce repeated compilation. false enables caching. + Maximum Mesa shader-cache size, such as 1G. Larger caches use more storage. + VKD3D options for D3D12. nodxr disables ray tracing; use only for a game that needs it. + Set to 1 for a Proton diagnostic log. Logging can reduce performance and use storage. + Set to 1 to use OpenGL-based WineD3D instead of DXVK for D3D9–11 compatibility testing. + Set to 0 to disable Proton’s gamepad-navigation helper for this game. + DXVK overlay for D3D9–11. fps displays frame rate; unset hides it. + DXVK settings separated by semicolons. Recent builds use dxvk.maxFrameRate for frame limiting; prefer the session frame limiter for ordinary play. + D3D12 frame-rate limit. 0 disables the limit. + Mesa OpenGL threading. true can help CPU-limited OpenGL games; test per game. + FEX preset + Applies on the next game launch. + Games + FEX defaults + Uses FEX defaults. + Stability + Safest, slowest settings. + Compatibility + Full TSO with multiblock. + Intermediate + Balanced TSO with reduced x87 precision. + Performance + All TSO disabled; multiblock. + Performance + TSO + Performance settings with main TSO enabled. + Extreme + Disables self-modifying-code checks. JIT games and DRM may break. + Extreme + TSO + Extreme settings with main TSO enabled. + Extreme-gn + Performance with TSC and metadata hints. Try before Extreme. + Denuvo + Performance with full code checks and the hypervisor bit hidden. + Custom value + Select value diff --git a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt new file mode 100644 index 000000000..320f57333 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt @@ -0,0 +1,75 @@ +package com.droiddeck.launcher.core + +import org.junit.Assert.* +import org.junit.Test + +class GameEnvironmentTest { + @Test fun defaultsIncludeRequestedGraphicsLevelsAndKeepCaching() { + val values = GameEnvironment.defaults("") + assertEquals("false", values["MESA_SHADER_CACHE_DISABLE"]) + assertEquals("12_2", values["VKD3D_FEATURE_LEVEL"]) + assertEquals("6_9", values["VKD3D_SHADER_MODEL"]) + } + + @Test fun gameOverridesSharedAndPresetWithoutLeakingToOtherGames() { + val config = GameEnvironment.Config( + shared = mapOf("FEX_MULTIBLOCK" to "0", "VKD3D_FEATURE_LEVEL" to "12_2"), + games = mapOf("42" to mapOf("FEX_MULTIBLOCK" to "1", "VKD3D_FEATURE_LEVEL" to null)), + ) + val game = GameEnvironment.effective(config, "COMPATIBILITY", "42") + assertEquals("1", game["FEX_MULTIBLOCK"]) + assertTrue(game.containsKey("VKD3D_FEATURE_LEVEL")) + assertNull(game["VKD3D_FEATURE_LEVEL"]) + val other = GameEnvironment.effective(config, "COMPATIBILITY", "43") + assertEquals("0", other["FEX_MULTIBLOCK"]) + assertEquals("12_2", other["VKD3D_FEATURE_LEVEL"]) + } + + @Test fun graphicsDefaultsRespectExistingEditsAndRemovals() { + val config = GameEnvironment.Config(shared = mapOf("VKD3D_FEATURE_LEVEL" to "12_0")) + .withEntries("42", mapOf("VKD3D_SHADER_MODEL" to null)) + val game = GameEnvironment.effective(config, "", "42") + assertEquals("12_0", game["VKD3D_FEATURE_LEVEL"]) + assertTrue(game.containsKey("VKD3D_SHADER_MODEL")) + assertNull(game["VKD3D_SHADER_MODEL"]) + val restored = GameEnvironment.effective(config.withEntries("42", emptyMap()), "", "42") + assertEquals("6_9", restored["VKD3D_SHADER_MODEL"]) + } + + @Test fun multiSelectionPreservesCustomTokensAndRemovesToggledValues() { + assertEquals("fps,custom_token,frametimes", GameEnvironmentOptions.toggle("fps,custom_token", "frametimes")) + assertEquals("custom_token", GameEnvironmentOptions.toggle("fps,custom_token", "fps")) + assertEquals("", GameEnvironmentOptions.toggle("fps", "fps")) + assertEquals("fps", GameEnvironmentOptions.toggle("", "fps")) + } + + @Test fun switchingPresetDropsOldPresetOnlyVariables() { + val config = GameEnvironment.Config() + assertEquals("none", GameEnvironment.effective(config, "EXTREME", "")["FEX_SMCCHECKS"]) + assertFalse(GameEnvironment.effective(config, "COMPATIBILITY", "").containsKey("FEX_SMCCHECKS")) + assertFalse(GameEnvironment.effective(config, "", "").containsKey("FEX_MULTIBLOCK")) + } + + @Test fun resettingOneProfilePreservesOtherProfiles() { + val config = GameEnvironment.Config(shared = mapOf("CUSTOM" to "shared")) + .withEntries("42", mapOf("CUSTOM" to "game")) + .withEntries("43", mapOf("CUSTOM" to "other")) + .withEntries("42", emptyMap()) + assertEquals("shared", GameEnvironment.effective(config, "", "42")["CUSTOM"]) + assertEquals("other", GameEnvironment.effective(config, "", "43")["CUSTOM"]) + assertFalse(config.games.containsKey("42")) + } + + @Test fun validationPreservesLiteralValuesAndRejectsInvalidKeys() { + assertTrue(GameEnvironment.validName("mesa_glthread")) + assertFalse(GameEnvironment.validName("X=Y")) + assertFalse(GameEnvironment.validName("1VAR")) + assertFalse(GameEnvironment.validName("VAR\n")) + assertTrue(GameEnvironment.validValue("a=b 'quote' $(touch file) ; $")) + assertTrue(GameEnvironment.validValue("")) + assertFalse(GameEnvironment.validValue("bad\u0000value")) + assertFalse(GameEnvironment.validValue("x".repeat(8193))) + assertTrue(GameEnvironment.validScope("4294967295")) + for (scope in listOf("0", "-1", "01", "+1", "4294967296", "../42")) assertFalse(GameEnvironment.validScope(scope)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt index a7cfc80a9..e930f85e5 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt @@ -1,6 +1,8 @@ package com.droiddeck.launcher.core import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test class PhantomProcessLimitTest { @@ -26,4 +28,33 @@ class PhantomProcessLimitTest { assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status(null, null)) assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status("", "")) } + + @Test + fun android12UsesDeviceConfig() { + assertEquals( + listOf( + "device_config set_sync_disabled_for_tests persistent", + "device_config put activity_manager max_phantom_processes 2147483647", + ), + PhantomProcessLimit.shellCommands(enabled = false, sdk = 31), + ) + assertTrue(PhantomProcessLimit.verified("2147483647\n", enabled = false, sdk = 31)) + assertFalse(PhantomProcessLimit.verified("null", enabled = false, sdk = 31)) + } + + @Test + fun android12LAndLaterUseTheFlag() { + assertEquals( + listOf("settings put global settings_enable_monitor_phantom_procs false"), + PhantomProcessLimit.shellCommands(enabled = false, sdk = 33), + ) + assertTrue(PhantomProcessLimit.verified("false", enabled = false, sdk = 34)) + assertFalse(PhantomProcessLimit.verified("null", enabled = false, sdk = 33)) + } + + @Test + fun developerToggleStartsAtAndroid14() { + assertFalse(PhantomProcessLimit.hasDeveloperToggle(33)) + assertTrue(PhantomProcessLimit.hasDeveloperToggle(34)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/DriverBundleTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/DriverBundleTest.kt new file mode 100644 index 000000000..434e87d09 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/gpu/DriverBundleTest.kt @@ -0,0 +1,133 @@ +package com.droiddeck.launcher.gpu + +import android.content.Context +import android.net.Uri +import com.droiddeck.launcher.session.SessionPrefs +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class DriverBundleTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + File(context.filesDir, "graphics_driver").deleteRecursively() + File(context.filesDir, LinuxVulkanDriverManager.DIR_NAME).deleteRecursively() + context.getSharedPreferences("driver_bundles", Context.MODE_PRIVATE).edit().clear().commit() + SessionPrefs.setAndroidDriver(context, "") + SessionPrefs.setLinuxDriver(context, "") + } + + /** Enough of an AArch64 ELF for the importers: the header they read, then the libc they look for. */ + private fun library(libc: String) = ByteArray(64).also { + byteArrayOf(0x7f, 'E'.code.toByte(), 'L'.code.toByte(), 'F'.code.toByte(), 2, 1).copyInto(it) + it[18] = 0xB7.toByte() + } + libc.toByteArray() + ByteArray(1) + + private val manifest = JSONObject() + .put("package", "DD-Turnip").put("version", "0.1.0").put("tag", "DD-Turnip-v0.1.0") + .put("drivers", JSONObject() + .put("android", JSONObject().put("path", "android")) + .put("linux", JSONObject().put("path", "linux"))) + + private fun zip(entries: Map): Uri { + val file = File.createTempFile("bundle", ".zip", context.cacheDir) + ZipOutputStream(file.outputStream()).use { z -> + for ((name, data) in entries) { z.putNextEntry(ZipEntry(name)); z.write(data); z.closeEntry() } + } + return Uri.fromFile(file) + } + + private fun bundle(linuxLibc: String = "libc.so.6", extra: Map = emptyMap()) = zip(mapOf( + "android/meta.json" to JSONObject().put("name", "DD-Turnip v0.1.0").put("libraryName", "libvulkan_freedreno.so").toString().toByteArray(), + "android/libvulkan_freedreno.so" to library("libc.so"), + "linux/meta.json" to JSONObject().put("name", "DD-Turnip v0.1.0").put("driverVersion", "DD-Turnip-v0.1.0").toString().toByteArray(), + "linux/libvulkan_freedreno.so" to library(linuxLibc), + "manifest.json" to manifest.toString().toByteArray(), + ) + extra) + + @Test fun manifestNeedsBothHalvesInSeparateSafeDirectories() { + val m = DriverBundle.parseManifest(manifest)!! + assertEquals("android", m.androidPath) + assertEquals("linux", m.linuxPath) + assertNull(DriverBundle.parseManifest(JSONObject().put("drivers", JSONObject().put("android", JSONObject().put("path", "a"))))) + val same = JSONObject(manifest.toString()).apply { getJSONObject("drivers").getJSONObject("linux").put("path", "android/") } + assertNull(DriverBundle.parseManifest(same)) + val escape = JSONObject(manifest.toString()).apply { getJSONObject("drivers").getJSONObject("linux").put("path", "../x") } + assertNull(DriverBundle.parseManifest(escape)) + } + + @Test fun singleDriverZipsAreNotBundles() { + val legacy = zip(mapOf("meta.json" to "{}".toByteArray(), "libvulkan_freedreno.so" to library("libc.so"))) + assertFalse(DriverBundle.isBundle(context, legacy)) + assertTrue(DriverBundle.isBundle(context, bundle())) + } + + @Test fun installsBothHalvesAndPicksAndDeletesThemTogether() { + val b = DriverBundle.install(context, bundle()) + assertEquals("DD-Turnip-v0.1.0", b.id) + assertEquals("DD-Turnip 0.1.0", b.label) + assertTrue(TurnipDriver(context).isInstalled(b.androidId)) + assertTrue(LinuxVulkanDriverManager(context).isInstalled(b.linuxId)) + assertEquals(b.id, DriverBundle.containing(context, b.linuxId, linux = true)?.id) + assertEquals(b.id, DriverBundle.containing(context, b.androidId, linux = false)?.id) + + assertNull(DriverBundle.active(context)) + DriverBundle.select(context, b) + assertEquals(b.androidId, SessionPrefs.androidDriver(context)) + assertEquals(b.linuxId, SessionPrefs.linuxDriver(context)) + assertNotNull(DriverBundle.active(context)) + + DriverBundle.remove(context, b) + assertFalse(TurnipDriver(context).isInstalled(b.androidId)) + assertFalse(LinuxVulkanDriverManager(context).isInstalled(b.linuxId)) + assertEquals("", SessionPrefs.androidDriver(context)) + assertEquals("", SessionPrefs.linuxDriver(context)) + assertTrue(DriverBundle.all(context).isEmpty()) + } + + @Test fun aRefusedHalfLeavesNothingInstalled() { + try { + DriverBundle.install(context, bundle(linuxLibc = "libc.so")) + fail("a bionic library in linux/ must be refused") + } catch (e: IllegalArgumentException) { + assertTrue(e.message!!.contains("glibc")) + } + assertTrue(TurnipDriver(context).enumerateImported().isEmpty()) + assertTrue(LinuxVulkanDriverManager(context).enumerateInstalledDrivers().isEmpty()) + } + + @Test fun entriesOutsideTheBundleAreRefused() { + try { + DriverBundle.install(context, bundle(extra = mapOf("../escape.so" to ByteArray(4)))) + fail("a zip-slip entry must be refused") + } catch (e: IllegalArgumentException) { + assertTrue(e.message!!.contains("outside")) + } + assertFalse(File(context.cacheDir.parentFile, "escape.so").exists()) + } + + @Test fun twoInstallsOfOneReleaseGetTheirOwnIds() { + val first = DriverBundle.install(context, bundle()) + val second = DriverBundle.install(context, bundle()) + assertEquals("DD-Turnip-v0.1.0-2", second.id) + assertEquals(2, DriverBundle.all(context).size) + assertFalse(first.androidId == second.androidId) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt new file mode 100644 index 000000000..47431f253 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt @@ -0,0 +1,109 @@ +package com.droiddeck.launcher.gpu + +import com.droiddeck.launcher.gpu.GpuInfo.Family +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class DriverPairsTest { + private fun gpu(model: Int, adreno: Boolean = true, oneUi: Boolean = false) = + GpuInfo("Adreno $model", model, GpuInfo.familyOf(adreno, model), "", oneUi) + + private fun asset(name: String, tag: String, linux: Boolean, pair: String) = + TurnipReleases.Asset("src", tag, name, "https://example/$name", 3_000_000, linux, "label", "0".repeat(64), pair) + + @Test + fun familiesFollowTheAdrenoModel() { + assertEquals(Family.A8XX, GpuInfo.familyOf(true, 825)) + assertEquals(Family.A8XX, GpuInfo.familyOf(true, 810)) + assertEquals(Family.A7XX_LOW, GpuInfo.familyOf(true, 722)) + assertEquals(Family.A7XX, GpuInfo.familyOf(true, 740)) + assertEquals(Family.A6XX, GpuInfo.familyOf(true, 610)) + assertEquals(Family.ADRENO_UNKNOWN, GpuInfo.familyOf(true, 0)) + assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0)) + } + + @Test + fun onlyTestedHardwareCountsAsSupported() { + assertEquals(GpuInfo.Support.TESTED, gpu(740).support) + assertEquals(GpuInfo.Support.TESTED, gpu(825).support) + assertEquals(GpuInfo.Support.UNTESTED, gpu(610).support) + assertEquals(GpuInfo.Support.UNTESTED, gpu(720).support) + assertEquals(GpuInfo.Support.UNSUPPORTED, gpu(0, adreno = false).support) + } + + @Test + fun autoPicksWinNativeBalancedOn8xxAndBannersElsewhere() { + assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), emptyList())) + assertEquals("840 with no DD-Turnip release listed", DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(840), emptyList())) + assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), emptyList())) + assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), emptyList())) + assertEquals(DriverPairs.BANNER_ONEUI, DriverPairs.recommendedKey(gpu(740, oneUi = true), emptyList())) + assertEquals(DriverPairs.BANNER_710, DriverPairs.recommendedKey(gpu(720), emptyList())) + assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650), emptyList())) + assertNull(DriverPairs.recommendedKey(gpu(0, adreno = false), emptyList())) + } + + @Test + fun pairsMatchHalvesAndNeverMixBannersReleases() { + val check = TurnipReleases.Check( + listOf( + asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER), + asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER), + // The A8xx set's newest display build is r4, but its Linux half is only in r3. + asset("Turnip-r4-A8xx.zip", "r4", false, DriverPairs.BANNER_A8XX), + asset("Turnip-r3-A8xx-Linux.zip", "r3", true, DriverPairs.BANNER_A8XX), + asset("WN-Turnip-1.19-b_Axxx.zip", "v1.19", false, DriverPairs.WN_BALANCED), + asset("WN-Linux-Turnip-0.1.2-b_Axxx.zip", "linux-v0.1.2", true, DriverPairs.WN_BALANCED), + ), + emptyList(), emptyList(), 0L, + ) + val pairs = DriverPairs.from(check).associateBy { it.key } + assertTrue(pairs.getValue(DriverPairs.BANNER).complete) + assertFalse("halves from two releases are not a pair", pairs.getValue(DriverPairs.BANNER_A8XX).complete) + val wn = pairs.getValue(DriverPairs.WN_BALANCED) + assertTrue("WinNative's two release lines pair up", wn.complete) + assertEquals("v1.19 + v0.1.2", wn.version) + assertTrue(wn.suits(gpu(830))) + assertFalse(pairs.getValue(DriverPairs.BANNER).suits(gpu(830))) + } + + @Test + fun everyBundleReleaseIsACompletePairOnItsOwnNewestFirst() { + fun bundle(tag: String) = TurnipReleases.Asset("DroidDeck", tag, "$tag.zip", "https://example/$tag", 6_000_000, + false, "Android + Linux", "0".repeat(64), DriverPairs.ddTurnip(tag), bundle = true) + val newer = bundle("DD-Turnip-v0.2.0") + val older = bundle("DD-Turnip-v0.1.0") + val pairs = DriverPairs.from(TurnipReleases.Check( + listOf(asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER), newer, older, + asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER)), + emptyList(), emptyList(), 0L, + )) + assertEquals(listOf(DriverPairs.ddTurnip("DD-Turnip-v0.2.0"), DriverPairs.ddTurnip("DD-Turnip-v0.1.0"), DriverPairs.BANNER), pairs.map { it.key }) + val dd = pairs.first() + assertTrue(dd.complete) + assertEquals(listOf(newer), dd.assets) + assertEquals("v0.2.0", dd.version) + assertEquals("DroidDeck · DD-Turnip", dd.name) + assertTrue(dd.suits(gpu(840))) + assertTrue(dd.suits(gpu(740))) + } + + @Test + fun adreno840GetsTheNewestOfficialDdTurnip() { + fun bundle(tag: String) = TurnipReleases.Asset("DroidDeck", tag, "$tag.zip", "https://example/$tag", 6_000_000, + false, "Android + Linux", "0".repeat(64), DriverPairs.ddTurnip(tag), bundle = true) + val pairs = DriverPairs.from(TurnipReleases.Check( + listOf(bundle("DD-Turnip-v0.9.0"), bundle("DD-Turnip-v1.0.0"), bundle("DD-Turnip-v0.10.1"), + asset("WN-Turnip-1.19-b_Axxx.zip", "v1.19", false, DriverPairs.WN_BALANCED), + asset("WN-Linux-Turnip-0.1.2-b_Axxx.zip", "linux-v0.1.2", true, DriverPairs.WN_BALANCED)), + emptyList(), emptyList(), 0L, + )) + assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(840), pairs)) + assertEquals("other 8xx keep WinNative", DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), pairs)) + assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), pairs)) + assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), pairs)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt new file mode 100644 index 000000000..fe3c9773d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt @@ -0,0 +1,42 @@ +package com.droiddeck.launcher.gpu + +import android.content.Context +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class FrameGenTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + context.getSharedPreferences("frame_gen", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun offUntilPicked() { + assertEquals(FrameGen.Mode.OFF, FrameGen.mode(context)) + } + + @Test fun adaptiveTargetIsKept() { + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 90)) + assertEquals(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 90), FrameGen.mode(context)) + } + + @Test fun fixedMultiplierReplacesATarget() { + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 120)) + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, 3)) + assertEquals(FrameGen.Mode(FrameGen.ENGINE_LSFG, 3), FrameGen.mode(context)) + } + + @Test fun onlyLsfgIsAdaptive() { + context.getSharedPreferences("frame_gen", Context.MODE_PRIVATE).edit() + .putString("engine", FrameGen.ENGINE_WINFG).putInt("multiplier", 4).putInt("target", 60).commit() + assertEquals(FrameGen.Mode(FrameGen.ENGINE_WINFG, 4), FrameGen.mode(context)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt new file mode 100644 index 000000000..158351477 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt @@ -0,0 +1,48 @@ +package com.droiddeck.launcher.gpu + +import android.content.Context +import com.droiddeck.launcher.runtime.LinuxRuntime +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class LosslessTest { + private lateinit var context: Context + private lateinit var flag: File + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + context.getSharedPreferences("lossless", Context.MODE_PRIVATE).edit().clear().commit() + flag = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/lossless-owned") + flag.delete() + } + + @Test fun nothingIsOwnedOrReadyUntilTheSessionSaysSo() { + assertEquals(Lossless.State.NONE, Lossless.state(context)) + assertNull(Lossless.cacheFile(context)) + } + + @Test fun theSessionsOwnershipFlagIsRememberedForGood() { + flag.parentFile!!.mkdirs() + flag.writeText("") + assertTrue(Lossless.owned(context)) + flag.delete() + assertTrue(Lossless.owned(context)) + } + + @Test fun importIsRefusedWithoutOwnership() { + val dll = File(context.cacheDir, "Lossless.dll").apply { writeText("not a dll") } + assertFalse(Lossless.owned(context)) + assertEquals(Lossless.ImportResult.NOT_OWNED, Lossless.import(context, dll)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt new file mode 100644 index 000000000..1064ab2b8 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenControlsTest.kt @@ -0,0 +1,191 @@ +package com.droiddeck.launcher.input + +import kotlin.math.sqrt +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.view.MotionEvent +import android.view.View +import android.widget.FrameLayout +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE, qualifiers = "mdpi") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class OnScreenControlsTest { + private lateinit var context: Context + private lateinit var view: OnScreenControls + private var time = 1000L + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + context.getSharedPreferences("controller", Context.MODE_PRIVATE).edit().clear().commit() + ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (0.45f to 0.5f), "rs" to (0.55f to 0.5f))) + view = OnScreenControls(context, null) + view.layout(0, 0, 1200, 800) + } + + @Test fun adaptiveStickHidesUntilTouchedAndReturnsToNeutralOnRelease() { + val left = control("ls") + assertEquals(0, pixel(value(left, "cx"), value(left, "cy"))) + assertTrue(touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f))) + assertEquals(7, field(left, "pressedBy")) + assertEquals(540f, value(left, "ax"), 0f) + assertEquals(400f, value(left, "ay"), 0f) + assertNotEquals(0, pixel(540f, 400f)) + touch(MotionEvent.ACTION_MOVE, 7 to (580f to 420f)) + assertTrue(value(left, "kx") > 0f) + assertTrue(value(left, "ky") > 0f) + touch(MotionEvent.ACTION_UP, 7 to (580f to 420f)) + assertEquals(-1, field(left, "pressedBy")) + assertEquals(0f, value(left, "kx"), 0f) + assertEquals(0f, value(left, "ky"), 0f) + assertEquals(0, pixel(540f, 400f)) + } + + @Test fun simultaneousSticksKeepTheirPointersAndReleaseIndependently() { + val left = control("ls") + val right = control("rs") + touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f)) + touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (540f to 400f), 9 to (660f to 400f)) + assertEquals(7, field(left, "pressedBy")) + assertEquals(9, field(right, "pressedBy")) + touch(MotionEvent.ACTION_POINTER_DOWN or (2 shl 8), 7 to (540f to 400f), 9 to (660f to 400f), 11 to (500f to 400f)) + assertEquals(7, field(left, "pressedBy")) + touch(MotionEvent.ACTION_POINTER_UP or (2 shl 8), 7 to (540f to 400f), 9 to (660f to 400f), 11 to (500f to 400f)) + touch(MotionEvent.ACTION_MOVE, 7 to (700f to 400f), 9 to (500f to 400f)) + assertTrue(value(left, "kx") > 0f) + assertTrue(value(right, "kx") < 0f) + touch(MotionEvent.ACTION_POINTER_UP, 7 to (700f to 400f), 9 to (500f to 400f)) + assertEquals(-1, field(left, "pressedBy")) + assertEquals(9, field(right, "pressedBy")) + touch(MotionEvent.ACTION_CANCEL, 9 to (500f to 400f)) + for (stick in listOf(left, right)) { + assertEquals(-1, field(stick, "pressedBy")) + assertEquals(0f, value(stick, "kx"), 0f) + } + } + + @Test fun cancelledTouchDoesNotBecomeAStickClick() { + touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f)) + touch(MotionEvent.ACTION_CANCEL, 1 to (540f to 400f)) + touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f)) + assertEquals(false, field(control("ls"), "clicked")) + touch(MotionEvent.ACTION_UP, 1 to (540f to 400f)) + touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f)) + assertEquals(true, field(control("ls"), "clicked")) + } + + @Test fun buttonsTakePriorityOverAdaptiveRegions() { + val button = control("a") + touch(MotionEvent.ACTION_DOWN, 3 to (value(button, "cx") to value(button, "cy"))) + assertEquals(3, field(button, "pressedBy")) + assertEquals(-1, field(control("rs"), "pressedBy")) + } + + @Test fun fixedSticksAndEditorRemainVisibleAtSavedPositions() { + ControllerPrefs.setAdaptiveSticks(context, false) + view.reload() + val left = control("ls") + val x = value(left, "cx") + val y = value(left, "cy") + assertNotEquals(0, pixel(x, y)) + assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f))) + touch(MotionEvent.ACTION_DOWN, 1 to (x + 10f to y)) + assertEquals(x, value(left, "ax"), 0f) + assertEquals(10f, value(left, "kx"), 0f) + ControllerPrefs.setAdaptiveSticks(context, true) + view = OnScreenControls(context, null, editing = true) + view.layout(0, 0, 1200, 800) + assertNotEquals(0, pixel(value(control("ls"), "cx"), value(control("ls"), "cy"))) + } + + @Test fun buttonsOnlyAndReloadReleaseAdaptiveSticks() { + touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f)) + touch(MotionEvent.ACTION_MOVE, 1 to (570f to 400f)) + view.reload() + assertEquals(-1, field(control("ls"), "pressedBy")) + assertEquals(0f, value(control("ls"), "kx"), 0f) + view.setButtonsOnly(true) + assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f))) + } + + @Test fun adaptiveActivationIsLimitedToExpandedSavedCircle() { + val left = control("ls") + val x = value(left, "cx") + val y = value(left, "cy") + val reach = value(left, "radius") * 1.4f * sqrt(1.5f) + assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to y - reach - 1f))) + assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to y - reach + 1f))) + assertEquals(y - reach + 1f, value(left, "ay"), 0.001f) + touch(MotionEvent.ACTION_UP, 1 to (x to y - reach + 1f)) + assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x - reach to y - reach))) + assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f))) + } + + @Test fun touchesOutsideActivationAreasStayWithTrackpad() { + val received = mutableListOf() + val trackpad = View(context).apply { + setOnTouchListener { _, event -> received.add(event.actionMasked); true } + } + val root = FrameLayout(context).apply { + addView(trackpad, FrameLayout.LayoutParams(1200, 800)) + addView(view, FrameLayout.LayoutParams(1200, 800)) + measure(View.MeasureSpec.makeMeasureSpec(1200, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY)) + layout(0, 0, 1200, 800) + } + for ((action, position) in listOf( + MotionEvent.ACTION_DOWN to (600f to 200f), + MotionEvent.ACTION_MOVE to (540f to 400f), + MotionEvent.ACTION_UP to (540f to 400f), + )) { + val event = MotionEvent.obtain(1000L, time++, action, position.first, position.second, 0) + try { assertTrue(root.dispatchTouchEvent(event)) } finally { event.recycle() } + } + assertEquals(listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP), received) + assertEquals(-1, field(control("ls"), "pressedBy")) + } + + @Test fun adaptiveActivationLeavesFivePixelsAroundButtonHitTargets() { + for (id in listOf("a", "rb")) { + val button = control(id) + val radius = value(button, "radius") + val edge = value(button, "cy") - radius * if (id == "rb") 1.05f else 1.25f + val x = value(button, "cx") + val left = control("ls") + left.javaClass.getDeclaredField("cx").apply { isAccessible = true }.setFloat(left, x) + left.javaClass.getDeclaredField("cy").apply { isAccessible = true }.setFloat(left, edge - 10f) + assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 4f))) + assertEquals(-1, field(left, "pressedBy")) + assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 6f))) + assertEquals(1, field(left, "pressedBy")) + touch(MotionEvent.ACTION_UP, 1 to (x to edge - 6f)) + } + } + + private fun control(id: String): Any = (field(view, "controls") as List<*>).first { field(it!!, "id") == id }!! + private fun field(owner: Any, name: String): Any = owner.javaClass.getDeclaredField(name).apply { isAccessible = true }.get(owner)!! + private fun value(owner: Any, name: String) = field(owner, name) as Float + + private fun pixel(x: Float, y: Float): Int { + val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888) + view.draw(Canvas(bitmap)) + val color = bitmap.getPixel(x.toInt(), y.toInt()) + bitmap.recycle() + return color + } + + private fun touch(action: Int, vararg pointers: Pair>): Boolean { + val properties = pointers.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray() + val coords = pointers.map { (_, position) -> MotionEvent.PointerCoords().apply { x = position.first; y = position.second; pressure = 1f; size = 1f } }.toTypedArray() + val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0) + return try { view.onTouchEvent(event) } finally { event.recycle() } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/AppImageManagerTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/AppImageManagerTest.kt new file mode 100644 index 000000000..1cd246ab4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/AppImageManagerTest.kt @@ -0,0 +1,51 @@ +package com.droiddeck.launcher.runtime + +import java.io.File +import java.nio.file.Files +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class AppImageManagerTest { + private lateinit var dir: File + + @Before fun setUp() { dir = Files.createTempDirectory("appimage").toFile() } + @After fun tearDown() { dir.deleteRecursively() } + + /** An ELF header with the AppImage magic at byte 8 and [machine] at byte 18. */ + private fun image(machine: Int, type: Int = 2, magic: Boolean = true): File { + val b = ByteArray(64) + b[0] = 0x7f; b[1] = 'E'.code.toByte(); b[2] = 'L'.code.toByte(); b[3] = 'F'.code.toByte() + if (magic) { b[8] = 'A'.code.toByte(); b[9] = 'I'.code.toByte(); b[10] = type.toByte() } + b[18] = (machine and 0xff).toByte(); b[19] = (machine shr 8).toByte() + return File(dir, "x.AppImage").apply { writeBytes(b) } + } + + @Test fun acceptsAnArm64TypeTwoImage() = assertNull(AppImageManager.problem(image(183))) + + @Test fun refusesX86WithAHint() = assertTrue(AppImageManager.problem(image(62))!!.contains("x86_64")) + + @Test fun refusesTypeOne() = assertTrue(AppImageManager.problem(image(183, type = 1))!!.contains("type 2")) + + @Test fun refusesAPlainProgram() = assertTrue(AppImageManager.problem(image(183, magic = false))!!.contains("not an AppImage")) + + @Test fun refusesSomethingElse() { + val f = File(dir, "notes.AppImage").apply { writeText("hello, this is not a program at all") } + assertTrue(AppImageManager.problem(f)!!.contains("not an AppImage")) + } + + @Test fun idsAreTidyAndUnique() { + assertEquals("some-app-1-2-aarch64", AppImageManager.idFor("Some_App-1.2-aarch64.AppImage", emptySet())) + assertEquals("some-app-2", AppImageManager.idFor("Some App.AppImage", setOf("some-app"))) + } + + @Test fun readsTheMainDesktopGroup() { + val entry = "[Desktop Entry]\nName=Duck\nName[de]=Ente\nIcon=duck\n[Desktop Action x]\nName=Other\n" + assertEquals("Duck", AppImageManager.desktopKey(entry, "Name")) + assertEquals("duck", AppImageManager.desktopKey(entry, "Icon")) + assertNull(AppImageManager.desktopKey(entry, "Comment")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt new file mode 100644 index 000000000..364c3ef9e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt @@ -0,0 +1,127 @@ +package com.droiddeck.launcher.runtime + +import android.util.Base64 +import org.robolectric.RuntimeEnvironment +import com.droiddeck.launcher.runtime.BwrapSpawner.Bind +import java.io.File +import java.nio.file.Files +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class BwrapSpawnerTest { + private val session = listOf( + Bind("/dev", "/dev"), + Bind("/cache/shm", "/dev/shm"), + Bind("/proc", "/proc"), + Bind("/rootfs/etc/bannerlator/proc/stat", "/proc/stat"), + Bind("/data/files", "/data/files"), + ) + + @Test fun underRespectsPathBoundaries() { + assertTrue(BwrapSpawner.under("/usr/lib", "/usr")) + assertTrue(BwrapSpawner.under("/usr", "/usr")) + assertFalse(BwrapSpawner.under("/usrlocal", "/usr")) + assertTrue(BwrapSpawner.under("/anything", "/")) + } + + @Test fun hostPathGoesThroughTheMostSpecificSessionBind() { + assertEquals("/cache/shm/x", BwrapSpawner.hostPath(session, "/rootfs", "/dev/shm/x")) + assertEquals("/dev/null", BwrapSpawner.hostPath(session, "/rootfs", "/dev/null")) + assertEquals("/data/files/.wayland-rt/wayland-1", BwrapSpawner.hostPath(session, "/rootfs", "/data/files/.wayland-rt/wayland-1")) + } + + @Test fun hostPathFallsBackToTheRootfs() { + assertEquals("/rootfs/root/.local/share/flatpak", BwrapSpawner.hostPath(session, "/rootfs/", "/root/.local/share/flatpak")) + } + + @Test fun bindingDevBringsTheSessionsStandInsAlong() { + val binds = BwrapSpawner.bindsFor(session, "/rootfs", "/dev", "/dev") + assertEquals(Bind("/dev", "/dev"), binds.first()) + assertTrue(Bind("/cache/shm", "/dev/shm") in binds) + assertFalse(binds.any { it.guest.startsWith("/proc") }) + } + + @Test fun nestedBindsFollowARenamedDestination() { + val binds = BwrapSpawner.bindsFor(session, "/rootfs", "/proc", "/newproc") + assertTrue(Bind("/rootfs/etc/bannerlator/proc/stat", "/newproc/stat") in binds) + } + + @Test fun normalizeResolvesDotsLexically() { + assertEquals("/usr/lib/x", BwrapSpawner.normalize("/usr/lib/GL/../x")) + assertEquals("/", BwrapSpawner.normalize("/../..")) + } + + @Test fun bindSpecsRoundTrip() { + assertEquals(Bind("/a", "/b"), Bind.parse("/a:/b")) + assertEquals(Bind("/a", "/a"), Bind.parse("/a")) + assertEquals("/a", Bind("/a", "/a").spec) + assertEquals("/a:/b", Bind("/a", "/b").spec) + } +} + +/** The sandbox a Flatpak request describes, built on disk under a temporary directory. */ +@RunWith(RobolectricTestRunner::class) +class BwrapSpawnerPlanTest { + private lateinit var dir: File + private lateinit var runtime: File + + @Before fun setUp() { + dir = Files.createTempDirectory("bwrap-plan").toFile() + // Flatpak names the runtime by its path inside the rootfs. + runtime = File(LinuxRuntime.rootDir(RuntimeEnvironment.getApplication()), "runtime-files") + File(runtime, "lib").mkdirs() + } + + @After fun tearDown() { + dir.deleteRecursively() + runtime.deleteRecursively() + } + + private fun op(vararg pairs: Pair) = JSONObject().apply { pairs.forEach { (k, v) -> put(k, v) } } + + private fun request(vararg ops: JSONObject) = JSONObject() + .put("argv", JSONArray().put("/app/bin/game")) + .put("env", JSONObject().put("FLATPAK_ID", "org.example.Game")) + .put("cwd", "/app") + .put("ops", JSONArray().apply { ops.forEach { put(it) } }) + + @Test fun buildsTheTreeFlatpakAsksFor() { + val context = RuntimeEnvironment.getApplication() + val info = Base64.encodeToString("[Application]\nname=org.example.Game\n".toByteArray(), Base64.NO_WRAP) + val plan = BwrapSpawner.plan(context, request( + op("t" to "bind", "src" to "/runtime-files", "dest" to "/usr", "ro" to true), + op("t" to "symlink", "target" to "usr/lib", "dest" to "/lib"), + op("t" to "dir", "dest" to "/usr/lib/GL", "empty" to true), + op("t" to "symlink", "target" to "default/lib/libEGL.so", "dest" to "/usr/lib/GL/libEGL.so"), + op("t" to "dir", "dest" to "/tmp"), + op("t" to "file", "dest" to "/.flatpak-info", "data" to info, "perms" to 0x180), + op("t" to "bind", "src" to "/nonexistent-${System.nanoTime()}", "dest" to "/run/x", "try" to true), + ), dir) + + // The runtime is bound at /usr, not written into. + assertTrue(plan.binds.any { it.guest == "/usr" && File(it.host).canonicalPath == runtime.canonicalPath }) + assertFalse(File(runtime, "lib/GL").exists()) + // The tmpfs under /usr is a directory of ours, and the link Flatpak makes inside it lands there. + val gl = plan.binds.single { it.guest == "/usr/lib/GL" } + assertTrue(gl.host.startsWith(dir.path)) + assertEquals("default/lib/libEGL.so", Files.readSymbolicLink(File(gl.host, "libEGL.so").toPath()).toString()) + // Top-level links, directories and files are made in the sandbox root itself. + assertEquals("usr/lib", Files.readSymbolicLink(File(plan.root, "lib").toPath()).toString()) + assertTrue(File(plan.root, "tmp").isDirectory) + assertEquals("[Application]\nname=org.example.Game\n", File(plan.root, ".flatpak-info").readText()) + // A --bind-try whose source is missing is left out. + assertFalse(plan.binds.any { it.guest == "/run/x" }) + assertEquals(listOf("/app/bin/game"), plan.argv) + assertEquals("/app", plan.cwd) + assertEquals("org.example.Game", plan.env["FLATPAK_ID"]) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt new file mode 100644 index 000000000..604c9456a --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt @@ -0,0 +1,73 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.core.GameEnvironment +import com.droiddeck.launcher.runtime.LinuxRuntime +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class GameEnvironmentStoreTest { + private lateinit var context: Context + private lateinit var guest: File + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + guest = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-environment.json") + File(context.filesDir, "game-environment.json").delete() + } + + @Test fun savedSettingsAndPublishedSettingsPreserveUnsetsAndLiteralValues() { + val config = GameEnvironment.Config( + shared = mapOf("LITERAL" to "a=b 'quoted' $(echo test)", "EMPTY" to ""), + games = mapOf("42" to mapOf("LITERAL" to null, "VKD3D_SHADER_MODEL" to "6_9")), + ) + GameEnvironmentStore.save(context, config) + assertEquals(config, GameEnvironmentStore.read(context)) + val published = GameEnvironmentStore.decode(JSONObject(guest.readText())) + assertEquals("false", published.shared["MESA_SHADER_CACHE_DISABLE"]) + assertEquals("12_2", published.shared["VKD3D_FEATURE_LEVEL"]) + assertEquals("6_9", published.shared["VKD3D_SHADER_MODEL"]) + assertEquals(config.games, published.games) + assertEquals(config.shared["LITERAL"], published.shared["LITERAL"]) + assertEquals("", published.shared["EMPTY"]) + } + + @Test fun changingFexPresetPublishesForNextGameLaunch() { + GameEnvironmentStore.save(context, GameEnvironment.Config()) + SessionPrefs.setFexPreset(context, "EXTREME") + assertEquals("none", JSONObject(guest.readText()).getJSONObject("shared").getString("FEX_SMCCHECKS")) + SessionPrefs.setFexPreset(context, "") + assertFalse(JSONObject(guest.readText()).getJSONObject("shared").has("FEX_SMCCHECKS")) + } + + @Test fun unchosenFexPresetPublishesPerformanceTso() { + GameEnvironmentStore.save(context, GameEnvironment.Config()) + val shared = JSONObject(guest.readText()).getJSONObject("shared") + assertEquals("1", shared.getString("FEX_TSOENABLED")) + assertEquals("0", shared.getString("FEX_HALFBARRIERTSOENABLED")) + assertEquals("1", shared.getString("FEX_X87REDUCEDPRECISION")) + assertEquals("1", shared.getString("FEX_MULTIBLOCK")) + } + + @Test fun invalidDataCannotReplaceSavedConfiguration() { + val original = GameEnvironment.Config(shared = mapOf("CUSTOM" to "ok")) + GameEnvironmentStore.save(context, original) + assertTrue(runCatching { GameEnvironmentStore.save(context, GameEnvironment.Config(shared = mapOf("BAD=NAME" to "x"))) }.isFailure) + assertEquals(original, GameEnvironmentStore.read(context)) + } + + @Test fun customComponentVariablesRemainEditable() { + val config = GameEnvironment.Config(shared = mapOf("DXVK_ASYNC" to "1")) + GameEnvironmentStore.save(context, config) + assertEquals(config, GameEnvironmentStore.read(context)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/GuestHostnameTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GuestHostnameTest.kt new file mode 100644 index 000000000..23329a6af --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/GuestHostnameTest.kt @@ -0,0 +1,30 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class GuestHostnameTest { + @Test fun validLabelsAreKept() { + assertEquals("localhost", SessionPrefs.validGuestHostname("localhost")) + assertEquals("Fold8-Steam", SessionPrefs.validGuestHostname("Fold8-Steam")) + assertEquals("a", SessionPrefs.validGuestHostname("a")) + assertEquals("x".repeat(63), SessionPrefs.validGuestHostname("x".repeat(63))) + } + + @Test fun surroundingSpaceIsTrimmed() { + assertEquals("localhost", SessionPrefs.validGuestHostname(" localhost \n")) + } + + @Test fun anythingElseIsRejected() { + assertNull(SessionPrefs.validGuestHostname(null)) + assertNull(SessionPrefs.validGuestHostname("")) + assertNull(SessionPrefs.validGuestHostname(" ")) + assertNull(SessionPrefs.validGuestHostname("-leading")) + assertNull(SessionPrefs.validGuestHostname("trailing-")) + assertNull(SessionPrefs.validGuestHostname("two words")) + assertNull(SessionPrefs.validGuestHostname("dotted.name")) + assertNull(SessionPrefs.validGuestHostname("back\\slash")) + assertNull(SessionPrefs.validGuestHostname("x".repeat(64))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/store/FlathubApiTest.kt b/app/src/test/java/com/droiddeck/launcher/store/FlathubApiTest.kt new file mode 100644 index 000000000..5aa2dfc2f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/store/FlathubApiTest.kt @@ -0,0 +1,20 @@ +package com.droiddeck.launcher.store + +import com.droiddeck.launcher.runtime.FlatpakManager +import org.junit.Assert.assertEquals +import org.junit.Test + +class FlathubApiTest { + @Test fun appstreamDescriptionsBecomeLines() { + val html = "

    A game & more.

    • Fast
    • Free

    Enjoy

    " + assertEquals("A game & more.\n• Fast\n• Free\n\nEnjoy", FlathubApi.plainText(html)) + } + + @Test fun refsReadAsWords() { + assertEquals("SuperTux", FlatpakManager.refLabel("app/org.supertuxproject.SuperTux/aarch64/stable")) + assertEquals("GNOME runtime 50", FlatpakManager.refLabel("runtime/org.gnome.Platform/aarch64/50")) + assertEquals("Freedesktop runtime 26.08", FlatpakManager.refLabel("runtime/org.freedesktop.Platform/aarch64/26.08")) + assertEquals("graphics drivers", FlatpakManager.refLabel("runtime/org.freedesktop.Platform.GL.default/aarch64/26.08")) + assertEquals("translations", FlatpakManager.refLabel("runtime/org.gnome.Platform.Locale/aarch64/50")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/update/AppUpdatesTest.kt b/app/src/test/java/com/droiddeck/launcher/update/AppUpdatesTest.kt new file mode 100644 index 000000000..2ac5f5e80 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/update/AppUpdatesTest.kt @@ -0,0 +1,83 @@ +package com.droiddeck.launcher.update + +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.assertTrue +import org.junit.Test + +class AppUpdatesTest { + private fun release(commit: String, pr: Int = 0, version: String? = null) = + AppUpdates.Release("t", "title", "", commit, pr, version, 0L, "", null) + + private val stable = release("aaaaaaa1111111111111111111111111111111", version = "0.2.0") + private val catalog = AppUpdates.Catalog( + stable = stable, + nightly = release("bbbbbbb"), + tests = listOf(release("ccccccc2222222222222222222222222222222", pr = 93)), + checkedAt = 0L, + ) + + private fun me(commit: String, pr: Int = 0, version: String = "0.2.0") = Installed(commit, pr, version, ci = true) + + @Test + fun theStableBuildIsCurrentOnStable() { + assertEquals(Offer.CURRENT, AppUpdates.offer(catalog, Follow(Channel.STABLE), me(stable.commit))) + } + + @Test + 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"))) + } + + @Test + 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))) + } + + @Test + fun testBuildsUpdateWithinTheirPrAndSwitchOtherwise() { + assertEquals(Offer.UPDATE, AppUpdates.offer(catalog, Follow(Channel.TEST, 93), me("fffffff000", pr = 93))) + assertEquals(Offer.SWITCH, AppUpdates.offer(catalog, Follow(Channel.TEST, 93), me(stable.commit))) + assertEquals(Offer.SWITCH, AppUpdates.offer(catalog, Follow(Channel.NIGHTLY), me("ccccccc2", pr = 93))) + assertEquals(Offer.GONE, AppUpdates.offer(catalog, Follow(Channel.TEST, 12), me("ccccccc2", pr = 12))) + } + + @Test + fun aTestBuildIsNeverTheMainBuildOfTheSameCommit() { + assertEquals(Offer.SWITCH, AppUpdates.offer(catalog, Follow(Channel.NIGHTLY), me("bbbbbbb", pr = 5))) + } + + @Test + fun versionsCompareByNumberNotText() { + assertTrue(AppUpdates.compareVersions("0.10.0", "0.9.2") > 0) + assertTrue(AppUpdates.compareVersions("v0.2.1", "0.2") > 0) + assertEquals(0, AppUpdates.compareVersions("0.2", "0.2.0")) + } + + @Test + 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("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) + } +} diff --git a/artwork/boot-animation-source/README.md b/artwork/boot-animation-source/README.md index e1915c39a..4caa7aa72 100644 --- a/artwork/boot-animation-source/README.md +++ b/artwork/boot-animation-source/README.md @@ -1,13 +1,17 @@ # DroidDeck boot animation This source accompanies the single Steam startup movie bundled by the app: -`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1920×1080, pitch black background, VP9 video +`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1280×720 at 30 fps, pitch black background, VP8 video with Opus audio). `droiddeck-boot.html` is the editable animation; the scripts and WAV below -reproduce the selected render. No alternate MP4 or WebM exports are kept in the repository. +render the animation at the bundled playback profile. No alternate MP4 or WebM exports are kept in the repository. From the repository root, render the movie with: - python3 artwork/boot-animation-source/render.py 1920 1080 60 app/src/main/assets/steam-startup/droiddeck-startup.webm dark + python3 artwork/boot-animation-source/render.py 1280 720 30 app/src/main/assets/steam-startup/droiddeck-startup.webm dark + +The bundled profile reduces decoded pixels per second by 78% compared with 1080p/60. +VP8 also lowers software decode cost while Steam is starting. Keep the bundled movie at +720p/30; higher-resolution exports are intended for sharing. The app stages that file into Steam's `config/uioverrides/movies` folder before each session. If Steam still has its built-in startup movie selected, DroidDeck sets this movie as the device's @@ -27,13 +31,12 @@ it down or step frame by frame (arrow keys). ## Re-render the video - pip install playwright && playwright install chromium # ffmpeg with libvpx-vp9 also required - python3 render.py 1280 800 60 droiddeck-boot-1280x800.webm - python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.webm + pip install playwright && playwright install chromium # ffmpeg with libvpx also required + python3 render.py 1280 720 30 droiddeck-boot-1280x720.webm python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.mp4 # .mp4 = H.264 for sharing - python3 render.py 1280 800 60 droiddeck-boot-dark-1280x800.webm dark # dark version + python3 render.py 1280 720 30 droiddeck-boot-dark-1280x720.webm dark # dark version -Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP9 for .webm or H.264 for .mp4, both BT.709, +Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP8 for .webm or H.264 for .mp4, both BT.709, so the orb stays #1A9FFF after compression. ## Sound diff --git a/artwork/boot-animation-source/render.py b/artwork/boot-animation-source/render.py index 9c55b9b10..ee85ea06a 100644 --- a/artwork/boot-animation-source/render.py +++ b/artwork/boot-animation-source/render.py @@ -2,11 +2,11 @@ """Render the DroidDeck boot animation to .webm (Steam) or .mp4 (H.264). Usage: python3 render.py [WIDTH] [HEIGHT] [FPS] [OUT] [light|dark] - python3 render.py 1280 800 60 droiddeck-boot.webm + python3 render.py 1280 720 30 droiddeck-boot.webm python3 render.py 1920 1080 60 droiddeck-boot.mp4 - python3 render.py 1280 800 60 droiddeck-boot-dark.webm dark + python3 render.py 1280 720 30 droiddeck-boot-dark.webm dark -Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx-vp9. +Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx. The animation is drawn by droiddeck-boot.html (same folder); each frame gets real motion blur (180-degree shutter, up to 48 sub-frames when things move fast). """ @@ -15,8 +15,8 @@ from pathlib import Path from playwright.sync_api import sync_playwright W = int(sys.argv[1]) if len(sys.argv) > 1 else 1280 -H = int(sys.argv[2]) if len(sys.argv) > 2 else 800 -FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 60 +H = int(sys.argv[2]) if len(sys.argv) > 2 else 720 +FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 30 OUT = sys.argv[4] if len(sys.argv) > 4 else f"droiddeck-boot-{W}x{H}.webm" THEME = sys.argv[5] if len(sys.argv) > 5 else "light" # light | dark ONLY = [int(x) for x in os.environ.get("FRAMES", "").split(",") if x] # debug: render some frames only @@ -54,9 +54,9 @@ cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+ful if OUT.lower().endswith(".mp4"): # H.264 for sharing, previews and anything that won't play webm cmd += ["-c:v", "libx264", "-preset", "slow", "-crf", "15", "-profile:v", "high", "-tune", "animation", "-g", str(FPS * 2), "-movflags", "+faststart"] -else: # VP9 webm for Steam's startup movie - cmd += ["-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "18", "-deadline", "good", "-cpu-used", "2", - "-row-mt", "1", "-g", str(FPS * 2)] +else: # VP8 keeps software decoding inexpensive during Steam startup + cmd += ["-c:v", "libvpx", "-b:v", "2M", "-crf", "10", "-deadline", "good", "-cpu-used", "2", + "-g", str(FPS * 2)] cmd += COLOR + ([] if SOUND.exists() else ["-an"]) + [OUT] subprocess.run(cmd, check=True) if not os.environ.get("FRAMEDIR"): diff --git a/docs/development/flatpak.md b/docs/development/flatpak.md new file mode 100644 index 000000000..006bab55a --- /dev/null +++ b/docs/development/flatpak.md @@ -0,0 +1,118 @@ +# Flatpak and the Store + +Both features are beta and off by default. Setup → Launcher → "Linux apps (beta)" has one toggle for the +Flathub Store, which shows the Store rail item and the Store's apps on the Desktop page, and one for +AppImages, which shows the AppImages section. Turning either off hides it; installed apps stay installed +and remain in the Linux desktop's menu. + +The Store rail section installs apps from Flathub into the Linux runtime with Flatpak. Only +ARM64 builds are listed. Everything lives in one per-user installation at +`/root/.local/share/flatpak`, so nothing needs Flatpak's system helper or polkit. + +## Putting Flatpak in the runtime + +`bannerlator-flatpak-setup` runs under proot's fake root (`-0`), because pacman and pacman-key +refuse any other uid. The runtime's pacman database lists only the base image. The desktop +and emulator packages were unpacked over it without registering. A plain `pacman -S flatpak` +would therefore reinstall about a hundred packages, Mesa among them, over the runtime's KGSL +Turnip build, and run every hook in the image, mkinitcpio included. So pacman, with a +database of its own under `/var/cache/droiddeck-flatpak`, only downloads the nine packages +Flatpak adds to this image and checks their signatures against the Arch Linux ARM keyring. +The script then unpacks them without hooks and checks what the binaries link. Libraries that +the Desktop package normally brings (PyGObject, json-glib, fuse3 and others) are fetched too, +but only when their files are missing. Flathub is added as a per-user remote from a copy of +its `.flatpakrepo` carried in the script, so that step needs no network. Every store command +writes its output to `Download/DroidDeck/flatpak-.log`, next to the session logs. The +setup script also puts Flatpak's own error text in the failure message the app shows. + +## bubblewrap without namespaces + +Android gives apps no user namespaces, so `bwrap` cannot work. Flatpak is pointed at +`bannerlator-bwrap` instead (`FLATPAK_BWRAP`, exported by `bannerlator-session` and by the +store's commands). It reads bwrap's command line, including `--args` fds and the `--file` and +`--bind-data` payloads, and then does one of two things: + +- A sandbox that remaps nothing runs directly. Flatpak's install triggers (`--ro-bind / /`) and + the D-Bus proxy (every top-level directory bound onto itself) are the cases, and they keep the + file descriptors Flatpak handed them. +- Anything else is described to the app over the abstract socket + `com.droiddeck.launcher.bwrap`, which serves only the app's own uid. `BwrapSpawner` builds the + tree under `cache/bwrap/`: a root directory for top-level links, directories and files, + scratch directories for `--tmpfs` inside a bind, and every `--bind` translated from guest + to host paths through the session's own binds. It then starts it as a proot of its own + beside the session's. Output, the pid (for `--info-fd`) and the exit status flow back, and + the stand-in exiting kills the sandbox. + +A proot nested in the session's proot would also work, but every system call then goes +through two tracers, about thirty times slower at a program's start. + +The spawner also adds what the rootfs gives its own programs: + +- **GPU.** Flathub's Mesa has Turnip only for DRM, and Adreno on Android is KGSL. The runtime's + own `libvulkan_freedreno.so` is bound in with the three libraries the Freedesktop runtime + lacks (`libdisplay-info`, SPIRV-Tools). Vulkan uses it, and Mesa's GL runs on it through Zink + (`MESA_LOADER_DRIVER_OVERRIDE=zink`). This is skipped for an app drawing into a desktop + composited by pixman, where Zink cannot present. +- **Controllers.** The libraries in the rootfs's `/etc/ld.so.preload` (the session shim and the + fake evdev reader) go in through `LD_PRELOAD`, with the session's `dev` directory. +- **Browsers.** Firefox's child sandboxes are switched off (`MOZ_DISABLE_*_SANDBOX`), and + Chromium and Electron apps use zypak's mimic strategy (`ZYPAK_ZYGOTE_STRATEGY_SPAWN=0`). The + Flatpak portal's Spawn refuses a caller whose `/proc//root` holds no `.flatpak-info`, + and a proot sandbox's root is the host's. +- **CPU.** `/proc/cpuinfo` without the cores' part numbers. Snapdragon's ARMv9 cores imply SVE2 + to LLVM, Qualcomm leaves SVE off, and llvmpipe's first shader died with SIGILL. + +## Running apps + +The front end starts an app as a run-mode session of `bannerlator-flatpak-run `, full +screen under gamescope. Under gamescope it passes `--nosocket=wayland --socket=x11` and sets +`XDG_SESSION_TYPE=x11`. Otherwise Flatpak finds the app compositor's `wayland-0` and the window +opens behind gamescope. gamescope's own Wayland socket is no alternative: Chromium on Wayland +asks the render node it names for a DRM version, which KGSL cannot give, and aborts. The +launcher also starts a session bus when there is none. On the Linux desktop, the apps' exported +menu entries appear in the LXQt menu. While the desktop is composited by pixman, games are +wrapped through `droiddeck-gpu` like the rootfs's own. + +## The store + +`FlathubApi` reads flathub.org's public API: collections, search filtered to `aarch64`, and +AppStream details. `bannerlator-flatpak` drives libflatpak through PyGObject and prints one +JSON object per line (`op`, `progress`, `error`, `done`). `FlatpakManager` turns those lines +into the store's progress bar. Store commands run in a proot of their own, and +`OrphanReaper` spares them when a session starts. + +## AppImages + +"Add AppImage" on the Desktop page imports an ARM64, type 2 AppImage from storage. `AppImageManager` +checks its ELF header first, so an x86_64 image is refused with a message saying so. It then copies the +image in, because shared storage is noexec, and extracts it once to `/opt/appimages/user//app`. +proot has no FUSE, and extracting at every start would cost the whole image each time. The name, +comment and icon come from the image's own desktop entry. A menu entry goes to +`/usr/local/share/applications`, where the desktop's GPU wrapper picks it up. + +`bannerlator-appimage-run` starts it: + +- `APPIMAGE` stays unset, so apps don't offer to add themselves to the menu or update in place. +- Firefox forks get the same sandbox switches as Flatpaks. +- Electron apps (a `chrome-sandbox` beside them) get `--no-sandbox` and X11. +- A session bus is started when the session has none. +- The launcher waits while anything from the image still runs, because Electron apps relaunch themselves. + +Known to fail: + +- Obsidian's own AppImage traps (SIGTRAP) after startup. Its Flatpak works. +- Zen's AppImage hangs in Firefox's startup GPU probe. The Firefox Flatpak works. + +## x86_64 apps + +Flathub lists x86_64-only apps (Heroic, Discord, Spotify, Steam), and the store hides them. Running them +would need an x86 emulator in the sandbox. There's no FEX or box64 package in Arch Linux ARM; Valve's +ARM64 Steam can install its FEX compatibility tool, but only through the Steam client. With a FEX binary +available, the path would be: + +1. `flatpak install --arch=x86_64`. Flatpak accepts it, and the x86 runtime is also the x86 root FEX needs. +2. `BwrapSpawner` starts those sandboxes with `proot -q`, through a small wrapper that runs FEXInterpreter. + `-q` passes QEMU-style arguments. +3. GPU drivers would need FEX's thunks, or Mesa runs emulated on the CPU. + +x86 AppImages would also need an x86 rootfs for the libraries they don't bundle. diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md new file mode 100644 index 000000000..5b9244a66 --- /dev/null +++ b/docs/development/game-environment.md @@ -0,0 +1,81 @@ +# Steam game environment + +Open **Games → Game environment**, directly below **FEX preset**, in Steam +settings or the in-session drawer. Choose all Proton games, an installed game, or enter a Steam app ID. For a +non-Steam shortcut, use its numeric `compatdata` directory ID (unsigned 32-bit). +Changes apply on the next game launch, including when Steam is already running. +A running game must be restarted. Native Linux games and Steam itself are outside +this editor's scope. + +The order is inherited process environment, selected FEX preset and built-in +settings, shared edits, then game-specific edits. Editor entries therefore win +over matching Steam launch-option variables. **Remove** explicitly unsets a +variable. **Restore inherited settings** removes the override. **Reset this +profile** clears only that profile's overrides. Values are literal strings, with +no shell expansion; quotes are only needed when the consuming program expects them. + +## Defaults and available suggestions + +The initial configuration enables Mesa shader caching with +`MESA_SHADER_CACHE_DISABLE=false`, sets `VKD3D_FEATURE_LEVEL=12_2` and +`VKD3D_SHADER_MODEL=6_9`, and preserves the selected FEX preset. Existing edits +and explicit removals take precedence over these defaults. FEX's own default +remains the default preset. Shader caching in VKD3D/DXVK, synchronization, ray +tracing and diagnostic logging otherwise retain the runtime's defaults. + +The variable-name picker offers 24 predefined variables and a Custom entry. Like +WinNative, known variables use toggles, value dropdowns, multi-select lists, or +numeric/text fields. Feature-level and shader-model dropdowns also accept custom +values. Custom variables have editable names and literal values. + +| Variable | Use | +| --- | --- | +| `VKD3D_FEATURE_LEVEL` | D3D12 capability override; defaults to `12_2`. | +| `VKD3D_SHADER_MODEL` | Shader-model override; defaults to `6_9`. | +| `VKD3D_CONFIG` | Per-game workarounds such as `nodxr`; not a universal performance preset. | +| `MESA_SHADER_CACHE_MAX_SIZE` | Storage budget for Mesa's shader cache, for example `1G`. | +| `mesa_glthread` | OpenGL threading; test with the affected game. | +| `DXVK_CONFIG` | DXVK configuration options; recent builds accept `dxvk.maxFrameRate = 60`. | +| `VKD3D_FRAME_RATE` | D3D12 frame-rate limit. | +| `DXVK_HUD`, `PROTON_LOG` | Optional diagnostics; leave unset for ordinary play. | +| `PROTON_USE_WINED3D` | D3D9–11 OpenGL fallback for compatibility testing. | +| `PROTON_USE_XALIA` | Proton's gamepad-navigation helper toggle. | + +Forcing `12_2` or `6_9` changes reported capabilities; it cannot implement a missing +Vulkan feature. Remove either entry to use automatic detection for that capability. +Other picker suggestions are editable starting values and are enabled only when +added and saved. Older or +custom components can support a different set of options. Android Wine wrapper, +ALSA-server, Box64 and patched async-DXVK options are identified in the editor as +requiring a different/custom component; custom entries remain allowed. The old +`DXVK_FRAME_RATE` environment variable was removed from current DXVK, so it is +not offered as a suggestion. Prefer the session frame limiter for ordinary play. + +## Launch path and references + +WinNative's Linux session filters Android-only options, merges user variables +over the FEX preset, and passes the result to `env -i` before starting Steam. Its +Windows/Wine graphics helper also maps the selected feature level to +`VKD3D_FEATURE_LEVEL`. Reviewed source: [WinNative Linux session](https://github.com/maxjivi05/WinNative/blob/c9fbbb342f2689c852046804f4f5c9afa45b5dcb/app/src/main/runtime/display/XServerDisplayActivity.java), +[variable editor](https://github.com/maxjivi05/WinNative/blob/c9fbbb342f2689c852046804f4f5c9afa45b5dcb/app/src/main/shared/ui/widget/EnvVarsView.java), +[graphics configuration](https://github.com/maxjivi05/WinNative/blob/c9fbbb342f2689c852046804f4f5c9afa45b5dcb/app/src/main/feature/settings/drivers/DXVKConfigUtils.java). + +DroidDeck instead publishes an atomic JSON snapshot at +`/root/.config/droiddeck/game-environment.json`. Both its Valve ARM64 Proton +wrapper and adopted third-party Proton wrappers execute `bannerlator-game-env`, +which reads that snapshot for each real game launch and uses `execvpe` to start +Proton. Probe prefix `compatdata/0` and non-launch verbs are unchanged. Malformed +configuration falls back to the inherited environment without evaluating its +contents. Signed non-Steam prefix IDs are normalized to unsigned IDs. + +Upstream references: [VKD3D capability parsing](https://github.com/HansKristian-Work/vkd3d-proton/blob/master/libs/vkd3d/device.c), +[VKD3D options](https://github.com/HansKristian-Work/vkd3d-proton#environment-variables), +[Proton runtime options](https://github.com/ValveSoftware/Proton/tree/proton_11.0#runtime-config-options), +[Mesa variables](https://docs.mesa3d.org/envvars.html), +[DXVK variables](https://github.com/doitsujin/dxvk#environment-variables), +[DXVK frame-limiter changes](https://github.com/doitsujin/dxvk/releases). + +Validation: `./gradlew testDebugUnitTest` and +`python3 -m unittest discover -s tools/tests -p test_game_environment.py`. +Actual game compatibility depends on the installed Proton, VKD3D and Vulkan driver; +these checks do not establish that every device supports feature level 12_2 or SM 6_9. diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md new file mode 100644 index 000000000..4c4efc0e1 --- /dev/null +++ b/docs/development/steam-game-imports.md @@ -0,0 +1,67 @@ +# Steam game imports + +Second Library still registers the selected Steam library. It now also scans Windows +executables in its immediate game subfolders and `steamapps/common`, using the same +importer as Added Games. Existing Steam manifests are preserved. + +`bannerlator-steam-games watch` runs beside the client. It identifies a game by an +existing manifest's install directory, a `steam_appid.txt` beside the game or selected +executable, or a unique normalized title from Steam's store search with an explicit +country. Matching also accepts the terminal Windows Edition and INTERGRADE suffixes; +multiple matches still remain unresolved. Artwork's fuzzy matching is deliberately not +used for identity. Ambiguous or unresolved titles remain non-Steam games. + +Ownership comes from the running native ARM64 client's `BIsSubscribedApp`, through +versioned SteamClient020 / SteamUser021 / STEAMAPPS_INTERFACE_VERSION008 interfaces. The +helper gets the account from that connection, not from a public profile. No API key, +password, profile visibility change, or CEF debugging port is needed. Each probe runs in +a bounded subprocess so library failures cannot crash the importer or client. + +The resulting snapshot is stored under that account's `userdata//config` and +refreshed every 30 seconds while logged in. Title lookups retry every five minutes and +when the source changes, so an early network failure does not end the watcher. Changed +status and probe failures are written to the session log. Startup and post-exit import +use the last successful snapshot for the selected account. The client reads manifests +and shortcuts only at start, so when a snapshot confirms owned titles that are not yet +imported, the watcher restarts the client once (not while a game runs or a download is in +progress) and the importer runs between the exit and the next start. An unavailable client or offline first launch falls back to shortcuts; existing +snapshots remain usable offline. Steam still enforces the current license at launch. + +For a confirmed game without a manifest, the importer links the source folder into the +internal Steam library and writes an installed manifest with `Universe=1` and +`StateFlags=4`. Steam ignores manifests without the universe field. A manifest without +installed depots makes Steam verify every file, so the importer carries the build another +client recorded: WinNative's `.winnative-steam/steamapps` manifest beside the game folder, +or a completed download's `.DepotDownloader/depot.config` depot manifest IDs. Steam then +only downloads what changed since that build. Bare manifests from earlier imports are +upgraded while Steam has not touched them. Without either record Steam still verifies. +WinNative's manifest also identifies the folder without a store lookup. Steam updates and uninstall +operate on the linked game files, so imported folders must be writable. Existing Steam +manifests and directories are preserved. Only the exact minimal manifests generated by +the earlier importer are migrated, with the matching source symlink still present. If +registration fails, the game remains a shortcut. Once Steam takes over an install, +manage it in Steam; forgetting an Added Games folder only removes its shortcuts. + +The account's `.droiddeck-routes.json` maps shortcut IDs to real Steam app IDs so the +Android launcher uses the same title and Proton prefix as Steam. Other accounts do not +inherit those routes. Managed shortcuts are replaced; user-created shortcuts and +unreadable shortcut files are preserved. Both routes use the existing ARM64 Proton +registration. + +## Validation + +Run `python3 -m unittest discover -s tools/tests -p 'test_*.py'` and Android unit tests. +Tests cover identity and edition matching, network recovery, account isolation, +owned/unowned/unknown routing, legacy manifest migration, manifest preservation, +filesystem collisions, shortcut preservation, and the versioned IPC call/cleanup +contract. On 2026-09-28, the ARM64 Steam client (1790545198) confirmed ownership and +installed status through ISteamApps for Final Fantasy VII Rebirth (2909400), Final +Fantasy VII Remake Intergrade (1462040), and Final Fantasy XV (637650), with all three +install paths resolving to the original second-library folders. The old managed +shortcuts were removed. This verifies library registration, not complete game launches. +Unowned fallback and account isolation are covered by automated tests. + +References: [Steam Apps +API](https://partner.steamgames.com/doc/api/ISteamApps#BIsSubscribedApp), [Valve's +versioned interfaces](https://github.com/ValveSoftware/Proton/tree/proton_11.0/lsteamcli +ent/steamworks_sdk_154). diff --git a/docs/progress-log.md b/docs/progress-log.md index d611fa084..8ca0aef37 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -7,6 +7,47 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d --- +## 2026-09-29 - `feat/controller-input`: the pad the way SteamOS has it + +Device-tested on the AYN Thor (Katamari under Proton Experimental ARM64). + +- **Why**: the client read the pad as an Xbox 360 controller, and games read the *same* node + wearing Steam Input's virtual identity (28de:11ff), because the client's own virtual pad needs + `/dev/uinput` and never appeared. Steam Input's layouts therefore never reached a game, and the + QAM was a timed Guide+A chord. InputPlumber itself cannot run in the sandbox (root, uinput, uhid, + udev, D-Bus), so what it provides is emulated in the interposer instead. +- **`/dev/uinput` stand-in** (`FAKE_EVDEV_UINPUT=1`, libfakeinput): a gamepad the client makes + becomes `/dev/input/event16+`, backed by a ring of the app's own format, with the client's name, + ids and bits; its writes are that ring's events. Other devices (virtual keyboard and mouse) are + accepted and dropped. `inputudev.c` describes these nodes to Wine's HID bus from a `.uevent` file + beside each one, and while one exists describes the app's pads as the Xbox 360 pad they are, so + Wine reads only Steam Input's output. Verified: the client makes "Microsoft X-Box 360 pad 0", + re-makes it at game launch, and the game binds it (`Controller 0 uses xinput : true`). +- **Steam Deck controller** (`FAKE_EVDEV_DECK=1`, Steam sessions): `/dev/hidraw16`, found through a + sysfs tree `SteamDeckPad.kt` binds in (usb_device → interface 2 → hid 28de:1205 → hidraw), streams + the Deck's 64-byte state report every 4 ms from ring 0 and answers feature reports as InputPlumber + does. systemd 261's libudev refuses a syspath not on sysfs, so `fstatfs`/`statfs` report sysfs + for that tree. The app's evdev nodes are withdrawn while it is on, and only the `steam` process + sees the Deck. QAM is a real button (snapshot bit 11). Verified: the client lists a Steam Deck + Controller (V1 HID protocol) and runs its handshake (0x83, 0xAE, 0x81/0x87 lizard off, 0x8F). +- **Setting**: Steam page → Touch & controls → **Controller**: *Steam Deck controller* (default) or + *Xbox 360 controller* (the pad of earlier versions, QAM by Guide+A; games still get Steam Input's + virtual pad). Debug switches: `droiddeck-no-uinput` (back to the 28de:11ff disguise), + `droiddeck-no-deck-pad` (forces the Xbox 360 pad). +- **Gyro**: `PadMotion.kt` feeds the handheld's own gyro and accelerometer (4 ms sampling, while + the session is on screen) into an IMU block after ring 0's events, turned to the screen and then + to the Deck's axes and units; the Deck report carries them. Verified: Steam's Gyro Calibration + page moves with the Thor (sh5001 IMU); at rest the accelerometer reads 1 g. +- **Deck grips + trackpads on the second screen** (`DeckControlsPanel.kt`, offered while the pad + is a Deck controller): tabs for the four grips (2x2), either trackpad with a click bar, and both + trackpads over the grips in a row; a second finger on a trackpad clicks it. True black for OLED. + Grips, pad positions, touch, click and pressure go through the same block after ring 0's events + as the gyro (`DeckControls.kt`) into the Deck report. +- **Not yet**: a Bluetooth pad's own IMU (DualSense); the + game's rumble on the virtual pad goes straight to the vibrator rather than back through the client. +- **Prior art checked**: WinNative and Bannerlator never emulated uinput or hidraw; Bannerlator's + `-steamdeck` mode stopped at "the virtual pad never arrives", which is this missing uinput. + ## 2026-09-28 - Cemu's Turnip fix released for every driver; A8xx driver back; proven on the Galaxy Z Fold 8 State: **DroidDeck main unchanged** (`d98c211`); this is driver-side work in `The412Banner/Banners-Turnip`, diff --git a/tools/build_local.sh b/tools/build_local.sh index a7a0d4d67..484e1f47b 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -89,7 +89,17 @@ linuxfs_replaced=1 rm -rf -- "${linuxfs_dir}" mkdir -p "${linuxfs_dir}" -if ! docker image inspect "${image_name}" >/dev/null 2>&1; then +# Docker Desktop's VM restarts now and then, and until its engine has loaded its image store it +# answers "No such image" for images it has. The rebuild that follows hangs on the registry +# (the base image's credentials go through docker-credential-desktop), so give a restarting daemon +# up to a minute before deciding the image is really missing. +image_present=0 +for _ in $(seq 1 30); do + if inspect_error=$(docker image inspect "${image_name}" 2>&1 >/dev/null); then image_present=1; break; fi + sleep 2 +done +if [[ "${image_present}" = 0 ]]; then + echo "Build image ${image_name} not found (${inspect_error:-no error}); building it." >&2 docker build --platform linux/amd64 -t "${image_name}" \ -f "${repo_root}/tools/local-cross.Dockerfile" "${repo_root}" fi @@ -164,20 +174,39 @@ if [[ -z "${github_repo}" ]]; then github_repo=${github_repo%.git} fi +# Pinned downloads are kept between builds, named by their checksum, so a rebuild fetches nothing +# it already has. A cached file is checked again before use; a bad one is fetched anew. +cache_dir=${DROIDDECK_BUILD_CACHE:-"${HOME}/.cache/droiddeck-build"} +mkdir -p "${cache_dir}" +# cached : prints the cached path, running the command (which writes +# to "$out") only when the cache has no file with that checksum. +cached() { + local sha=$1 name=$2 out + shift 2 + out="${cache_dir}/${sha}-${name}" + if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then + echo "${out}" + return 0 + fi + rm -f "${out}.part" + out="${out}.part" "$@" >&2 + printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2 + mv "${out}.part" "${out}" + echo "${out}" +} + if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then . "${repo_root}/tools/gamescope/release.env" - gamescope_archive="${staging_dir}/gamescope.tzst" - gh release download "${GAMESCOPE_TAG}" -R "${github_repo}" -p gamescope.tzst -O "${gamescope_archive}" - printf '%s %s\n' "${GAMESCOPE_SHA256}" "${gamescope_archive}" | shasum -a 256 -c - + gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \ + bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${github_repo}") zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}" test -f "${linuxfs_dir}/usr/local/bin/gamescope" fi if [[ -f "${repo_root}/tools/wlroots/release.env" ]]; then . "${repo_root}/tools/wlroots/release.env" - wlroots_archive="${staging_dir}/wlroots.tzst" - gh release download "${WLROOTS_TAG}" -R "${github_repo}" -p wlroots.tzst -O "${wlroots_archive}" - printf '%s %s\n' "${WLROOTS_SHA256}" "${wlroots_archive}" | shasum -a 256 -c - + wlroots_archive=$(cached "${WLROOTS_SHA256}" wlroots.tzst \ + bash -c 'gh release download "$0" -R "$1" -p wlroots.tzst -O "$out"' "${WLROOTS_TAG}" "${github_repo}") zstd -dc "${wlroots_archive}" | tar -xf - -C "${linuxfs_dir}" test -f "${linuxfs_dir}/usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so" fi @@ -187,9 +216,8 @@ mango_pkgs="${staging_dir}/mango-pkgs" mkdir -p "${mango_dir}" "${mango_pkgs}" while read -r package_sha256 package_url; do [[ -n "${package_url}" ]] || continue - package_archive="${staging_dir}/$(basename "${package_url}")" - curl -fsSL --retry 3 -o "${package_archive}" "${package_url}" - printf '%s %s\n' "${package_sha256}" "${package_archive}" | shasum -a 256 -c - + package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ + bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}") 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" @@ -201,11 +229,14 @@ install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/b pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"} if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then - curl -fsSL -o "${staging_dir}/pulseaudio-13.0.tar.gz" \ - https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz + pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz" + if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then + curl -fsSL -o "${pa_tarball}.part" \ + https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz + mv "${pa_tarball}.part" "${pa_tarball}" + fi mkdir -p "${pa_source}" - tar -xzf "${staging_dir}/pulseaudio-13.0.tar.gz" \ - -C "${pa_source}" --strip-components=1 + tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1 fi if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2 @@ -214,7 +245,17 @@ fi sink_output="${staging_dir}/sink-out" "${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}" -"${repo_root}/tools/proot/build.sh" "${repo_root}/app/src/main/jniLibs/arm64-v8a" +# proot is rebuilt only when its sources (source.env, the patches, the build script) changed since +# the libraries in jniLibs were built. +proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a" +proot_inputs=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1) +if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \ + && "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]]; then + echo "proot: sources unchanged, keeping ${proot_out}/libproot.so" +else + "${repo_root}/tools/proot/build.sh" "${proot_out}" + echo "${proot_inputs}" > "${proot_out}/.proot-inputs" +fi cp -p "${bundle_asset}" "${bundle_backup}" bundle_dir="${staging_dir}/pulseaudio-bundle" @@ -229,7 +270,7 @@ install -m755 "${sink_output}/module-aaudio-sink.so" \ "${bundle_dir}/modules/arm64/module-aaudio-sink.so" install -m755 "${sink_output}/module-directaudio-sink.so" \ "${bundle_dir}/modules/arm64/module-directaudio-sink.so" -tar -cf - -C "${bundle_dir}" . | zstd -19 -c > "${staging_dir}/pulseaudio.tzst" +tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst" bundle_replaced=1 mv "${staging_dir}/pulseaudio.tzst" "${bundle_asset}" @@ -309,6 +350,29 @@ grep -qi 'CN=Android, OU=Android, O=Android' <<<"${signature_output}" || { exit 1 } +# With DroidDeck's own key at hand, sign as CI's main builds are (tools/release/sign-apk.sh), so +# the apk installs over a release instead of being refused as a different signer. The key's +# location and password live in an untracked .signing.env (RELEASE_KEYSTORE, RELEASE_STORE_PASSWORD, +# RELEASE_KEY_ALIAS), looked for in this checkout and then in the main one, which worktrees share. +signing_env=${DROIDDECK_SIGNING_ENV:-} +if [[ -z "${signing_env}" ]]; then + for candidate in "${repo_root}/.signing.env" \ + "$(dirname "$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir 2>/dev/null || echo .)")/.signing.env"; do + [[ -f "${candidate}" ]] && { signing_env=${candidate}; break; } + done +fi +if [[ -n "${signing_env}" ]]; then + echo "Signing with DroidDeck's key (${signing_env})" + ( + set -a + # shellcheck disable=SC1090 + . "${signing_env}" + set +a + BUILD_TOOLS="${build_tools}" "${repo_root}/tools/release/sign-apk.sh" "${apk}" standard "${apk}.release" + ) + mv "${apk}.release" "${apk}" +fi + printf 'APK: %s\n' "${apk}" printf 'SHA-256: ' shasum -a 256 "${apk}" | awk '{print $1}' diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 8fa264904..ad4fc4b34 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -14,8 +14,11 @@ library list, before anything is published. - `0020-color-p3-red-is-wide-gamut.patch` - Armada, verbatim. - `0100-realtime-queue-and-gamepad-cursor.patch` - this app, two of Armada's ported by hand onto 3.16.29: realtime-priority Vulkan queues on request (`GAMESCOPE_FORCE_VULKAN_REALTIME=1`) - without CAP_SYS_NICE, which proot can never have; and the gamepad-driven cursor sprite following - the X pointer that XTest moves (it sat frozen). + without CAP_SYS_NICE, which proot can never have (a no-op on KGSL Turnip, which has a single + submit-queue priority); and the gamepad-driven cursor sprite following the X pointer that XTest + moves (it sat frozen). The X pointer is asked for only while a cursor image is drawn - every + vblank while shown, every 50 ms while hidden for inactivity - since each ask is a blocking round + trip to Xwayland on the paint thread; with no image, wlserver's position is used as upstream does. - `0110-wayland-backend-touch.patch` - this app: the nested Wayland backend bound only the host's pointer and keyboard, so a finger on the phone's screen never reached Steam. It now binds `wl_touch` too and hands each finger to wlserver's touch path (`wlserver_touchdown` / `motion` / @@ -27,6 +30,14 @@ library list, before anything is published. down moves nothing - so in the app's touchpad mode the Steam client saw no hover and a click landed wherever the pointer had last been. The motion now always warps the real pointer as well (`bAlwaysWarpCursor`), which the other touch modes did already. +- `0112-restore-iconified-game-on-resume.patch` - this app: the Steam menu is an overlay that + takes input without changing the focus window, and a fullscreen wine game minimizes itself when + it loses input. gamescope only takes a window out of iconic when the focus window changes, and + wine will not activate a window it believes iconic, so after Resume the game stayed minimized: a + black screen with its small caption in the top-left corner (Titanfall 2, GE-Proton 11). The + iconify request is remembered and the window goes back to NormalState before input returns to it, + 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). 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. diff --git a/tools/gamescope/patches/0100-realtime-queue-and-gamepad-cursor.patch b/tools/gamescope/patches/0100-realtime-queue-and-gamepad-cursor.patch index a49a0aa1a..0e390b099 100644 --- a/tools/gamescope/patches/0100-realtime-queue-and-gamepad-cursor.patch +++ b/tools/gamescope/patches/0100-realtime-queue-and-gamepad-cursor.patch @@ -7,8 +7,8 @@ index 54e4efc..024af02 100644 float queuePriorities = 1.0f; + // Without CAP_SYS_NICE gamescope never asks for realtime-priority queues. Under proot on -+ // Android there is no capability to have, but the driver may still grant the priority (Turnip -+ // does on Adreno), and the existing fallback below covers a driver that refuses. Opt in with ++ // Android there is no capability to have; the fallback below covers a driver that refuses. KGSL ++ // Turnip accepts but ignores it (one submit-queue priority, contexts created alike). Opt in with + // GAMESCOPE_FORCE_VULKAN_REALTIME=1. (Armada's --force-vulkan-realtime, as an environment switch.) + const char *pszForceRealtime = getenv( "GAMESCOPE_FORCE_VULKAN_REALTIME" ); + const bool useRealtimeVulkanQueue = gamescope::Process::HasCapSysNice() || ( pszForceRealtime && atoi( pszForceRealtime ) != 0 ); @@ -52,27 +52,10 @@ index 54e4efc..024af02 100644 fprintf(stderr, "vkCreateDevice failed with a high-priority queue (compute). Falling back to regular priority (all).\n"); queueCreateInfos[0].pNext = nullptr; diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp -index 18b799e..16f7846 100644 +index 10990b8..08afbc4 100644 --- a/src/steamcompmgr.cpp +++ b/src/steamcompmgr.cpp -@@ -2020,23 +2020,41 @@ MouseCursor::MouseCursor(xwayland_ctx_t *ctx) - - void MouseCursor::UpdatePosition() - { -+ // The gamepad-driven cursor is moved through XTest, which moves the X pointer and nothing -+ // else: wlserver's copy of the position never changes, so the sprite sat frozen while the -+ // pointer moved. Ask X where the pointer is. (Armada 0001, on 3.16.29.) -+ Window root_ret, child_ret; -+ int root_x = m_x, root_y = m_y, win_x = 0, win_y = 0; -+ unsigned int mask; -+ XQueryPointer( m_ctx->dpy, DefaultRootWindow( m_ctx->dpy ), -+ &root_ret, &child_ret, -+ &root_x, &root_y, -+ &win_x, &win_y, -+ &mask ); -+ - wlserver_lock(); - struct wlr_pointer_constraint_v1 *pConstraint = wlserver.GetCursorConstraint(); +@@ -2025,18 +2025,53 @@ void MouseCursor::UpdatePosition() if ( pConstraint && pConstraint->current.cursor_hint.enabled ) { m_bConstrained = true; @@ -84,23 +67,61 @@ index 18b799e..16f7846 100644 } - else + m_bConstrained = false; -+ wlserver_unlock(); -+ if ( root_x != m_x || root_y != m_y ) ++ // Nothing to draw (the gamepad UI, most games): the position only feeds focus and zoom, and ++ // wlserver's copy is what stock gamescope uses for those. No round trip to X. ++ if ( m_imageEmpty ) { - m_bConstrained = false; - -- m_x = wlserver.mouse_surface_cursorx; -- m_y = wlserver.mouse_surface_cursory; + m_x = wlserver.mouse_surface_cursorx; + m_y = wlserver.mouse_surface_cursory; ++ wlserver_unlock(); ++ return; + } + wlserver_unlock(); ++ ++ // The gamepad-driven cursor is moved through XTest, which moves the X pointer and nothing ++ // else: wlserver's copy of the position never changes, so the sprite sat frozen while the ++ // pointer moved. Ask X where the pointer is. (Armada 0001, on 3.16.29.) That is a blocking ++ // round trip to Xwayland on the paint thread, which waits while Xwayland is busy drawing the ++ // client's interface: once per vblank only while the sprite is shown, and every 50 ms while ++ // it is hidden for inactivity - enough to bring it back within a few frames of a move. ++ if ( wlserver.bCursorHidden ) ++ { ++ const uint64_t now = get_time_in_nanos(); ++ if ( now - m_ulLastPointerQuery < 50'000'000ul ) ++ return; ++ m_ulLastPointerQuery = now; ++ } ++ Window root_ret, child_ret; ++ int root_x = m_x, root_y = m_y, win_x = 0, win_y = 0; ++ unsigned int mask; ++ XQueryPointer( m_ctx->dpy, DefaultRootWindow( m_ctx->dpy ), ++ &root_ret, &child_ret, ++ &root_x, &root_y, ++ &win_x, &win_y, ++ &mask ); ++ ++ if ( root_x != m_x || root_y != m_y ) ++ { + m_x = root_x; + m_y = root_y; -+ if ( !m_imageEmpty ) -+ { -+ wlserver.ulLastMovedCursorTime = get_time_in_nanos(); -+ wlserver.bCursorHidden = !wlserver.bCursorHasImage; -+ hasRepaintNonBasePlane = true; -+ } - } -- wlserver_unlock(); ++ wlserver.ulLastMovedCursorTime = get_time_in_nanos(); ++ wlserver.bCursorHidden = !wlserver.bCursorHasImage; ++ hasRepaintNonBasePlane = true; ++ } } void MouseCursor::checkSuspension() +diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp +index c428784..bd62fd1 100644 +--- a/src/steamcompmgr.hpp ++++ b/src/steamcompmgr.hpp +@@ -109,6 +109,7 @@ private: + + int m_x = 0, m_y = 0; + bool m_bConstrained = false; ++ uint64_t m_ulLastPointerQuery = 0; + int m_hotspotX = 0, m_hotspotY = 0; + + gamescope::OwningRc m_texture; diff --git a/tools/gamescope/patches/0112-restore-iconified-game-on-resume.patch b/tools/gamescope/patches/0112-restore-iconified-game-on-resume.patch new file mode 100644 index 000000000..2eee045e4 --- /dev/null +++ b/tools/gamescope/patches/0112-restore-iconified-game-on-resume.patch @@ -0,0 +1,108 @@ +From: DroidDeck +Subject: [PATCH] steamcompmgr: restore a game that minimized itself behind the Steam menu + +The Steam menu is an overlay that takes input without changing the focus window. A fullscreen +wine game minimizes itself when it loses input (WM_CHANGE_STATE IconicState, which gamescope +fakes by setting WM_STATE). gamescope only puts a window back to NormalState when the focus +window changes, which never happens here, and wine will not activate a window it believes +iconic - so after Resume the game stayed minimized: a black screen with its 160x24 caption in +the top-left corner, 0 fps (seen with Titanfall 2 on GE-Proton 11). + +Remember the iconify request, restore NormalState before input returns to that window, and hand +focus over again so wine sees the restore before the activation. GAMESCOPE_RESTORE_FOCUS_WINDOW +on the root window asks for the same thing from outside. + +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 08afbc4..372a82c 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -4708,6 +4708,7 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win + /* Some games (e.g. DOOM Eternal) don't react well to being put back as + * iconic, so never do that. Only take them out of iconic. */ + set_wm_state( ctx, id, ICCCM_NORMAL_STATE ); ++ ctx->focus.focusWindow->iconifyRequested = false; + + gpuvis_trace_printf( "determine_and_apply_focus focus %lu", id ); + +@@ -4795,6 +4796,19 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win + if ( keyboardFocusWindow && ctx->currentKeyboardFocusWindow && find_win( ctx, ctx->currentKeyboardFocusWindow ) == keyboardFocusWin ) + keyboardFocusWindow = ctx->currentKeyboardFocusWindow; + ++ // An overlay that takes input (the Steam menu) moves input away without changing the focus window, and a ++ // fullscreen game iconifies itself when it loses input. The focus window never changed, so it is never taken ++ // out of iconic above, and wine will not activate a window it believes iconic: the game stays minimized ++ // (its 160x24 caption in the corner) after Resume. Put it back to NormalState before input returns to it, ++ // then hand focus over again so wine sees the restore first and the activation after it. ++ if ( inputFocus == ctx->focus.focusWindow && ctx->focus.focusWindow->iconifyRequested ) ++ { ++ ctx->focus.focusWindow->iconifyRequested = false; ++ xwm_log.infof( "restoring iconified focus window 0x%lx as input returns to it", ctx->focus.focusWindow->xwayland().id ); ++ set_wm_state( ctx, ctx->focus.focusWindow->xwayland().id, ICCCM_NORMAL_STATE ); ++ ctx->currentKeyboardFocusWindow = None; ++ } ++ + if ( ctx->focus.inputFocusWindow != inputFocus || + ctx->focus.inputFocusMode != inputFocus->inputFocusMode || + ctx->currentKeyboardFocusWindow != keyboardFocusWindow ) +@@ -6559,6 +6573,8 @@ handle_wm_change_state(xwayland_ctx_t *ctx, steamcompmgr_win_t *w, XClientMessag + if (state == ICCCM_ICONIC_STATE) { + xwm_log.debugf("Faking WM_CHANGE_STATE to ICONIC for window 0x%lx", w->xwayland().id); + set_wm_state( ctx, w->xwayland().id, ICCCM_ICONIC_STATE ); ++ w->iconifyRequested = true; ++ MakeFocusDirty(); + } else { + xwm_log.debugf("Unhandled WM_CHANGE_STATE to %ld for window 0x%lx", state, w->xwayland().id); + } +@@ -7539,6 +7555,19 @@ handle_property_notify(xwayland_ctx_t *ctx, XPropertyEvent *ev) + if ( set_sdr_input_gain( bit_cast(val) ) ) + hasRepaint = true; + } ++ if ( ev->atom == ctx->atoms.gamescopeRestoreFocusWindow ) ++ { ++ // Anything outside (the session's watcher) can ask for the same restore: NormalState on the focus ++ // window and focus handed to it again. Harmless on a window that is not iconic. ++ if ( ctx->focus.focusWindow && get_prop( ctx, ctx->root, ctx->atoms.gamescopeRestoreFocusWindow, 0 ) ) ++ { ++ xwm_log.infof( "restore requested for focus window 0x%lx", ctx->focus.focusWindow->xwayland().id ); ++ ctx->focus.focusWindow->iconifyRequested = false; ++ set_wm_state( ctx, ctx->focus.focusWindow->xwayland().id, ICCCM_NORMAL_STATE ); ++ ctx->currentKeyboardFocusWindow = None; ++ MakeFocusDirty(); ++ } ++ } + if ( ev->atom == ctx->atoms.gamescopeForceWindowsFullscreen ) + { + ctx->force_windows_fullscreen = !!get_prop( ctx, ctx->root, ctx->atoms.gamescopeForceWindowsFullscreen, 0 ); +@@ -9056,6 +9085,7 @@ void init_xwayland_ctx(uint32_t serverId, gamescope_xwayland_server_t *xwayland_ + ctx->atoms.gamescopeHDRTonemapOperator = XInternAtom( ctx->dpy, "GAMESCOPE_HDR_TONEMAP_OPERATOR", false ); + + ctx->atoms.gamescopeForceWindowsFullscreen = XInternAtom( ctx->dpy, "GAMESCOPE_FORCE_WINDOWS_FULLSCREEN", false ); ++ ctx->atoms.gamescopeRestoreFocusWindow = XInternAtom( ctx->dpy, "GAMESCOPE_RESTORE_FOCUS_WINDOW", false ); + + ctx->atoms.gamescopeColorLut3DOverride = XInternAtom( ctx->dpy, "GAMESCOPE_COLOR_3DLUT_OVERRIDE", false ); + ctx->atoms.gamescopeColorShaperLutOverride = XInternAtom( ctx->dpy, "GAMESCOPE_COLOR_SHAPERLUT_OVERRIDE", false ); +diff --git a/src/steamcompmgr_shared.hpp b/src/steamcompmgr_shared.hpp +index 66022d7..af93a23 100644 +--- a/src/steamcompmgr_shared.hpp ++++ b/src/steamcompmgr_shared.hpp +@@ -134,6 +134,8 @@ struct steamcompmgr_win_t { + + bool isFullscreen = false; + bool isSysTrayIcon = false; ++ // The client asked to be iconified (WM_CHANGE_STATE) and has not been put back to NormalState since. ++ bool iconifyRequested = false; + bool sizeHintsSpecified = false; + bool skipTaskbar = false; + bool skipPager = false; +diff --git a/src/xwayland_ctx.hpp b/src/xwayland_ctx.hpp +index 7b39ecb..81910a1 100644 +--- a/src/xwayland_ctx.hpp ++++ b/src/xwayland_ctx.hpp +@@ -228,6 +228,7 @@ struct xwayland_ctx_t final : public gamescope::IWaitable + Atom gamescopeHDRTonemapOperator; + + Atom gamescopeForceWindowsFullscreen; ++ Atom gamescopeRestoreFocusWindow; + + Atom gamescopeColorLut3DOverride; + Atom gamescopeColorShaperLutOverride; diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index a7a39e459..af715c671 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,2 +1,2 @@ -GAMESCOPE_TAG=gamescope-3.16.29-p3 -GAMESCOPE_SHA256=566e3b93931f37c30375d440d15ee76452892b842d2dc854cd3c06b926c8451b +GAMESCOPE_TAG=gamescope-3.16.29-p4 +GAMESCOPE_SHA256=e750fb34864bc2eb1160aeed29593e402bf9c8153fafd9fd18c77450bdd50574 diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index 6820a9dce..6e1d17595 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -55,10 +55,10 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') renderer=$WLR_RENDERER" fi export WLR_BACKENDS=wayland -# The app's compositor draws no wl_pointer cursor surfaces, so a cursor wlroots hands to its -# parent ("hardware" cursor on the wayland backend) never shows - on the GPU renderers the whole -# cursor was missing. Draw it into the desktop's own frames instead. -export WLR_NO_HARDWARE_CURSORS=${WLR_NO_HARDWARE_CURSORS:-1} +# The cursor goes to the app's compositor as a wl_pointer cursor surface ("hardware" cursor on the +# wayland backend), which the app draws as its pointer. Drawn into the desktop's own frames instead +# (WLR_NO_HARDWARE_CURSORS=1), it cost every frame a full-screen composite: a software cursor +# rules out direct scan-out, so a full-screen game was never handed to the app as it is. mkdir -p "$HOME/.config/labwc" "$HOME/.config/lxqt" # Our defaults for labwc and the panel, refreshed every session. What a user changes in the # panel's own settings lands in panel.conf and is kept; only rc.xml and autostart are ours. diff --git a/tools/linuxfs/desktop/droiddeck-desktop-gpu b/tools/linuxfs/desktop/droiddeck-desktop-gpu index 08d280aec..8a9a6b108 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop-gpu +++ b/tools/linuxfs/desktop/droiddeck-desktop-gpu @@ -12,6 +12,10 @@ import re HOME = os.environ.get("HOME", "/root") SYSTEM_DIR = "/usr/share/applications" +# The user's own AppImages (the front end's Add AppImage). +LOCAL_DIR = "/usr/local/share/applications" +# Flathub's games, as Flatpak exports them; the copies here win over these as they do over the system's. +FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/applications") USER_DIR = os.path.join(HOME, ".local/share/applications") MARK = "X-DroidDeck-GPU=1" # The client and its games already hand themselves to the app (bannerlator-steam-launch). @@ -37,6 +41,14 @@ def main_group(text): return lines[:start + 1], lines[start + 1:end], lines[end:] +def gpu_exec(exec_line): + """The Exec that runs a program on the GPU; a Flatpak app goes through its launcher, which + keeps it on gamescope's X server instead of the desktop's Wayland socket.""" + if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "): + exec_line = "/usr/local/bin/bannerlator-flatpak-run " + exec_line.split(" run ", 1)[1] + return "droiddeck-gpu " + exec_line + + def wrap(text): head, group, rest = main_group(text) if group is None: @@ -59,7 +71,7 @@ def wrap(text): for l in group: k = l.split("=", 1)[0].strip() if "=" in l else None if k == "Exec": - out_group.append("Exec=droiddeck-gpu " + exec_line) + out_group.append("Exec=" + gpu_exec(exec_line)) elif k == "Actions": continue else: @@ -73,7 +85,7 @@ def wrap(text): wrapped_rest = [] for l in rest: if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "): - l = "Exec=droiddeck-gpu " + l[5:] + l = "Exec=" + gpu_exec(l[5:]) wrapped_rest.append(l) if wrapped_rest and wrapped_rest[0].strip(): wrapped_rest.insert(0, "") @@ -92,8 +104,9 @@ def main(): on = enabled() os.makedirs(USER_DIR, exist_ok=True) written = set() - if on and os.path.isdir(SYSTEM_DIR): - for name in sorted(os.listdir(SYSTEM_DIR)): + sources = [d for d in (SYSTEM_DIR, LOCAL_DIR, FLATPAK_DIR) if os.path.isdir(d)] if on else [] + for source in sources: + for name in sorted(os.listdir(source)): if not name.endswith(".desktop") or SKIP.match(name): continue target = os.path.join(USER_DIR, name) @@ -101,7 +114,7 @@ def main(): if os.path.exists(target) and not ours(target): continue try: - with open(os.path.join(SYSTEM_DIR, name), encoding="utf-8", errors="replace") as f: + with open(os.path.join(source, name), encoding="utf-8", errors="replace") as f: text = wrap(f.read()) except OSError: continue diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-appimage-run b/tools/linuxfs/overlay/usr/local/bin/bannerlator-appimage-run new file mode 100755 index 000000000..fbe13caaf --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-appimage-run @@ -0,0 +1,63 @@ +#!/bin/bash +# An AppImage imported from the front end (AppImageManager), extracted once at import into +# /opt/appimages/user//app +# and started from there: proot has no FUSE to mount the image, and extracting it at every +# start (APPIMAGE_EXTRACT_AND_RUN) would cost the whole image in /tmp each time. +# bannerlator-appimage-run /opt/appimages/user/ [args...] +set -u +dir=${1:?usage: bannerlator-appimage-run [args...]} +shift +export APPDIR=$dir/app +# APPIMAGE is left unset on purpose: with it an app believes it runs from an image file and offers +# to add itself to the menu (DuckStation) or update the file in place - DroidDeck already does the +# one, and there is no image file for the other. +unset APPIMAGE +export ARGV0=$(cat "$dir/name" 2>/dev/null || basename "$dir") +if [ ! -x "$APPDIR/AppRun" ]; then + echo "bannerlator-appimage-run: $APPDIR/AppRun is missing; import the AppImage again" >&2 + exit 127 +fi +# Browsers sandbox their own children with namespaces and a setuid helper, neither of which proot +# can give them (the Flatpak sandboxes get the same; see BwrapSpawner): Firefox and its forks (Zen, +# LibreWolf) by these switches, Electron and Chromium builds by --no-sandbox. Chromium on Wayland +# also asks the render node for a DRM version KGSL cannot give, so with an X server up it stays on +# X11, which it picks from the session type. +export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1 +export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1 +flags=() +if [ -e "$APPDIR/chrome-sandbox" ] || compgen -G "$APPDIR/*/chrome-sandbox" >/dev/null; then + flags+=(--no-sandbox) + if [ -n "${DISPLAY:-}" ]; then + export XDG_SESSION_TYPE=x11 + unset WAYLAND_DISPLAY + flags+=(--ozone-platform=x11) + fi +fi +echo "== appimage $ARGV0 ($APPDIR) ${flags[*]}" +cd "$APPDIR" || exit 1 +# Apps expect a session bus; Electron's main process traps (SIGTRAP) on an address it cannot +# parse. A run mode has none, so one is started for the app, as for Flatpak apps. +case ${DBUS_SESSION_BUS_ADDRESS:-} in + unix:*) "$APPDIR/AppRun" "${flags[@]}" "$@" ;; + *) unset DBUS_SESSION_BUS_ADDRESS + if command -v dbus-run-session >/dev/null 2>&1; then + dbus-run-session -- "$APPDIR/AppRun" "${flags[@]}" "$@" + else + "$APPDIR/AppRun" "${flags[@]}" "$@" + fi ;; +esac +rc=$? +# The program a session was started for may hand over to another process and exit: Electron apps +# relaunch themselves (Obsidian on its first start), launchers fork their real program. The +# session ends with this script, and takes the rest with it - so it waits while anything running +# from the image is still up. +image_running() { + local p exe + for p in /proc/[0-9]*; do + exe=$(readlink "$p/exe" 2>/dev/null) || continue + case $exe in "$APPDIR"/*) return 0 ;; esac + done + return 1 +} +while image_running; do sleep 2; done +exit $rc diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-bwrap b/tools/linuxfs/overlay/usr/local/bin/bannerlator-bwrap new file mode 100644 index 000000000..5a3a73951 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-bwrap @@ -0,0 +1,318 @@ +#!/usr/bin/python3 +# bubblewrap for Flatpak (FLATPAK_BWRAP), in a runtime that cannot have it. +# +# bwrap builds each sandbox from mount namespaces, which Android gives no app. proot gives the same +# picture - Flatpak's runtime as /usr, the app as /app, host paths bound where Flatpak asks - but a +# proot nested inside the session's proot runs every system call through two tracers, some thirty +# times slower on a program's start. So a sandbox is described to the app instead, over a socket +# only this app's uid may use, and the app starts it as a proot of its own beside the session's +# (BwrapSpawner). This process stands in for the sandbox until it ends: its output, its pid for +# --info-fd, and its exit status come back here. +# +# Sandboxes that remap nothing - Flatpak's install triggers (`--ro-bind / /` and the directory they +# update) and the D-Bus proxy (every top-level directory bound onto itself) - need no proot at all +# and run here directly, with the file descriptors Flatpak handed them. +import base64 +import json +import os +import signal +import socket +import struct +import sys + +SOCKET = "\0com.droiddeck.launcher.bwrap" +VERSION = "bubblewrap 0.11.0 (droiddeck)" + +# Options and how many arguments each takes; bwrap(1). +NO_ARG = { + "--unshare-user", "--unshare-user-try", "--unshare-ipc", "--unshare-pid", "--unshare-net", + "--unshare-uts", "--unshare-cgroup", "--unshare-cgroup-try", "--unshare-all", "--share-net", + "--disable-userns", "--assert-userns-disabled", "--clearenv", "--new-session", + "--die-with-parent", "--as-pid-1", "--level-prefix", "--tmp-overlay", "--ro-overlay", +} +ONE_ARG = { + "--args", "--argv0", "--userns", "--userns2", "--pidns", "--uid", "--gid", "--hostname", + "--chdir", "--unsetenv", "--lock-file", "--sync-fd", "--remount-ro", "--exec-label", + "--file-label", "--proc", "--dev", "--tmpfs", "--mqueue", "--dir", "--seccomp", + "--add-seccomp-fd", "--block-fd", "--userns-block-fd", "--info-fd", "--json-status-fd", + "--cap-add", "--cap-drop", "--perms", "--size", "--overlay-src", +} +TWO_ARG = { + "--setenv", "--bind", "--bind-try", "--dev-bind", "--dev-bind-try", "--ro-bind", + "--ro-bind-try", "--bind-fd", "--ro-bind-fd", "--file", "--bind-data", "--ro-bind-data", + "--symlink", "--chmod", +} +THREE_ARG = {"--overlay"} + + +def read_fd(fd): + chunks = [] + while True: + b = os.read(fd, 65536) + if not b: + break + chunks.append(b) + os.close(fd) + return b"".join(chunks) + + +def fd_path(fd): + return os.readlink("/proc/self/fd/%d" % fd) + + +def expand(argv): + """argv with every --args FD replaced by the NUL-separated arguments read from FD.""" + out = [] + i = 0 + while i < len(argv): + a = argv[i] + if a == "--args" and i + 1 < len(argv): + data = read_fd(int(argv[i + 1])) + # Each argument ends in a NUL; an empty one (--setenv LD_LIBRARY_PATH "") is kept. + parts = data.split(b"\0") + if parts and parts[-1] == b"": + parts.pop() + out.extend(x.decode("utf-8", "surrogateescape") for x in parts) + i += 2 + continue + out.append(a) + i += 1 + return out + + +class Spec: + def __init__(self): + self.ops = [] + self.env = dict(os.environ) + self.cwd = None + self.info_fds = [] + self.json_fds = [] + self.keep_fds = [] + self.command = [] + self.argv0 = None + + +def parse(argv): + s = Spec() + perms = None + i = 0 + while i < len(argv): + a = argv[i] + if a == "--": + s.command = argv[i + 1:] + break + if not a.startswith("--"): + s.command = argv[i:] + break + if a in ("--version",): + print(VERSION) + sys.exit(0) + if a == "--help": + print("usage: bwrap [OPTIONS...] [--] COMMAND [ARGS...]") + sys.exit(0) + n = 0 if a in NO_ARG else 1 if a in ONE_ARG else 2 if a in TWO_ARG else 3 if a in THREE_ARG else -1 + if n < 0: + sys.stderr.write("bwrap: Unknown option %s\n" % a) + sys.exit(1) + args = argv[i + 1:i + 1 + n] + if len(args) < n: + sys.stderr.write("bwrap: %s takes %d arguments\n" % (a, n)) + sys.exit(1) + i += 1 + n + op_perms, perms = perms, None + if a == "--perms": + perms = int(args[0], 8) + elif a == "--clearenv": + s.env = {"PWD": os.getcwd()} if "PWD" in os.environ else {} + elif a == "--setenv": + s.env[args[0]] = args[1] + elif a == "--unsetenv": + s.env.pop(args[0], None) + elif a == "--chdir": + s.cwd = args[0] + elif a == "--argv0": + s.argv0 = args[0] + elif a in ("--bind", "--bind-try", "--dev-bind", "--dev-bind-try", "--ro-bind", "--ro-bind-try"): + s.ops.append({"t": "bind", "src": args[0], "dest": args[1], "try": a.endswith("-try"), + "ro": a.startswith("--ro")}) + elif a in ("--bind-fd", "--ro-bind-fd"): + fd = int(args[0]) + s.ops.append({"t": "bind", "src": fd_path(fd), "dest": args[1], "try": False, + "ro": a.startswith("--ro")}) + os.close(fd) + elif a in ("--file", "--bind-data", "--ro-bind-data"): + s.ops.append({"t": "file", "dest": args[1], "data": read_fd(int(args[0])), + "perms": op_perms if op_perms is not None else 0o666 if a == "--file" else 0o600}) + elif a == "--symlink": + s.ops.append({"t": "symlink", "target": args[0], "dest": args[1]}) + elif a == "--dir": + s.ops.append({"t": "dir", "dest": args[0], "perms": op_perms if op_perms is not None else 0o755}) + elif a in ("--tmpfs", "--mqueue"): + s.ops.append({"t": "dir", "dest": args[0], "perms": op_perms if op_perms is not None else 0o755, + "empty": True}) + elif a == "--proc": + s.ops.append({"t": "proc", "dest": args[0]}) + elif a == "--dev": + s.ops.append({"t": "dev", "dest": args[0]}) + elif a in ("--seccomp", "--add-seccomp-fd"): + # proot is the sandbox; there is no filter to install under it. + os.close(int(args[0])) + elif a == "--block-fd": + read_fd(int(args[0])) + elif a == "--sync-fd": + s.keep_fds.append(int(args[0])) + elif a == "--info-fd": + s.info_fds.append(int(args[0])) + elif a == "--json-status-fd": + s.json_fds.append(int(args[0])) + # Everything else - namespaces, capabilities, labels, locks, --remount-ro, --chmod - has + # nothing to act on under proot. + if not s.command: + sys.stderr.write("bwrap: No command specified\n") + sys.exit(1) + return s + + +def real(path): + try: + return os.path.realpath(path) + except OSError: + return path + + +def remaps_nothing(s): + """True when every path in the sandbox is what it is out here already.""" + for op in s.ops: + t = op["t"] + if t == "bind": + src = real(op["src"]) + if not os.path.exists(src): + if op["try"]: + continue + return False + if src != real(op["dest"]) and not (op["src"] == "/" and op["dest"] == "/"): + return False + elif t == "symlink": + if not os.path.islink(op["dest"]) or os.readlink(op["dest"]) != op["target"]: + return False + elif t == "file": + # The D-Bus proxy's /.flatpak-info names the app to the bus; nothing here reads it. + if op["dest"] != "/.flatpak-info": + return False + elif t == "dir": + if not os.path.isdir(op["dest"]) or op.get("empty") and op["dest"] not in ("/tmp", "/var/tmp", "/run"): + return False + elif t in ("proc", "dev"): + if op["dest"] != "/" + t: + return False + return True + + +def report_pid(s, pid): + for fd in s.info_fds: + try: + os.write(fd, json.dumps({"child-pid": pid}).encode() + b"\n") + os.close(fd) + except OSError: + pass + for fd in s.json_fds: + try: + os.write(fd, json.dumps({"child-pid": pid}).encode() + b"\n") + except OSError: + pass + + +def run_here(s): + report_pid(s, os.getpid()) + for fd in s.json_fds: + os.close(fd) + if s.cwd: + os.chdir(s.cwd) + argv = list(s.command) + program = argv[0] + if s.argv0: + argv[0] = s.argv0 + try: + os.execvpe(program, argv, s.env) + except OSError as e: + sys.stderr.write("bwrap: execvp %s: %s\n" % (program, e.strerror)) + sys.exit(1) + + +def send(sock, kind, payload): + sock.sendall(kind + struct.pack(">I", len(payload)) + payload) + + +def recv_exact(sock, n): + buf = b"" + while len(buf) < n: + b = sock.recv(n - len(buf)) + if not b: + return None + buf += b + return buf + + +def run_by_app(s): + ops = [] + for op in s.ops: + op = dict(op) + if op["t"] == "bind": + # The app resolves no guest symlinks; hand it the path they lead to. + op["src"] = real(op["src"]) + if op["t"] == "file": + op["data"] = base64.b64encode(op["data"]).decode() + ops.append(op) + argv = list(s.command) + if s.argv0: + argv[0] = s.argv0 + request = {"argv": argv, "env": s.env, "cwd": s.cwd or "/", "ops": ops} + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.connect(SOCKET) + except OSError as e: + sys.stderr.write("bwrap: DroidDeck is not answering (%s); open DroidDeck and try again\n" % e) + sys.exit(1) + send(sock, b"R", json.dumps(request).encode()) + # This process is the sandbox as far as Flatpak is concerned: ended, it takes the sandbox down. + for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + signal.signal(sig, lambda *_: os._exit(128 + 15)) + status = 1 + out = sys.stdout.buffer + while True: + head = recv_exact(sock, 5) + if head is None: + sys.stderr.write("bwrap: DroidDeck closed the sandbox\n") + break + kind, size = head[:1], struct.unpack(">I", head[1:])[0] + payload = recv_exact(sock, size) if size else b"" + if payload is None: + break + if kind == b"P": + report_pid(s, int(payload)) + elif kind == b"O": + out.write(payload) + out.flush() + elif kind == b"E": + sys.stderr.write("bwrap: %s\n" % payload.decode("utf-8", "replace")) + elif kind == b"X": + status = int(payload) + break + for fd in s.json_fds: + try: + os.write(fd, json.dumps({"exit-code": status}).encode() + b"\n") + except OSError: + pass + sys.exit(status) + + +def main(): + s = parse(expand(sys.argv[1:])) + if remaps_nothing(s): + run_here(s) + else: + run_by_app(s) + + +if __name__ == "__main__": + main() diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-desktop-games b/tools/linuxfs/overlay/usr/local/bin/bannerlator-desktop-games index 16fc736ec..7690fd219 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-desktop-games +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-desktop-games @@ -11,7 +11,7 @@ import sys HOME = os.environ.get("HOME", "/root") STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HOME, ".local/share/Steam") -LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/bannerlator-sd", "SD Games")) +LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd", "SD Games")) # The client's own tools and runtimes live in steamapps beside the games; they are not titles. NOT_GAMES = {228980, 1493710, 3127680, 4183110, 4427310, 4185400} APPS_DIR = os.path.join(HOME, ".local/share/applications") diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak b/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak new file mode 100644 index 000000000..3b322539f --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak @@ -0,0 +1,237 @@ +#!/usr/bin/python3 +# The app's store talks to Flatpak through this: one JSON object per line on stdout, so progress +# reaches the front end as numbers rather than a terminal's redrawn bar. Per-user installation, +# Flathub as the remote, this device's architecture. +# +# bannerlator-flatpak install the app and whatever runtimes it needs +# bannerlator-flatpak uninstall the app, then runtimes nothing uses any more +# bannerlator-flatpak update [] one app, or everything with an update +# bannerlator-flatpak updates what has one (a "updates" line) +# +# Lines: {"e":"op","i":1,"n":3,"kind":"install","ref":"..."} as each step starts, +# {"e":"progress","i":1,"n":3,"percent":45,"status":"..."} while it runs, +# {"e":"error","message":"..."} and {"e":"done"} at the end. Exit status 0 on success. +import json +import os +import sys + +os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/bannerlator-bwrap") + +import gi # noqa: E402 + +gi.require_version("Flatpak", "1.0") +from gi.repository import Flatpak, GLib # noqa: E402 + +REMOTE = "flathub" + + +def prepare_rootfs(): + """Some runtimes (KDE 6.10) ship etc/resolv.conf as a link to /run/host/monitor/resolv.conf. + Deploying one, Flatpak removes that link only if GIO reports it existing, and GIO follows it: + dangling here, it was left in place and making Flatpak's own link failed ("File exists"). + With the target present in the rootfs the link resolves and the deploy goes through.""" + target = "/run/host/monitor/resolv.conf" + try: + if not os.path.exists(target): + os.makedirs(os.path.dirname(target), exist_ok=True) + try: + with open("/etc/resolv.conf", "rb") as src: + data = src.read() + except OSError: + data = b"" + with open(target, "wb") as dst: + dst.write(data) + except OSError as err: + emit(e="warning", message="could not prepare %s: %s" % (target, err)) + + +def emit(**kw): + sys.stdout.write(json.dumps(kw) + "\n") + sys.stdout.flush() + + +def installation(): + return Flatpak.Installation.new_user(None) + + +def app_ref(inst, app_id): + """The installed ref of an app, or None.""" + for ref in inst.list_installed_refs_by_kind(Flatpak.RefKind.APP, None): + if ref.get_name() == app_id: + return ref + return None + + +def transaction(inst): + t = Flatpak.Transaction.new_for_installation(inst, None) + t.set_no_interaction(True) + state = {"i": 0, "n": 0, "error": None} + + def on_ready(tr): + state["n"] = len(tr.get_operations()) + return True + + def on_new_operation(tr, op, progress): + state["i"] += 1 + emit(e="op", i=state["i"], n=state["n"], kind=op.get_operation_type().value_nick, ref=op.get_ref()) + progress.set_update_frequency(500) + + def changed(p): + emit(e="progress", i=state["i"], n=state["n"], percent=p.get_progress(), status=p.get_status() or "") + progress.connect("changed", changed) + + def on_operation_error(tr, op, err, details): + # A runtime extension that fails to install (a missing translation, an unneeded GL + # driver) is not worth losing the app over; anything else ends the transaction. + # FLATPAK_TRANSACTION_ERROR_DETAILS_NON_FATAL is 1, but PyGObject does not always hand the + # flags over ("g_value_get_flags: assertion ... failed" and a 0). An extension installed + # alongside an app - its translations, debug data, a GL or codecs runtime - is what Flatpak + # marks non-fatal, as the flatpak CLI does: its failure costs that extension, not the app. + try: + non_fatal = bool(int(details) & 1) + except (TypeError, ValueError): + non_fatal = False + if not non_fatal: + try: + related = bool(op.get_related_to_ops()) + except (AttributeError, TypeError): + related = False + ref_id = (op.get_ref() or "").split("/")[1:2] + ref_id = ref_id[0] if ref_id else "" + non_fatal = related or ref_id.endswith((".Locale", ".Debug")) or ".GL." in ref_id or "codecs" in ref_id + emit(e="warning" if non_fatal else "error", message="%s: %s" % (op.get_ref(), err.message)) + if not non_fatal: + state["error"] = err.message + return non_fatal + + t.connect("ready", on_ready) + t.connect("new-operation", on_new_operation) + t.connect("operation-error", on_operation_error) + # A dependency found on more than one remote comes from the first (Flathub, the only one). + t.connect("choose-remote-for-ref", lambda tr, ref, runtime_ref, remotes: 0) + t.connect("end-of-lifed-with-rebase", lambda *a: False) + t.connect("add-new-remote", lambda *a: False) + return t, state + + +def run(t, state, report_done=True): + try: + t.run(None) + except GLib.Error as err: + if state["error"] is None and not err.matches(Flatpak.error_quark(), Flatpak.Error.ABORTED): + state["error"] = err.message + if state["error"]: + emit(e="error", message=state["error"]) + return 1 + if report_done: + emit(e="done") + return 0 + + +def install(app_id): + inst = installation() + arch = Flatpak.get_default_arch() + if app_ref(inst, app_id) is not None: + emit(e="done", note="already installed") + return 0 + # Flathub publishes apps on "stable"; libflatpak's default branch is "master". + branch, last = None, None + for candidate in ("stable", "master"): + try: + branch = inst.fetch_remote_ref_sync(REMOTE, Flatpak.RefKind.APP, app_id, arch, candidate, None).get_branch() + break + except GLib.Error as err: + last = err + if branch is None: + emit(e="error", message="%s is not on Flathub for %s (%s)" % (app_id, arch, last.message if last else "no branch")) + return 1 + t, state = transaction(inst) + t.add_install(REMOTE, "app/%s/%s/%s" % (app_id, arch, branch), None) + rc = run(t, state, report_done=False) + # A failure the transaction did not report (an error handler that raised, say) must not read + # as an install: the app is there, or it is not. + if rc == 0 and app_ref(installation(), app_id) is None: + emit(e="error", message="%s did not install; see flatpak-install.log" % app_id) + return 1 + if rc == 0: + emit(e="done") + return rc + + +def uninstall(app_id): + inst = installation() + ref = app_ref(inst, app_id) + if ref is None: + emit(e="done", note="not installed") + return 0 + t, state = transaction(inst) + t.add_uninstall(ref.format_ref()) + rc = run(t, state) + if rc == 0: + # Runtimes only this app used; Flatpak's own `uninstall --unused`. + try: + unused = inst.list_unused_refs(None, None) + except GLib.Error: + unused = [] + if unused: + t, state = transaction(inst) + for r in unused: + t.add_uninstall(r.format_ref()) + run(t, state) + return rc + + +def updatable(inst): + try: + return inst.list_installed_refs_for_update(None) + except GLib.Error as err: + emit(e="error", message=err.message) + return None + + +def update(app_id=None): + inst = installation() + refs = updatable(inst) + if refs is None: + return 1 + if app_id: + refs = [r for r in refs if r.get_name() == app_id or r.get_kind() == Flatpak.RefKind.RUNTIME] + if not refs: + emit(e="done", note="up to date") + return 0 + t, state = transaction(inst) + for r in refs: + t.add_update(r.format_ref(), None, None) + return run(t, state) + + +def updates(): + refs = updatable(installation()) + if refs is None: + return 1 + emit(e="updates", apps=sorted({r.get_name() for r in refs if r.get_kind() == Flatpak.RefKind.APP}), + runtimes=len([r for r in refs if r.get_kind() == Flatpak.RefKind.RUNTIME])) + return 0 + + +def main(): + if len(sys.argv) < 2: + sys.stderr.write(__doc__ or "usage: bannerlator-flatpak install|uninstall|update|updates [app-id]\n") + return 2 + cmd, args = sys.argv[1], sys.argv[2:] + if cmd in ("install", "update"): + prepare_rootfs() + if cmd == "install" and args: + return install(args[0]) + if cmd == "uninstall" and args: + return uninstall(args[0]) + if cmd == "update": + return update(args[0] if args else None) + if cmd == "updates": + return updates() + sys.stderr.write("usage: bannerlator-flatpak install|uninstall|update|updates [app-id]\n") + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak-run b/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak-run new file mode 100644 index 000000000..203769d13 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak-run @@ -0,0 +1,28 @@ +#!/bin/bash +# A Flatpak app from the front end, full screen under gamescope like an emulator: +# bannerlator-flatpak-run [args...] +set -u +export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap +case ":${XDG_DATA_DIRS:-}:" in + *"/flatpak/exports/share:"*) ;; + *) export XDG_DATA_DIRS=$HOME/.local/share/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share} ;; +esac +# Under gamescope - a program's session (BL_INSIDE), or droiddeck-gpu from the desktop +# (GAMESCOPE_WAYLAND_DISPLAY) - windows have to reach gamescope's X server. Flatpak would hand an +# app wayland-0 (it finds it in the runtime directory even with WAYLAND_DISPLAY unset) and the +# window would open behind gamescope. gamescope's own Wayland socket is no way out: Chromium on +# Wayland asks the render node it names for its DRM version, which KGSL cannot answer, and exits. +# The session is X11 as far as an app can tell; Electron picks its platform from that. +# Its own flatpak options (--branch, --command, from a menu entry) come first, then the app id. +socket=() +if [ -n "${BL_INSIDE:-}" ] || [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then + unset WAYLAND_DISPLAY + export XDG_SESSION_TYPE=x11 + socket=(--nosocket=wayland --socket=x11) +fi +echo "== flatpak run ${socket[*]} $*" +# Apps expect a session bus (settings, portals, single-instance checks); a run mode has none. +if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then + exec dbus-run-session -- flatpak run "${socket[@]}" "$@" +fi +exec flatpak run "${socket[@]}" "$@" diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak-setup b/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak-setup new file mode 100644 index 000000000..9020b38fe --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-flatpak-setup @@ -0,0 +1,121 @@ +#!/bin/bash +# Puts Flatpak into the runtime, with Flathub as a per-user remote. Run by the app under proot's +# fake root (pacman and pacman-key refuse any other uid), outside a session. +# +# The runtime's pacman database lists only the base image: the desktop and emulator packages were +# unpacked over it without registering. Asked for flatpak the usual way, pacman "reinstalls" about +# a hundred of those - Mesa among them, over the runtime's own Turnip build with its KGSL backend - +# and then runs every hook in the image, mkinitcpio included. So pacman only fetches and checks the +# few packages Flatpak needs on top of this image, verifying each against the Arch Linux ARM +# keyring, and they are unpacked here without hooks or scripts, like the desktop package itself. +# +# bannerlator-flatpak-setup install or repair; prints "== STEP ..." milestones +set -u +export LANG=C.UTF-8 +step() { echo "== STEP $*"; } +fail() { echo "== FAIL $*"; exit 1; } + +# Flatpak, the libraries it and appstream add to this image, and the D-Bus proxy flatpak run puts +# between an app and the session bus. bubblewrap is not among them: Android gives an app no user +# namespaces, and bannerlator-bwrap stands in for it (FLATPAK_BWRAP). +PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy" +# Libraries Flatpak and the store's helper also need, which the Desktop package brings but a +# runtime without it may lack: each is fetched only when its file is not already there. +while read -r pkg probe; do + [ -n "$pkg" ] || continue + compgen -G "$probe" >/dev/null || PACKAGES="$PACKAGES $pkg" +done <<'NEEDS' +json-glib /usr/lib/libjson-glib-1.0.so.0 +fuse3 /usr/lib/libfuse3.so.4 +fuse-common /etc/fuse.conf +libsodium /usr/lib/libsodium.so.* +libstemmer /usr/lib/libstemmer.so.* +polkit /usr/lib/libpolkit-gobject-1.so.0 +mpdecimal /usr/lib/libmpdec.so.* +python /usr/bin/python3 +libgirepository /usr/lib/libgirepository-2.0.so.0 +gobject-introspection-runtime /usr/lib/girepository-1.0/GObject-2.0.typelib +python-gobject /usr/lib/python3*/site-packages/gi/__init__.py +NEEDS +WORK=/var/cache/droiddeck-flatpak +CONF=$WORK/pacman.conf +mkdir -p "$WORK/pkg" "$WORK/db" || fail "cannot create $WORK" + +# The image's pacman.conf names a download user this rootfs does not have (only root exists) and a +# sandbox proot cannot set up. Its one mirror is plain HTTP; these serve the same repos over TLS. +{ for m in https://ca.us.mirror.archlinuxarm.org https://fl.us.mirror.archlinuxarm.org \ + https://de3.mirror.archlinuxarm.org https://nl.mirror.archlinuxarm.org; do + echo "Server = $m/\$arch/\$repo"; done + grep '^Server' /etc/pacman.d/mirrorlist 2>/dev/null; } > "$WORK/mirrorlist" +sed -e 's/^DownloadUser/#DownloadUser/' \ + -e 's/^\[options\]/[options]\nDisableSandbox/' \ + -e "s#^Include *= */etc/pacman.d/mirrorlist#Include = $WORK/mirrorlist#" \ + /etc/pacman.conf > "$CONF" || fail "no /etc/pacman.conf" + +if [ ! -f /etc/pacman.d/gnupg/pubring.gpg ] && [ ! -f /etc/pacman.d/gnupg/pubring.kbx ]; then + step "Preparing the package keyring" + pacman-key --init >/dev/null 2>&1 || fail "pacman-key --init failed" + pacman-key --populate archlinuxarm >/dev/null 2>&1 || fail "pacman-key --populate failed" +fi + +# A database of our own, so the image's stays exactly as it was built: -Sy on it would leave the +# rest of the image a partial upgrade behind the repos. +step "Reading the package lists" +pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy >/dev/null 2>&1 \ + || pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1 | tail -3 \ + || fail "could not reach the Arch Linux ARM mirrors" +[ -f "$WORK/db/sync/extra.db" ] || fail "could not reach the Arch Linux ARM mirrors" + +step "Downloading Flatpak" +# -w only downloads; pacman still checks each package's signature against the keyring. -dd: the +# dependencies are already in the image (and checked below by what the binaries actually link). +out=$(pacman --config "$CONF" --dbpath "$WORK/db" --cachedir "$WORK/pkg" --noconfirm -Sw -dd $PACKAGES 2>&1) +rc=$? +echo "$out" | grep -vE '^\s*$' | tail -4 +[ $rc -eq 0 ] || fail "download failed" + +step "Installing Flatpak" +for name in $PACKAGES; do + ver=$(pacman --config "$CONF" --dbpath "$WORK/db" -Sp --print-format '%v' -dd "$name" 2>/dev/null | tail -1) + file=$(ls "$WORK/pkg/$name-$ver-"*.pkg.tar.* 2>/dev/null | grep -v '\.sig$' | head -1) + [ -n "$file" ] || fail "no package file for $name $ver" + bsdtar -xpf "$file" -C / --exclude .PKGINFO --exclude .BUILDINFO --exclude .MTREE --exclude .INSTALL \ + || fail "could not unpack $name" + echo "$name $ver" >> "$WORK/installed.new" +done +mv -f "$WORK/installed.new" "$WORK/installed" +# Only the newest file of each package is worth keeping for a repair. +find "$WORK/pkg" -type f -mtime +1 -delete 2>/dev/null + +# What the binaries link is the real dependency list: anything this image lacks shows here. +missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do + ldd "$f" 2>&1 | grep -E 'not found|version .* not found' +done | sort -u) +[ -z "$missing" ] || { echo "$missing"; fail "Flatpak is missing libraries"; } +flatpak --version >/dev/null 2>&1 || fail "flatpak does not start" +python3 -c 'import gi; gi.require_version("Flatpak", "1.0"); from gi.repository import Flatpak' 2>/dev/null \ + || fail "the store helper cannot load libflatpak from Python" + +step "Adding Flathub" +export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap +# Flathub's descriptor - its URL and the key its commits are signed with - is carried here rather +# than fetched: adding the remote then needs no network, and a descriptor that did not arrive +# whole cannot be what failed. Flathub's own copy: https://dl.flathub.org/repo/flathub.flatpakrepo +cat > "$WORK/flathub.flatpakrepo" <<'REPO' +[Flatpak Repo] +Title=Flathub +Url=https://dl.flathub.org/repo/ +Homepage=https://flathub.org/ +Comment=Central repository of Flatpak applications +Description=Central repository of Flatpak applications +Icon=https://dl.flathub.org/repo/logo.svg +GPGKey=mQINBFlD2sABEADsiUZUOYBg1UdDaWkEdJYkTSZD68214m8Q1fbrP5AptaUfCl8KYKFMNoAJRBXn9FbE6q6VBzghHXj/rSnA8WPnkbaEWR7xltOqzB1yHpCQ1l8xSfH5N02DMUBSRtD/rOYsBKbaJcOgW0K21sX+BecMY/AI2yADvCJEjhVKrjR9yfRX+NQEhDcbXUFRGt9ZT+TI5yT4xcwbvvTu7aFUR/dH7+wjrQ7lzoGlZGFFrQXSs2WI0WaYHWDeCwymtohXryF8lcWQkhH8UhfNJVBJFgCY8Q6UHkZG0FxMu8xnIDBMjBmSZKwKQn0nwzwM2afskZEnmNPYDI8nuNsSZBZSAw+ThhkdCZHZZRwzmjzyRuLLVFpOj3XryXwZcSefNMPDkZAuWWzPYjxS80cm2hG1WfqrG0Gl8+iX69cbQchb7gbEb0RtqNskTo9DDmO0bNKNnMbzmIJ3/rTbSahKSwtewklqSP/01o0WKZiy+n/RAkUKOFBprjJtWOZkc8SPXV/rnoS2dWsJWQZhuPPtv3tefdDiEyp7ePrfgfKxuHpZES0IZRiFI4J/nAUP5bix+srcIxOVqAam68CbAlPvWTivRUMRVbKjJiGXIOJ78wAMjqPg3QIC0GQ0EPAWwAOzzpdgbnG7TCQetaVV8rSYCuirlPYN+bJIwBtkOC9SWLoPMVZTwQARAQABtC5GbGF0aHViIFJlcG8gU2lnbmluZyBLZXkgPGZsYXRodWJAZmxhdGh1Yi5vcmc+iQJUBBMBCAA+FiEEblwF2XnHba+TwIE1QYTdTZB6fK4FAllD2sACGwMFCRLMAwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQQYTdTZB6fK5RJQ/+Ptd4sWxaiAW91FFk7+wmYOkEe1NY2UDNJjEEz34PNP/1RoxveHDt43kYJQ23OWaPJuZAbu+fWtjRYcMBzOsMCaFcRSHFiDIC9aTp4ux/mo+IEeyarYt/oyKb5t5lta6xaAqg7rwt65jW5/aQjnS4h7eFZ+dAKta7Y/fljNrOznUp81/SMcx4QA5G2Pw0hs4Xrxg59oONOTFGBgA6FF8WQghrpR7SnEe0FSEOVsAjwQ13Cfkfa7b70omXSWp7GWfUzgBKyoWxKTqzMN3RQHjjhPJcsQnrqH5enUu4Pcb2LcMFpzimHnUgb9ft72DP5wxfzHGAWOUiUXHbAekfq5iFks8cha/RST6wkxG3Rf44Zn09aOxh1btMcGL+5xb1G0BuCQnA0fP/kDYIPwh9z22EqwRQOspIcvGeLVkFeIfubxpcMdOfQqQnZtHMCabV5Q/Rk9K1ZGc8M2hlg8gHbXMFch2xJ0Wu72eXbA/UY5MskEeBgawTQnQOK/vNm7t0AJMpWK26Qg6178UmRghmeZDj9uNRc3EI1nSbgvmGlpDmCxaAGqaGL1zW4KPW5yN25/qeqXcgCvUjZLI9PNq3Kvizp1lUrbx7heRiSoazCucvHQ1VHUzcPVLUKKTkoTP8okThnRRRsBcZ1+jI4yMWIDLOCT7IW3FePr+3xyuy5eEo9a25Ag0EWUPa7AEQALT/CmSyZ8LWlRYQZKYw417p7Z2hxqd6TjwkwM3IQ1irumkWcTZBZIbBgrSOg6CcXD2oWydCQHWi9qaxhuhEl2bJL5LskmBcMxVdQeD0LLHd8QUnbnnIby8ocvWN1alPfvJFjCUTrmD22U1ycOzRw2lIe4kiQONbOZtdWrVImQQSndjFlisitbmlWHvHm2lOOYy8+GJB7YffVV193hmnBSJffCy4bvkuLxsI+n1DhOzc7MPV3z6HGk4HiEcF0yyt9tCYhpsxHFdBoq2h771HfAcS0s98EVAqYMFnf9em+4cnYpdI6mhIfS1FQiKl6DBAYA8tT3ggla00DurPo0JwX/zN+PaO5h/6O9aCZwV7G6rbkgMuqMergXaf8oP38gr0z+MqWnkfM63Bodq68GP4l4hd02BoFBbDf38TMuGQB14+twJMdfbAxo2MbgluvQgfwHfZ2ca6gyEY+9s/YD1gugLjV+S6CB51WkFNe1z4tAPgJZNxUcKCbeaHNbthl8Hks/pY9RCEseX/EdfzF18epbSjJMPh4DPQXbUoFwmyuYcoBOPmvZHNl9hK7B/1RP8w1ZrXk8qdupC0SNbafX7270B7lMMVImzZetGsM9ypXJ6llhp3FwW09iseNyGJGPsr/dvTMGDXqOPfU/9SAS1LSTY4K9PbRtdrBE318YX8mIk5ABEBAAGJBHIEGAEIACYWIQRuXAXZecdtr5PAgTVBhN1NkHp8rgUCWUPa7AIbAgUJEswDAAJACRBBhN1NkHp8rsF0IAQZAQgAHRYhBFSmzd2JGfsgQgDYrFYnAunj7X7oBQJZQ9rsAAoJEFYnAunj7X7oR6AP/0KYmiAFeqx14Z43/6s2gt3VhxlSd8bmcVV7oJFbMhdHBIeWBp2BvsUf00I0Zl14ZkwCKfLwbbORC2eIxvzJ+QWjGfPhDmS4XUSmhlXxWnYEveSek5Tde+fmu6lqKM8CHg5BNx4GWIX/vdLi1wWJZyhrUwwICAxkuhKxuP2Z1An48930eslTD2GGcjByc27+9cIZjHKa07I/aLffo04V+oMT9/tgzoquzgpVV4jwekADo2MJjhkkPveSNI420bgT+Q7Fi1l0X1aFUniBvQMsaBa27PngWm6xE2ZYvh7nWCdd5g0c0eLIHxWwzV1lZ4Ryx4ITO/VL25ItECcjhTRdYa64sA62MYSaB0x3eR+SihpgP3wSNPFu3MJo6FKTFdi4CBAEmpWHFW7FcRmd+cQXeFrHLN3iNVWryy0HK/CUEJmiZEmpNiXecl4vPIIuyF0zgSCztQtKoMr+injpmQGC/rF/ELBVZTUSLNB350S0Ztvw0FKWDAJSxFmoxt3xycqvvt47rxTrhi78nkk6jATKGyvP55sO+K7Q7Wh0DXA69hvPrYW2eu8jGCdVGxi6HX7L1qcfEd0378S71dZ3g9o6KKl1OsDWWQ6MJ6FGBZedl/ibRfs8p5+sbCX3lQSjEFy3rx6n0rUrXx8U2qb+RCLzJlmC5MNBOTDJwHPcX6gKsUcXZrEQALmRHoo3SrewO41RCr+5nUlqiqV3AohBMhnQbGzyHf2+drutIaoh7Rj80XRh2bkkuPLwlNPf+bTXwNVGse4bej7B3oV6Ae1N7lTNVF4Qh+1OowtGjmfJPWo0z1s6HFJVxoIof9z58Msvgao0zrKGqaMWaNQ6LUeC9g9Aj/9Uqjbo8X54aLiYs8Z1WNc06jKP+gv8AWLtv6CR+l2kLez1YMDucjm7v6iuCMVAmZdmxhg5I/X2+OM3vBsqPDdQpr2TPDLX3rCrSBiS0gOQ6DwN5N5QeTkxmY/7QO8bgLo/Wzu1iilH4vMKW6LBKCaRx5UEJxKpL4wkgITsYKneIt3NTHo5EOuaYk+y2+Dvt6EQFiuMsdbfUjs3seIHsghX/cbPJa4YUqZAL8C4OtVHaijwGo0ymt9MWvS9yNKMyT0JhN2/BdeOVWrHk7wXXJn/ZjpXilicXKPx4udCF76meE+6N2u/T+RYZ7fP1QMEtNZNmYDOfA6sViuPDfQSHLNbauJBo/n1sRYAsL5mcG22UDchJrlKvmK3EOADCQg+myrm8006LltubNB4wWNzHDJ0Ls2JGzQZCd/xGyVmUiidCBUrD537WdknOYE4FD7P0cHaM9brKJ/M8LkEH0zUlo73bY4XagbnCqve6PvQb5G2Z55qhWphd6f4B6DGed86zJEa/RhS +REPO +if ! flatpak remote-list --user --columns=name 2>/dev/null | grep -qx flathub; then + out=$(flatpak remote-add --user --if-not-exists flathub "$WORK/flathub.flatpakrepo" 2>&1) + rc=$? + echo "$out" + # What Flatpak said goes up with the failure, so the app can show it rather than a guess. + [ $rc -eq 0 ] || fail "could not add the Flathub remote: $(echo "$out" | grep -v '^[[:space:]]*$' | tail -1)" +fi +echo "== DONE $(flatpak --version)" diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-game-env b/tools/linuxfs/overlay/usr/local/bin/bannerlator-game-env new file mode 100755 index 000000000..ff9e87449 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-game-env @@ -0,0 +1,59 @@ +#!/usr/bin/python3 +import json +import os +import re +import sys +from pathlib import Path + + +def game_id(env): + prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/") + if not prefix: + return None + value = prefix.rsplit("/", 1)[-1] + if not re.fullmatch(r"-?[0-9]+", value): + return None + number = int(value) + if not -(2**31) <= number < 2**32 or number == 0: + return None + return str(number % 2**32) + + +def apply_config(env, config, app_id): + if config.get("version") != 1: + raise ValueError("unsupported environment configuration") + result = env.copy() + entries = dict(config.get("shared", {})) + entries.update(config.get("games", {}).get(app_id, {})) + for name, value in entries.items(): + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name): + raise ValueError("invalid environment name") + if value is None: + result.pop(name, None) + elif isinstance(value, str) and "\0" not in value and len(value) <= 8192: + result[name] = value + else: + raise ValueError("invalid environment value") + return result + + +def main(): + command = sys.argv[1:] + if not command: + return 2 + env = os.environ.copy() + app_id = game_id(env) + if len(command) > 1 and command[1] == "waitforexitandrun" and app_id: + path = Path.home() / ".config/droiddeck/game-environment.json" + try: + with path.open(encoding="utf-8") as source: + env = apply_config(env, json.load(source), app_id) + except FileNotFoundError: + pass + except (OSError, ValueError, TypeError, AttributeError): + print("bannerlator-game-env: invalid configuration; using inherited environment", file=sys.stderr) + os.execvpe(command[0], command, env) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-seed-redists b/tools/linuxfs/overlay/usr/local/bin/bannerlator-seed-redists index 9d2d60fa7..ea1d413f5 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-seed-redists +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-seed-redists @@ -1,5 +1,6 @@ #!/bin/bash -# Marks Steam's shared redistributables as already run in every Proton prefix. +# Marks Steam's shared redistributables as already run in every Proton prefix, and in the +# template Proton makes new prefixes from. # # A game whose depot lists _CommonRedist makes the client run the real installer inside the # prefix on first launch. Those are x86 bundles, so they run under FEX, and the 2019 one leaves @@ -14,27 +15,15 @@ set -u steam_root=${1:?steam root} redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist" -[ -d "$redist" ] || exit 0 -# Every process an install script would run becomes the registry value the client writes once it -# has run it. Names sit one level inside "Run Process", the key they share a level further in. -block=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | xargs -0 -r awk -v now="$(date +%s)" ' - function emit(key, name, path) { - path = key - sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path) - if (path == key) - return - printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, name - # The client writes these from 32-bit steam.exe, so its own copy lands under Wow6432Node; - # both spellings are seeded because the reader picks by its own word size. - sub(/^Software\\\\/, "Software\\\\\\\\Wow6432Node\\\\\\\\", path) - printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, name - } +# Every process an install script would run, as the registry key and value the client writes once +# it has run it. Names sit one level inside "Run Process", the key they share a level further in. +pairs=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | xargs -0 -r awk ' FNR == 1 { depth = 0; name = ""; key = "" } /^[[:space:]]*\{/ { depth++; next } /^[[:space:]]*\}/ { if (depth == 3 && name != "" && key != "") - emit(key, name) + printf "%s\t%s\n", key, name depth-- next } @@ -44,15 +33,62 @@ block=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | x if (n >= 3 && depth == 2) { name = part[2]; key = "" } } ') -[ -n "$block" ] || exit 0 -stamp=$(printf '%s' "$block" | cksum) +# The client downloads the scripts with the first game that wants them, which is too late for that +# game; until then the set they held when this was written stands in. (WinNative's list.) +[ -n "$pairs" ] || pairs=$(sed 's/^\([^ ]*\) /HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\\1\t/' <<'KNOWN' +DirectX\\Jun2010 dxsetup +.NET\\4.8 4.8 +vcredist\\2008 x86 SP1 +vcredist\\2008 x64 SP1 +vcredist\\2010 x86 +vcredist\\2010 x64 +vcredist\\2013 x86 12.0.30501 +vcredist\\2013 x64 12.0.30501 +vcredist\\2015 x86 Update 3 14.0.24215.0 +vcredist\\2015 x64 Update 3 14.0.24215.0 +vcredist\\2017 x86 14.10.25008.0 +vcredist\\2017 x64 14.10.25008.0 +vcredist\\2019 x86 14.28.29334.0 +vcredist\\2019 x64 14.28.29334.0 +vcredist\\2022 x86 14.51.36247.0 +vcredist\\2022 x64 14.51.36247.0 +KNOWN +) +# The stamp is the set of names, taken before the block below dates its keys: stamped from the +# dated block it never matched, and every prefix had the whole block appended again on every beat. +stamp=$(printf '%s' "$pairs" | cksum) -for reg in "$steam_root"/steamapps/compatdata/*/pfx/system.reg \ - /mnt/bannerlator-sd/steamapps/compatdata/*/pfx/system.reg; do +block=$(printf '%s\n' "$pairs" | awk -F'\t' -v now="$(date +%s)" ' + { + path = $1 + sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path) + if (path == $1) + next + printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2 + # The client writes these from 32-bit steam.exe, so its own copy lands under Wow6432Node; + # both spellings are seeded because the reader picks by its own word size. + sub(/^Software\\\\/, "Software\\\\\\\\Wow6432Node\\\\\\\\", path) + printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2 + } +') +[ -n "$block" ] || exit 0 + +# Proton builds a new prefix from its template, and the client runs the install scripts in that +# prefix moments later, so the template carries the markers too. Its date is kept: Proton reads a +# changed one as a new template and upgrades every prefix made from the old. +for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \ + "$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \ + "$steam_root"/steamapps/compatdata/*/pfx/system.reg \ + /mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg; do [ -f "$reg" ] || continue seeded=$(dirname "$reg")/.bannerlator-redists [ "$(cat "$seeded" 2>/dev/null)" = "$stamp" ] && continue - printf '%s\n' "$block" >>"$reg" || continue - printf '%s\n' "$stamp" >"$seeded" - echo "== seeded redist markers into $reg" + dated=$(mktemp) || continue + touch -r "$reg" "$dated" + if printf '%s\n' "$block" >>"$reg"; then + printf '%s\n' "$stamp" >"$seeded" + echo "== seeded redist markers into $reg" + fi + touch -r "$dated" "$reg" + rm -f "$dated" done diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session index c0adc95e7..01fb68198 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session @@ -73,14 +73,29 @@ if [ -n "${BL_VK_DRIVER:-}" ]; then fi unset bl_icd_lib fi -# The app's gamescope build (tools/gamescope) takes realtime-priority Vulkan queues on this +# The app's gamescope build (tools/gamescope) asks for realtime-priority Vulkan queues on this # switch instead of on CAP_SYS_NICE, which proot never has; it falls back to normal priority -# where the driver refuses, and the runtime's own build ignores it. -export GAMESCOPE_FORCE_VULKAN_REALTIME=${BL_GAMESCOPE_REALTIME:-1} +# where the driver refuses, and the runtime's own build ignores it. On KGSL Turnip (Mesa 26.2) it +# changes nothing yet: the driver reports one submit-queue priority and creates every KGSL context +# with the same flags, so no priority reaches the GPU. Kept for a driver that maps it, and off +# unless the app's Performance page turns it on (BL_GAMESCOPE_REALTIME=1). +export GAMESCOPE_FORCE_VULKAN_REALTIME=${BL_GAMESCOPE_REALTIME:-0} + +# A sleep that starts no process. Under proot every exec is a traced execve plus the loader's +# opens and maps, and the watchers below poll for the whole session: `sleep 1` in a loop was 60 +# execs a minute each. read -t on a pipe nothing ever writes to waits in bash itself. +nap() { + [ -n "${bl_nap_fd:-}" ] || exec {bl_nap_fd}<> <(:) + read -r -t "$1" -u "$bl_nap_fd" _ 2>/dev/null || : +} export XDG_DATA_HOME=${XDG_DATA_HOME:-$HOME/.local/share} export XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config} export XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache} mkdir -p "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME" +# Flatpak (the store's apps): its sandboxes through the app instead of bubblewrap, which needs the +# user namespaces Android keeps from apps, and its apps' menu entries and icons on the desktop. +export FLATPAK_BWRAP=/usr/local/bin/bannerlator-bwrap +export XDG_DATA_DIRS=$XDG_DATA_HOME/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share} # The cores a program runs on outside Steam (the desktop and everything started from it, a # program from the rail): the user's game cores when set (BL_GAME_CPUS), else every core but the @@ -219,7 +234,7 @@ case $mode in bannerlator-steam-install || exit $? step "Steam client ready" steam_root=$XDG_DATA_HOME/Steam - # Register the card library (bound at /mnt/bannerlator-sd) with the client - internal storage is + # Register the card library (bound at /mnt/droiddeck-sd) with the client - internal storage is # its main library already - and the ARM64 Proton that lets it launch the Windows ones. # A request left in ~/.bl-proton-extra installs a third-party Proton before the client starts, # so it is in the Compatibility dropdown the first time the user looks. One per line, each the @@ -258,15 +273,26 @@ case $mode in # device it took 5 of 8, leaving out both little cores and the fastest one - which is a # reasonable thing to do while a game is running and the wrong thing when the client is all # there is. BL_CLIENT_CPUS overrides it. Re-applied on a beat because steamwebhelper spawns - # children continuously and each one inherits Steam's choice, not ours. + # children continuously and each one inherits Steam's choice, not ours. The beat reads /proc + # itself instead of running pgrep, and only runs taskset for a process that is new or has + # grown threads since it was last pinned: every fork is a round of traced syscalls, and a + # beat that forked a taskset per process every 5 s did that for an hour. taskset -a, because + # without it only a process's main thread moves and the renderer's workers stay where they were. if [ -n "${BL_CLIENT_CPUS:-}" ]; then step "client cores: $BL_CLIENT_CPUS" ( - for _ in $(seq 1 720); do - for _p in $(pgrep -f 'steamwebhelper|steamrtarm64/steam|gamescope' 2>/dev/null); do - taskset -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true + declare -A _bl_pinned=() + for ((_i = 0; _i < 720; _i++)); do + for _d in /proc/[0-9]*; do + IFS= read -r -d '' _c < "$_d/cmdline" 2>/dev/null || continue + case $_c in *steamwebhelper*|*steamrtarm64/steam|*gamescope*) ;; *) continue ;; esac + _t=("$_d"/task/*) + _p=${_d#/proc/} + [ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && continue + taskset -a -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true + _bl_pinned[$_p]=${#_t[@]} done - sleep 5 + nap 5 done ) & fi @@ -374,8 +400,9 @@ case $mode in [ -z "${BL_DESKTOP:-}" ] && ( last=${BL_GAMESCOPE_FORCE_FULLSCREEN:-1} while :; do - sleep 1 - want=$(cat "$HOME/.droiddeck-fill" 2>/dev/null) || continue + nap 1 + want= + { read -r want || [ -n "$want" ]; } < "$HOME/.droiddeck-fill" 2>/dev/null || continue case $want in 0|1) ;; *) continue ;; esac [ "$want" = "$last" ] && continue if xprop -root -f GAMESCOPE_FORCE_WINDOWS_FULLSCREEN 32c -set GAMESCOPE_FORCE_WINDOWS_FULLSCREEN "$want" 2>/dev/null; then @@ -384,13 +411,53 @@ case $mode in fi done ) & + # Resume from the Steam menu. The menu is an overlay that takes input, and a fullscreen game that + # loses input minimizes itself; gamescope only takes a window out of that state when the focused + # window changes, which the menu never does, so the game stayed minimized after Resume (a black + # screen with its small caption in the top-left corner). gamescope-3.16.29-p4 restores it itself; + # this asks it again a moment after input comes back from the client (app 769) to anything else, + # which covers a game that minimizes late. Harmless when nothing is minimized. + # BL_RESTORE_ON_RESUME=0 turns it off. + [ -z "${BL_DESKTOP:-}" ] && [ "${BL_RESTORE_ON_RESUME:-1}" = 1 ] && ( + prev= + xprop -spy -root GAMESCOPE_FOCUSED_APP 2>/dev/null | while read -r line; do + app=${line##*= } + case $app in ''|*[!0-9]*) prev=; continue ;; esac + if [ "$prev" = 769 ] && [ "$app" != 769 ]; then + nap 1 + xprop -root -f GAMESCOPE_RESTORE_FOCUS_WINDOW 32c -set GAMESCOPE_RESTORE_FOCUS_WINDOW 1 2>/dev/null \ + && echo "== resume: asked gamescope to restore the game window (app $app)" + fi + prev=$app + 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 + # marked and every 15 s is soon enough for the rest. The compat pass runs when a directory it + # reads from has changed since its last run - a new manifest, a new depot or tool, the client + # rewriting config.vdf - which [ -nt ] answers without starting anything, and once a minute + # regardless. ( beat=0 - for _ in $(seq 1 720); do - sleep 5 - bannerlator-seed-redists "$steam_root" >/dev/null 2>&1 || true + compat_stamp=$HOME/.bl-compat-beat + rm -f "$compat_stamp" + compat_due() { + local d + [ -e "$compat_stamp" ] && [ "$((beat % 12))" -ne 0 ] || return 0 + for d in "$steam_root/steamapps" "$steam_root/steamapps/common" "$steam_root/config" \ + "$steam_root/compatibilitytools.d" /mnt/droiddeck-sd/steamapps; do + [ "$d" -nt "$compat_stamp" ] && return 0 + done + return 1 + } + for ((_i = 0; _i < 720; _i++)); do + nap 5 beat=$((beat + 1)) - if [ "$((beat % 3))" -eq 0 ]; then + [ "$((beat % 3))" -eq 0 ] || continue + bannerlator-seed-redists "$steam_root" >/dev/null 2>&1 || true + if compat_due; then + : > "$compat_stamp" bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true fi done @@ -501,20 +568,19 @@ BUSCONF # desktop's launchers ask for; gamescope shows one window at a time and the game takes over. _bl_ui=(-gamepadui) [ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=() - # Deck mode (BL_STEAMDECK=1, the Performance page): -steamdeck is the flag that puts the Quick - # Access Menu, the performance overlay and the Deck settings pages on screen. Only -steamdeck, - # never -steamos3: that one makes the client manage itself as SteamOS does - it calls - # steamos-select-branch and opts the install into the steamdeck_stable client branch, writes - # that to package/beta, and from then on the branch on disk loses to the -clientbeta below on - # every launch; the updater finds "installed version 0", marks an update pending and exits 42 - # to apply it, which never happens, so the client restarts for ever - under a running game, - # taking Steam Input with it each time. (Bannerlator 38996ea1, on device.) The SteamOS helpers - # the client calls in this mode are staged as no-op stubs under /usr/bin. + # Deck mode (BL_STEAMDECK=1, the Steam page's Client settings): -steamdeck is the flag that puts + # the Quick Access Menu and the Deck settings pages on screen; the QAM's performance overlay + # controls stay greyed out without -steamos3, as SteamOS and Armada launch it. -steamos3 makes + # the client manage itself as SteamOS does - it calls steamos-select-branch and writes + # steamdeck_stable to package/beta, and a branch on disk that loses to the -clientbeta below + # is an update that never installs: exit 42, a restart, for ever (Bannerlator 38996ea1). The + # loop below puts package/beta back before every start. The SteamOS helpers the client calls + # in this mode are staged as no-op stubs under /usr/bin. if [ "${BL_STEAMDECK:-0}" = 1 ] && [ "${BL_STEAM_UI:-}" != desktop ]; then - _bl_ui+=(-steamdeck) + _bl_ui+=(-steamdeck -steamos3) # The QAM's Scaling Filter lists NVIDIA Image Scaling only when told gamescope has it (it does). export STEAM_GAMESCOPE_NIS_SUPPORTED=1 - echo "== steam: Deck mode on (-steamdeck)" + echo "== steam: Deck mode on (-steamdeck -steamos3)" fi # What a killed session leaves behind. Android ends sessions without warning (backgrounding, the # low-memory killer), and the client then finds .crash - opening its update UI on the spinner - @@ -539,10 +605,49 @@ BUSCONF # again on the branch it just wrote. steam_channel=${BL_STEAM_CHANNEL:-publicbeta} steam_beta=$steam_root/package/beta + if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then + bannerlator-steam-games watch "$steam_root" "$BL_ADDED_GAMES" & + games_watcher=$! + fi + # Lossless Scaling (Steam app 993090): whether this account owns it, asked of the signed-in + # client once a session until the answer is yes. From then on the app offers importing + # Lossless.dll and passes BL_LOSSLESS_OWNED=1, so the question is never asked again. + if [ "${BL_LOSSLESS_OWNED:-0}" != 1 ]; then + ( + owned=$HOME/.config/droiddeck/lossless-owned + for ((_i = 0; _i < 60; _i++)); do + nap 30 + [ -e "$owned" ] && exit 0 + answer=$(bannerlator-steam-games probe "$steam_root" 993090 2>/dev/null) || continue + case $answer in + *'"993090": true'*) mkdir -p "${owned%/*}" && : > "$owned" && echo "== Lossless Scaling: owned" ;; + *) echo "== Lossless Scaling: not owned by this account" ;; + esac + exit 0 + done + ) & + fi echo "== steam args: ${_bl_ui[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*" # An update that cannot install asks for a restart (rc=42) every time; the count is capped so a # session can never again loop in silence, which reads as a menu opening and closing by itself. steam_updates=0 + rm -f "$HOME/.bl-stop-requested" + if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -d "$BL_LAUNCH_DIR" ]; then + rm -f "$BL_LAUNCH_DIR/steam-stop" + ( + while :; do + if [ -e "$BL_LAUNCH_DIR/steam-stop" ]; then + rm -f "$BL_LAUNCH_DIR/steam-stop" + : > "$HOME/.bl-stop-requested" + echo "== steam: the app asked for a clean exit" + "$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true + exit 0 + fi + nap 0.5 + done + ) & + stop_watcher=$! + fi while :; do rm -f "$HOME/.bl-restart-once" if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then @@ -556,6 +661,13 @@ BUSCONF rc=$? echo "== steam exited rc=$rc" collect_steam_logs + if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then + bannerlator-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true + fi + if [ -f "$HOME/.bl-stop-requested" ]; then + rm -f "$HOME/.bl-stop-requested" "$HOME/.bl-restart-once" + break + fi # The session asked for this exit (the ARM64 Proton landed): start again, without the URL # arguments, which were acted on. Not counted against the update cap. if [ -f "$HOME/.bl-restart-once" ]; then @@ -572,6 +684,14 @@ BUSCONF # The URL arguments were acted on the first time; a restart must not repeat them. set -- done + if [ -n "${stop_watcher:-}" ]; then + kill "$stop_watcher" 2>/dev/null || true + wait "$stop_watcher" 2>/dev/null || true + fi + if [ -n "${games_watcher:-}" ]; then + kill "$games_watcher" 2>/dev/null || true + wait "$games_watcher" 2>/dev/null || true + fi if [ -n "${BL_DESKTOP:-}" ]; then # Started from the desktop (bannerlator-steam-launch): the desktop's own programs share this # script's parent, so reap_orphans - right under gamescope, where everything is the client's - diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat index 4abca5b52..fb70b40e2 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat @@ -146,6 +146,29 @@ bl_game_cpus() { # game never gets OpenGL; left at its own size in a window, it draws small in a corner. So these # titles are told to stay windowed at the session's own size - unless the user's launch options # already say something about the video mode, which are left as they are. +# The session puts the client's own libraries (steamrtarm64, its panorama/) ahead of everything for +# the client, and a game inherits that: Wine then resolved gnutls, SDL, FFmpeg and the rest against +# the client's private copies instead of the rootfs it was built for. Inside Steam's runtime +# container that path never reaches Proton either. (WinNative's winnative-proton-launch.) +BL_LIBPATH_SETUP = """ +bl_libpath() { + # A Proton built to prefer PipeWire (CachyOS's among the adopted ones) hung its audio thread + # here, where only PulseAudio answers. (WinNative, winnative-proton-launch.) + export PROTON_USE_PIPEWIRE=${PROTON_USE_PIPEWIRE:-0} + [ -n "${LD_LIBRARY_PATH:-}" ] || return 0 + local kept= dir old_ifs=$IFS + IFS=: + for dir in $LD_LIBRARY_PATH; do + case $dir in + "" | */steamrtarm64 | */steamrtarm64/*) ;; + *) kept=${kept:+$kept:}$dir ;; + esac + done + IFS=$old_ifs + if [ -n "$kept" ]; then export LD_LIBRARY_PATH="$kept"; else unset LD_LIBRARY_PATH; fi +} +""" + BL_IDTECH3_SETUP = """ bl_idtech3() { BL_EXTRA_ARGS=() @@ -226,16 +249,29 @@ if [ -f "$fake" ]; then *) LD_PRELOAD="$fake${LD_PRELOAD:+:$LD_PRELOAD}"; export LD_PRELOAD ;; esac fi +# The newest of the ARM64 depots the client has, by the build number that opens each one's version +# file: taking the first one found ran a stale Experimental over a newer 11.0. (WinNative.) +depot= +best=0 for name in %s; do - depot="$steam_root/steamapps/common/$name" - if [ -d "$depot/files/bin-arm64" ] && [ -x "$depot/proton" ]; then - bl_components "$depot" - bl_directaudio "$depot" - bl_game_cpus - bl_idtech3 "$@" - exec ${BL_TASKSET:-} "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" + 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" + case $build in "" | *[!0-9]*) build=0 ;; esac + if [ -z "$depot" ] || [ "$build" -gt "$best" ]; then + depot=$candidate + best=$build fi done +if [ -n "$depot" ]; then + bl_components "$depot" + bl_directaudio "$depot" + bl_game_cpus + bl_idtech3 "$@" + bl_libpath + exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" +fi echo "bannerlator-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2 exit 1 """ % " ".join('"%s"' % n for n in SOURCES) @@ -244,7 +280,7 @@ exit 1 # something else. LAUNCHER_SH = LAUNCHER_SH.replace( "verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP - + BL_COMPONENTS_SETUP, 1) + + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1) # A third-party Proton dropped into compatibilitytools.d - GE-Proton, proton-cachyos, anything of # that shape - is adopted rather than used as shipped, for the same two reasons Valve's ARM64 depot @@ -280,9 +316,10 @@ bl_components "$here" bl_directaudio "$here" bl_game_cpus bl_idtech3 "$@" +bl_libpath # Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be # started from its own tree. -exec ${BL_TASKSET:-} "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" +exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" """ EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools" { @@ -369,6 +406,28 @@ def serialize(tokens): return "\n".join(out) + "\n" +def write_changed(path, text, mode=None): + """Writes `text` to `path` only when it differs, through a rename so a reader never sees half a + file. The session runs this script every 15 s for as long as the client does; rewriting files + that have not changed cost a python start's worth of writes each time, and config.vdf is the + client's own, which it may be writing at that moment. Returns whether anything was written.""" + try: + with open(path, encoding="utf-8", errors="replace") as f: + same = f.read() == text + except OSError: + same = False + if not same: + tmp = path + ".bannerlator" + with open(tmp, "w", encoding="utf-8") as f: + f.write(text) + if mode is not None: + os.chmod(tmp, mode) + os.replace(tmp, path) + elif mode is not None and (os.stat(path).st_mode & 0o7777) != mode: + os.chmod(path, mode) + return not same + + def first_key(path, section): """The single key naming a block inside `section`, or None. Used to keep a third-party tool's own internal name, so a mapping the user already made against it keeps working.""" @@ -442,14 +501,10 @@ def adopt_extras(tools): body = (EXTRA_WRAPPER_SH % entry_point).replace( 'here=$(dirname "$0")', 'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP - + BL_COMPONENTS_SETUP, 1) - with open(wrapper, "w", encoding="utf-8") as f: - f.write(body) - os.chmod(wrapper, 0o755) - with open(manifest, "w", encoding="utf-8") as f: - f.write(EXTRA_MANIFEST_VDF) - with open(compat_vdf, "w", encoding="utf-8") as f: - f.write(EXTRA_COMPAT_TOOL_VDF % (name, entry)) + + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP, 1) + write_changed(wrapper, body, 0o755) + write_changed(manifest, EXTRA_MANIFEST_VDF) + write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, entry)) except OSError as e: print("bannerlator-steam-compat: could not adopt %s (%s)" % (entry, e)) continue @@ -494,7 +549,8 @@ def register_default(config_path, apps=(), name=None, protect=()): # Tool names the user may deliberately have chosen (see adopt_extras); never repointed. keep = {n.lower() for n in protect} with open(config_path, encoding="utf-8", errors="replace") as f: - tokens = tokenize(f.read()) + original = f.read() + tokens = tokenize(original) steam = find_block(tokens, ["InstallConfigStore", "Software", "Valve", "Steam"]) if steam is None: return @@ -521,39 +577,43 @@ def register_default(config_path, apps=(), name=None, protect=()): continue tokens[mapping + 1:mapping + 1] = [ '"%s"' % app, "{", '"name"', '"%s"' % tool, '"config"', '""', '"priority"', '"250"', "}"] - tmp = config_path + ".bannerlator" - with open(tmp, "w", encoding="utf-8") as f: - f.write(serialize(tokens)) - os.replace(tmp, config_path) + # Nothing to change is the usual case on the session's beat: the client's own file is left alone. + text = serialize(tokens) + if text != serialize(tokenize(original)): + write_changed(config_path, text) + + +def depot_build(depot): + """The build number a depot's version file starts with; 0 when there is none.""" + try: + with open(os.path.join(depot, "version"), encoding="utf-8", errors="replace") as f: + first = f.read().split(None, 1) + except OSError: + return 0 + return int(first[0]) if first and first[0].isdigit() else 0 def find_source(steam_root): - """The ARM64 Proton depot the client has downloaded, or None.""" + """The newest ARM64 Proton depot the client has downloaded (the one the launcher runs), or None.""" common = os.path.join(steam_root, "steamapps", "common") - for name in SOURCES: - depot = os.path.join(common, name) - # bin-arm64 is what makes it the native build rather than the x86_64 one. - if os.path.isdir(os.path.join(depot, "files", "bin-arm64")): - return depot - return None + # bin-arm64 is what makes it the native build rather than the x86_64 one. + 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 def build_tool(tool_dir): """Our own manifests and the launcher. The depot is found at launch time, not here.""" if os.path.islink(tool_dir): os.unlink(tool_dir) - elif os.path.isdir(tool_dir): - # Earlier versions mirrored the depot in here as symlinks; start clean. + elif os.path.isdir(tool_dir) and set(os.listdir(tool_dir)) - set(OWN_FILES): + # Earlier versions mirrored the depot in here as symlinks; start clean. A directory holding + # only our own files is kept, and each file rewritten only when it changed. shutil.rmtree(tool_dir) - os.makedirs(tool_dir) - with open(os.path.join(tool_dir, "toolmanifest.vdf"), "w", encoding="utf-8") as f: - f.write(TOOL_MANIFEST_VDF) - with open(os.path.join(tool_dir, "compatibilitytool.vdf"), "w", encoding="utf-8") as f: - f.write(COMPAT_TOOL_VDF % TOOL) - launcher = os.path.join(tool_dir, LAUNCHER) - with open(launcher, "w", encoding="utf-8") as f: - f.write(LAUNCHER_SH) - os.chmod(launcher, 0o755) + os.makedirs(tool_dir, exist_ok=True) + write_changed(os.path.join(tool_dir, "toolmanifest.vdf"), TOOL_MANIFEST_VDF) + write_changed(os.path.join(tool_dir, "compatibilitytool.vdf"), COMPAT_TOOL_VDF % TOOL) + write_changed(os.path.join(tool_dir, LAUNCHER), LAUNCHER_SH, 0o755) def main(): diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games new file mode 100755 index 000000000..46dcdb83e --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games @@ -0,0 +1,378 @@ +#!/usr/bin/env python3 +"""Resolve added games against the signed-in Steam client's licenses.""" +import ctypes as C +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time +import unicodedata +import urllib.parse +import urllib.request + +STATE = ".droiddeck-games.json" +WINNATIVE = ".winnative-steam/steamapps" +LIBRARY = "/mnt/droiddeck-sd" +LEGACY_LIBRARY = "/mnt/bannerlator-sd" +BASE_ID = 76561197960265728 + + +def read_json(path, default): + try: + return json.loads(Path(path).read_text()) + except (OSError, ValueError): + return default + + +def save_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix(".tmp") + temp.write_text(json.dumps(value)) + os.replace(temp, path) + + +def title_key(name): + return "".join(c for c in unicodedata.normalize("NFKC", name.replace("™", "").replace("®", "")).casefold() if c.isalnum()) + + +def edition_key(name): + name = re.sub(r"(?i)\s+(?:windows edition|intergrade)\s*$", "", name) + return title_key(name) + + +def legacy_path(path): + path = str(path) + return LEGACY_LIBRARY + path[len(LIBRARY):] if path == LIBRARY or path.startswith(LIBRARY + "/") else path + + +def source_stamp(game): + try: + exe = Path(game["exe"]) + stat = exe.stat() + hints = [] + for parent in sorted({Path(game["folder"]), exe.parent}): + hint = parent / "steam_appid.txt" + hints.append(hint.read_text().strip() if hint.is_file() else "") + return [game["name"], str(exe), stat.st_size, stat.st_mtime_ns, hints] + except (OSError, ValueError): + return None + + +def manifest_ids(steamapps, name): + matches = [] + for manifest in Path(steamapps).glob("appmanifest_*.acf"): + try: + install = re.search(r'"installdir"\s*"([^"\\]*)"', manifest.read_text(), re.I) + if install and install[1] == name: + matches.append(int(manifest.stem.removeprefix("appmanifest_"))) + except (OSError, ValueError): + pass + return matches + + +def identify(game): + folder = Path(game["folder"]) + steamapps = folder.parent.parent + for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]: + matches = manifest_ids(library, folder.name) + if matches: + return matches[0] if len(matches) == 1 else None + ids = set() + for parent in {folder, Path(game["exe"]).parent}: + try: + appid = int((parent / "steam_appid.txt").read_text().strip()) + if 0 < appid < 0x80000000: + ids.add(appid) + except (OSError, ValueError): + pass + if ids: + return next(iter(ids)) if len(ids) == 1 else None + url = "https://store.steampowered.com/api/storesearch/?l=english&cc=US&term=" + urllib.parse.quote(game["name"]) + try: + with urllib.request.urlopen(url, timeout=5) as response: + items = json.loads(response.read(1024 * 1024)).get("items", []) + for key in (title_key, edition_key): + ids = {int(item["id"]) for item in items + if key(item.get("name", "")) == key(game["name"]) and key(game["name"])} + if ids: + return next(iter(ids)) if len(ids) == 1 else None + return None + except (OSError, ValueError, KeyError): + return None + + +def method(obj, slot, result, *args): + if not obj: + raise RuntimeError("Steam interface unavailable") + table = C.cast(obj, C.POINTER(C.POINTER(C.c_void_p))).contents + return C.CFUNCTYPE(result, C.c_void_p, *args)(table[slot]) + + +def probe(steam_root, ids): + # Slots belong to Valve's SteamClient020, SteamUser021 and STEAMAPPS_INTERFACE_VERSION008. + library = C.CDLL(str(Path(steam_root) / "steamrtarm64/steamclient.so")) + library.CreateInterface.argtypes = [C.c_char_p, C.c_void_p] + library.CreateInterface.restype = C.c_void_p + client = library.CreateInterface(b"SteamClient020", None) + pipe = method(client, 0, C.c_int)(client) + if not pipe: + raise RuntimeError("Steam pipe unavailable") + user = 0 + try: + user = method(client, 2, C.c_int, C.c_int)(client, pipe) + if not user: + raise RuntimeError("No signed-in Steam user") + get_interface = lambda slot, version: method(client, slot, C.c_void_p, C.c_int, C.c_int, C.c_char_p)(client, user, pipe, version) + account = get_interface(5, b"SteamUser021") + if not method(account, 1, C.c_bool)(account): + raise RuntimeError("Steam is offline") + steamid = method(account, 2, C.c_uint64)(account) + apps = get_interface(15, b"STEAMAPPS_INTERFACE_VERSION008") + subscribed = method(apps, 6, C.c_bool, C.c_uint32) + return {"account": str(steamid - BASE_ID), "checked": time.time(), + "owned": {str(appid): bool(subscribed(apps, appid)) for appid in ids}} + finally: + if user: + method(client, 4, None, C.c_int, C.c_int)(client, pipe, user) + method(client, 1, C.c_bool, C.c_int)(client, pipe) + + +def game_running(): + """Whether a Proton game is up: a wineserver is there for as long as any prefix is in use.""" + try: + pids = [p for p in os.listdir("/proc") if p.isdigit()] + except OSError: + return False + for pid in pids: + try: + with open("/proc/%s/comm" % pid) as f: + if f.read().strip() == "wineserver": + return True + except OSError: + pass + return False + + +def downloads_idle(steam_root): + try: + return not any(Path(steam_root, "steamapps/downloading").iterdir()) + except OSError: + return True + + +def request_restart(steam_root): + """The client reads manifests and shortcuts only at start, so an import needs one restart; + the session's loop runs the importer between the exit and the next start.""" + Path(os.environ.get("HOME", "/root"), ".bl-restart-once").touch() + subprocess.run([str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30) + + +def unimported(steam_root, snapshot, candidates): + routes = read_json(Path(steam_root) / "userdata" / snapshot["account"] / "config/.droiddeck-routes.json", {}) + routed = set(routes.values()) if isinstance(routes, dict) else set() + return sorted({appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True} - routed) + + +def watch(steam_root, listing): + games = read_json(listing, []) + if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games: + return + candidates, sources = {}, {} + next_lookup = 0 + last_status = None + # The probe is a fresh python that loads steamclient.so, seconds of CPU under proot. Ownership + # only moves with a purchase or a new match, so it runs when the matches or their sources + # change, after a failed probe, and otherwise every five minutes - not on every 30 s beat. + # A failed probe is retried on a doubling delay up to those five minutes rather than on every + # beat (a client that is not logged on fails it for as long as it stays that way), and none + # starts while a game is running: the answer can wait, the game's cores cannot. + probed, next_probe, failures = None, 0, 0 + pending, requested = [], [] + while True: + now = time.monotonic() + for game in games: + folder = game["folder"] + stamp = source_stamp(game) + if now >= next_lookup or stamp != sources.get(folder): + sources[folder] = stamp + appid = identify(game) + if appid: + candidates[folder] = appid + else: + candidates.pop(folder, None) + if now >= next_lookup: + next_lookup = now + 300 + status = "waiting for a matching Steam title" + key = (dict(candidates), dict(sources)) + if candidates and (key != probed or now >= next_probe) and game_running(): + status = last_status + elif candidates and (key != probed or now >= next_probe): + probed, next_probe = key, now + 300 + try: + result = subprocess.run([sys.executable, __file__, "probe", steam_root, + *map(str, sorted(set(candidates.values())))], + capture_output=True, text=True, timeout=15) + if result.returncode != 0: + status = "ownership probe failed: " + (result.stderr.strip()[-300:] or str(result.returncode)) + failures += 1 + next_probe = now + min(300, 30 * 2 ** failures) + else: + failures = 0 + line = next(line for line in result.stdout.splitlines() if line.startswith("DROIDDECK_OWNERSHIP=")) + snapshot = json.loads(line.removeprefix("DROIDDECK_OWNERSHIP=")) + if not snapshot["account"].isdigit() or int(snapshot["account"]) <= 0: + raise ValueError("invalid Steam account") + snapshot["candidates"] = candidates + snapshot["sources"] = sources + save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot) + pending = unimported(steam_root, snapshot, candidates) + status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values())) + except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error: + status = "ownership check unavailable: " + str(error) + failures += 1 + next_probe = now + min(300, 30 * 2 ** failures) + elif candidates: + status = last_status + if pending and pending != requested and not game_running() and downloads_idle(steam_root): + requested = pending + print("bannerlator-steam-games: restarting the client once to import %s" % pending, flush=True) + try: + request_restart(steam_root) + except (OSError, subprocess.TimeoutExpired) as error: + print("bannerlator-steam-games: restart unavailable: %s" % error, flush=True) + if status != last_status: + print("bannerlator-steam-games: " + status, flush=True) + last_status = status + time.sleep(30) + + +def installed_build(folder, appid, installdir): + """The build another Steam client recorded for these files, so Steam updates from it + instead of verifying every file.""" + try: + text = (folder.parent / WINNATIVE / f"appmanifest_{appid}.acf").read_text() + install = re.search(r'("installdir"\s*")([^"\\]*)(")', text, re.I) + flags = re.search(r'"StateFlags"\s*"(\d+)"', text) + if (install and install[2] == folder.name and flags and flags[1] == "4" + and re.search(rf'"appid"\s*"{appid}"', text) and '"InstalledDepots"' in text): + return text[:install.start(2)] + installdir + text[install.end(2):] + except OSError: + pass + if not (folder / ".download_complete").is_file(): + return None + try: + ids = json.loads((folder / ".DepotDownloader/depot.config").read_text())["installedManifestIDs"] + depots = sorted((int(depot), int(gid)) for depot, gid in ids.items()) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + return None + if not depots or not all(0 < depot < 0x80000000 and 0 < gid < 0x7FFFFFFFFFFFFFFF for depot, gid in depots): + return None + return "".join(f' "{depot}"\n {{\n "manifest" "{gid}"\n }}\n' for depot, gid in depots) + + +def update_not_started(text, steamapps, appid, installdir): + fields = dict(re.findall(r'^\s*"(\w+)"\s*"([^"]*)"', text, re.M)) + return (fields.get("installdir") == installdir and fields.get("buildid", "0") == "0" + and fields.get("BytesDownloaded", "0") == "0" and fields.get("BytesStaged", "0") == "0" + and re.search(r'"InstalledDepots"\s*\{\s*\}', text) is not None + and not (steamapps / "downloading" / str(appid)).exists()) + + +def seed_install(steam_root, game, appid): + steamapps = Path(steam_root) / "steamapps" + common = steamapps / "common" + name = f"DroidDeck-{appid}" + target = common / name + source = Path(game["folder"]) + title = game["name"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ") + minimal = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n' + + f' "StateFlags" "4"\n "installdir" "{name}"\n' + '}\n') + legacy = minimal.replace(' "Universe" "1"\n', '') + build = installed_build(source, appid, name) + if build is None: + content = minimal + elif build.lstrip().startswith('"AppState"'): + content = build + else: + content = minimal[:-2] + ' "InstalledDepots"\n {\n' + build + ' }\n}\n' + manifest = steamapps / f"appmanifest_{appid}.acf" + if target.is_symlink() and os.readlink(target) != str(source) and os.readlink(target) == legacy_path(source): + relink = target.with_name(name + ".droiddeck") + relink.unlink(missing_ok=True) + relink.symlink_to(source, target_is_directory=True) + os.replace(relink, target) + for root in [Path(steam_root), Path(LIBRARY)]: + existing = root / "steamapps" / manifest.name + if existing.is_file(): + if (existing == manifest and source.is_dir() and target.is_symlink() + and os.readlink(target) == str(source) + and existing.read_text() != content + and (existing.read_text() in (minimal, legacy, legacy.replace('"StateFlags" "4"', '"StateFlags" "2"')) + or (build is not None and update_not_started(existing.read_text(), steamapps, appid, name)))): + temp = manifest.with_suffix(".droiddeck") + temp.write_text(content) + os.replace(temp, manifest) + return True + if not source.is_dir(): + return False + common.mkdir(parents=True, exist_ok=True) + if os.path.lexists(target): + if not target.is_symlink() or os.readlink(target) != str(source): + return False + else: + target.symlink_to(source, target_is_directory=True) + try: + with manifest.open("x") as output: + output.write(content) + except FileExistsError: + pass + return True + + +def route(steam_root, acct, games): + snapshot = read_json(Path(acct) / "config" / STATE, {}) + if not isinstance(snapshot, dict): + snapshot = {} + owned = snapshot.get("owned", {}) if snapshot.get("account") == Path(acct).name else {} + candidates = snapshot.get("candidates", {}) + sources = snapshot.get("sources", {}) + if not all(isinstance(value, dict) for value in (owned, candidates, sources)): + owned, candidates, sources = {}, {}, {} + shortcuts, routes = [], {} + for game in games: + folder = game.get("folder", "") + appid = candidates.get(folder, candidates.get(legacy_path(folder))) + stamp = source_stamp(game) + recorded = sources.get(folder, sources.get(legacy_path(folder))) + confirmed = (isinstance(appid, int) and 0 < appid < 0x80000000 + and owned.get(str(appid)) is True and stamp is not None + and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:])) + if confirmed: + try: + if seed_install(steam_root, game, appid): + routes[str(game["appid"])] = appid + continue + except OSError as error: + print(f"bannerlator-steam-games: import unavailable ({error})") + shortcuts.append(game) + save_json(Path(acct) / "config/.droiddeck-routes.json", routes) + return shortcuts, routes + + +if __name__ == "__main__": + if len(sys.argv) < 4: + sys.exit(2) + try: + if sys.argv[1] == "probe": + print("DROIDDECK_OWNERSHIP=" + json.dumps(probe(sys.argv[2], [int(value) for value in sys.argv[3:]])), flush=True) + elif sys.argv[1] == "watch": + watch(sys.argv[2], sys.argv[3]) + else: + sys.exit(2) + except (OSError, RuntimeError, ValueError) as error: + print(str(error), file=sys.stderr) + sys.exit(1) diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-library b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-library index e67878e6e..d065db6b5 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-library +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-library @@ -1,5 +1,5 @@ #!/usr/bin/python3 -# Registers the card the app installs to (bound at /mnt/bannerlator-sd) as a library folder of the +# Registers the card the app installs to (bound at /mnt/droiddeck-sd) as a library folder of the # native Steam client, so they show as installed there instead of being downloaded a second time. # # bannerlator-steam-library @@ -14,7 +14,7 @@ import sys # The app binds the storage the user chose (Steam cog -> Game storage) at this path and names it # in BL_LIBRARY_LABEL; nothing bound = internal only, and the entry is removed so the client does # not keep offering a place that is not there. -LIBRARIES = (("/mnt/bannerlator-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),) +LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),) # The client calls its own library "Local Drive (/)", which says nothing about where that is. # It is the phone's internal storage, so say so. MAIN_LABEL = "Internal Storage" @@ -66,6 +66,26 @@ def register(steam_root, library, label): RETIRED = ("/mnt/bannerlator",) +RENAMED = (("/mnt/bannerlator-sd", "/mnt/droiddeck-sd"),) + + +def rename(steam_root, old, new): + """Moves a library registered under an earlier mount point to the current one, keeping its + entry (content id, app sizes) rather than registering it anew.""" + path = os.path.join(steam_root, "steamapps", "libraryfolders.vdf") + if not os.path.isfile(path): + return + with open(path, encoding="utf-8", errors="replace") as f: + text = f.read() + old_path = re.compile(r'("path"\s+")%s(")' % re.escape(old)) + if not old_path.search(text): + return + if re.search(r'"path"\s+"%s"' % re.escape(new), text): + forget(steam_root, old) + return + with open(path, "w", encoding="utf-8") as f: + f.write(old_path.sub(lambda m: m.group(1) + new + m.group(2), text)) + print("bannerlator-steam-library: moved %s to %s" % (old, new)) def forget(steam_root, library): @@ -152,6 +172,8 @@ def main(): steam_root = sys.argv[1] for library in RETIRED: forget(steam_root, library) + for old, new in RENAMED: + rename(steam_root, old, new) relabel(steam_root, steam_root, MAIN_LABEL) for library, label in LIBRARIES: if os.path.isdir(os.path.join(library, "steamapps")): diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts index 7f7606912..0abb8b719 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts @@ -1,15 +1,7 @@ #!/usr/bin/env python3 -"""Puts the app's added games (Windows games in the user's own folders) into the Steam client's -library as non-Steam shortcuts, each mapped to the ARM64 Proton, before the client starts. +"""Import added games while Steam is closed, preserving user-created shortcuts. - bannerlator-steam-shortcuts - -The JSON is a list the app writes each session: {"name", "exe", "dir", "appid"} with guest paths. -The client keeps non-Steam games in userdata//config/shortcuts.vdf, a binary VDF it -reads at start-up and rewrites at exit, so this runs while it is down. Entries the app wrote -carry the tag "droiddeck-app" and are replaced wholesale; anything the user added inside the -client is kept as it is. The appid is the one the client itself derives (crc32 of exe+name with -the top bit set), so the launch URL the app uses matches what the client shows. +Usage: bannerlator-steam-shortcuts """ import importlib.machinery import importlib.util @@ -105,7 +97,7 @@ def write(obj): return bytes(out) -def shortcut(game): +def shortcut(game, launch_options=""): appid = int(game["appid"]) & 0xFFFFFFFF return { "appid": struct.unpack(" @@ -31,8 +39,11 @@ #include #include -/* The app opens one ring per configured controller; four is what its launcher offers. */ -#define PAD_MAX 4 +/* The app opens one ring per configured controller; four is what its launcher offers. Nodes from + * UINPUT_BASE up are the virtual pads made through libfakeinput's /dev/uinput stand-in. */ +#define RING_MAX 4 +#define UINPUT_BASE 16 +#define PAD_MAX 64 #define EVENT_MINOR_BASE 64 /* BUS_VIRTUAL, and the identity Steam Input gives the gamepad it presents to a game. */ @@ -41,16 +52,23 @@ "NAME=\"Generic HID Gamepad %d\"\n" \ "PHYS=\"usb-fakeinput/input%d\"\n" +/* The identity libfakeinput gives the pad itself (FAKE_EVDEV_IDENTITY=xbox360). */ +#define PAD_PHYSICAL_UEVENT_FORMAT \ + "PRODUCT=3/45e/28e/110\n" \ + "NAME=\"Xbox 360 Controller (%d)\"\n" \ + "PHYS=\"usb-fakeinput/input%d\"\n" + struct pad { char syspath[64]; char devnode[32]; char sysname[16]; - char uevent[128]; + char uevent[256]; dev_t devnum; }; static struct pad pads[PAD_MAX]; static int pad_count; +static pthread_mutex_t virtual_lock = PTHREAD_MUTEX_INITIALIZER; /* * The slots the app published rings for, named in FAKE_EVDEV_MEMFD_PATHS as "=" @@ -66,7 +84,7 @@ static void discover_pads(void) { char *end; long slot = strtol(entry, &end, 10); - if (end != entry && *end == '=' && slot >= 0 && slot < PAD_MAX) { + if (end != entry && *end == '=' && slot >= 0 && slot < RING_MAX) { struct pad *pad = &pads[slot]; if (pad->devnode[0] == '\0') { @@ -90,6 +108,66 @@ static void ensure_pads(void) { pthread_once(&once, discover_pads); } +static int uinput_enabled(void) { + const char *enabled = getenv("FAKE_EVDEV_UINPUT"); + return enabled != NULL && atoi(enabled) != 0; +} + +/* Reads the .uevent libfakeinput wrote for virtual pad into buf; 0 when there is none. */ +static int read_virtual_uevent(int node, char *buf, size_t size) { + const char *dir = getenv("FAKE_EVDEV_DIR"); + char path[PATH_MAX]; + FILE *file; + size_t length; + + if (dir == NULL) return 0; + snprintf(path, sizeof(path), "%s/.uinput-event%d.uevent", dir, node); + if ((file = fopen(path, "re")) == NULL) return 0; + length = fread(buf, 1, size - 1, file); + fclose(file); + buf[length] = '\0'; + return length > 0; +} + +static int any_virtual_pad(void) { + char uevent[256]; + int node; + + for (node = UINPUT_BASE; node < PAD_MAX; node++) + if (read_virtual_uevent(node, uevent, sizeof(uevent))) return 1; + return 0; +} + +/* + * Brings the entry for event up to date before Wine resolves it: a virtual pad comes and + * goes with the client, and the app's pads change identity with it. + */ +static void refresh_pad(int node) { + struct pad *pad; + + if (node < 0 || node >= PAD_MAX) return; + pad = &pads[node]; + pthread_mutex_lock(&virtual_lock); + if (node >= UINPUT_BASE) { + char uevent[sizeof(pad->uevent)]; + + if (read_virtual_uevent(node, uevent, sizeof(uevent))) { + snprintf(pad->sysname, sizeof(pad->sysname), "event%d", node); + snprintf(pad->syspath, sizeof(pad->syspath), "/sys/devices/virtual/input/bannerlator%d", node); + memcpy(pad->uevent, uevent, sizeof(uevent)); + pad->devnum = makedev(13, EVENT_MINOR_BASE + (unsigned int)node); + snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%d", node); + if (node >= pad_count) pad_count = node + 1; + } else { + pad->devnode[0] = '\0'; + } + } else if (pad->devnode[0] != '\0' && uinput_enabled()) { + snprintf(pad->uevent, sizeof(pad->uevent), + any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT, node, node); + } + pthread_mutex_unlock(&virtual_lock); +} + /* The pad a synthetic syspath names, or NULL when the path is not one of ours. */ static struct pad *pad_for_syspath(const char *syspath) { int i; @@ -123,6 +201,7 @@ static struct pad *pad_for_syslink(const char *path) { if (path == NULL || strncmp(path, prefix, sizeof(prefix) - 1) != 0) return NULL; name = path + sizeof(prefix) - 1; ensure_pads(); + if (strncmp(name, "event", 5) == 0 && name[5] >= '0' && name[5] <= '9') refresh_pad(atoi(name + 5)); for (i = 0; i < pad_count; i++) { if (pads[i].devnode[0] != '\0' && strcmp(pads[i].sysname, name) == 0) return &pads[i]; } @@ -131,6 +210,9 @@ static struct pad *pad_for_syslink(const char *path) { static void *next_symbol(const char *name) { return dlsym(RTLD_NEXT, name); } +char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *)) + __attribute__((visibility("hidden"))); + /* Wine reaches libudev from its HID bus driver, which is the only caller these pads are for. */ static int caller_is_winebus(void *caller) { Dl_info info; @@ -152,7 +234,7 @@ char *realpath(const char *path, char *resolved) { } if (real_realpath == NULL) real_realpath = next_symbol("realpath"); if (real_realpath == NULL) return NULL; - return real_realpath(path, resolved); + return bl_cached_realpath(path, resolved, real_realpath); } void *udev_device_new_from_syspath(void *udev, const char *syspath) { diff --git a/tools/linuxfs/preload/kgslpoll.c b/tools/linuxfs/preload/kgslpoll.c new file mode 100644 index 000000000..00eb8f01f --- /dev/null +++ b/tools/linuxfs/preload/kgslpoll.c @@ -0,0 +1,79 @@ +/* + * A zero-timeout KGSL timestamp wait answered as the poll it was meant to be. + * + * Turnip's KGSL backend emulates timeline semaphores with timestamps, and asks "has this one + * retired yet?" by waiting on it with IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID and a timeout of 0. + * KGSL reads a timeout of 0 as no timeout at all, so the poll blocks until the GPU gets there. + * Mesa's timeline bookkeeping polls like that under a lock on every signalling submit, which put + * vkd3d-proton, DXVK, gamescope and Zink in lock-step with the GPU: one frame queued, never two. + * Found and measured by Bannerlator (PROGRESS_LOG 2026-09-29: a D3D12 demo went from 614 to + * 4335 fps with the same answer given in its Vulkan adapter); the driver-side fix is on + * Banners-Turnip, and this covers the drivers that do not carry it yet. + * + * The answer comes from the context's retired timestamp, compared the way KGSL compares them + * (with wrap-around). Anything the read does not answer - an unknown context, a device that is not + * KGSL - goes to the kernel as before. BL_NO_KGSL_POLL_FIX=1 turns it off. + */ +#define _GNU_SOURCE +#include +#include +#include +#include + +#define KGSL_IOC_TYPE 0x09 +#define KGSL_TIMESTAMP_RETIRED 0x00000002 + +struct kgsl_device_waittimestamp_ctxtid { + unsigned int context_id; + unsigned int timestamp; + unsigned int timeout; +}; + +struct kgsl_cmdstream_readtimestamp_ctxtid { + unsigned int context_id; + unsigned int type; + unsigned int timestamp; +}; + +#define IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID \ + _IOW(KGSL_IOC_TYPE, 0x7, struct kgsl_device_waittimestamp_ctxtid) +#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID \ + _IOWR(KGSL_IOC_TYPE, 0x16, struct kgsl_cmdstream_readtimestamp_ctxtid) + +static int enabled(void) { + static int cached = -1; + const char *off; + + if (cached >= 0) return cached; + off = getenv("BL_NO_KGSL_POLL_FIX"); + cached = !(off != NULL && off[0] == '1'); + return cached; +} + +/* True when the call was answered here, with its result in *rc (and errno set on failure). */ +__attribute__((visibility("hidden"))) int bl_kgsl_poll(int (*real)(int, unsigned long, void *), + int fd, unsigned long request, void *arg, + int *rc) { + const struct kgsl_device_waittimestamp_ctxtid *wait = arg; + struct kgsl_cmdstream_readtimestamp_ctxtid read; + int saved = errno; + + if (request != IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID || arg == NULL || wait->timeout != 0 || + !enabled()) + return 0; + read.context_id = wait->context_id; + read.type = KGSL_TIMESTAMP_RETIRED; + read.timestamp = 0; + if (real(fd, IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, &read) != 0) { + errno = saved; + return 0; + } + if ((int32_t)(read.timestamp - wait->timestamp) >= 0) { + errno = saved; + *rc = 0; + } else { + errno = ETIMEDOUT; + *rc = -1; + } + return 1; +} diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index 4b79c3f3f..a835c6cdd 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -349,6 +349,9 @@ static int is_link_query(unsigned long request) { || request == SIOCGIFBRDADDR; } +int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request, + void *arg, int *rc) __attribute__((visibility("hidden"))); + /* Every DRM and evdev call comes through here, so the lookup is done once. Two threads racing * to store it store the same pointer. */ int ioctl(int fd, unsigned long request, ...) { @@ -360,7 +363,9 @@ int ioctl(int fd, unsigned long request, ...) { va_end(ap); if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl"); - int rc = real(fd, request, arg); + int 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; diff --git a/tools/linuxfs/preload/pathcache.c b/tools/linuxfs/preload/pathcache.c new file mode 100644 index 000000000..2f2cfd3d4 --- /dev/null +++ b/tools/linuxfs/preload/pathcache.c @@ -0,0 +1,189 @@ +/* + * Path lookups the Steam client repeats, answered from a short-lived cache. + * + * While it registers its compatibility tools after logon, the client resolves the same few + * directories - its local tools under compatibilitytools.d and its own platform directory - with + * realpath() and access() thousands of times a second. Each realpath() is one readlinkat() per + * path component, and under proot every one of those is a trapped syscall with a round trip + * through the tracer. Measured on an AYN Thor, that loop was 23 of the client's 31 seconds of + * startup, with proot busy for 16 of them. + * + * Only the client itself uses the cache, never a game or a helper. Only successful answers are + * kept, and only for a moment: a path that stops existing is noticed within PATH_CACHE_TTL_NS, and + * one that starts existing is never hidden, since failures always go to the filesystem. + * BL_NO_PATH_CACHE=1 turns it off. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PATH_CACHE_SLOTS 256 +#define PATH_CACHE_KEY_MAX 512 +#define PATH_CACHE_TTL_NS 2000000000LL + +enum { KIND_REALPATH, KIND_ACCESS }; + +struct entry { + long long stamp; + unsigned hash; + int kind; + int mode; + int flags; + char key[PATH_CACHE_KEY_MAX]; + char *value; +}; + +static struct entry table[PATH_CACHE_SLOTS]; +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + +static long long now_ns(void) { + struct timespec t; + + clock_gettime(CLOCK_MONOTONIC_COARSE, &t); + return (long long)t.tv_sec * 1000000000LL + t.tv_nsec; +} + +static int enabled(void) { + static int cached = -1; + const char *off; + + if (cached >= 0) return cached; + off = getenv("BL_NO_PATH_CACHE"); + cached = strcmp(program_invocation_short_name, "steam") == 0 && + strstr(program_invocation_name, "steamrtarm64") != NULL && + !(off != NULL && off[0] == '1'); + return cached; +} + +static unsigned hash_of(const char *s, int kind, int mode, int flags) { + unsigned h = 2166136261u ^ (unsigned)(kind * 31 + mode * 7 + flags); + + while (*s) h = (h ^ (unsigned char)*s++) * 16777619u; + return h; +} + +static int cacheable(const char *path) { + return path != NULL && path[0] == '/' && strlen(path) < PATH_CACHE_KEY_MAX && enabled(); +} + +static struct entry *find(const char *path, int kind, int mode, int flags, unsigned h) { + struct entry *e = &table[h % PATH_CACHE_SLOTS]; + + if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) return NULL; + if (now_ns() - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) return NULL; + return e; +} + +static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) { + struct entry *e = &table[h % PATH_CACHE_SLOTS]; + char *copy = value != NULL ? strdup(value) : NULL; + + if (value != NULL && copy == NULL) return; + free(e->value); + e->value = copy; + e->hash = h; + e->kind = kind; + e->mode = mode; + e->flags = flags; + memcpy(e->key, path, strlen(path) + 1); + e->stamp = now_ns(); +} + +__attribute__((visibility("hidden"))) +char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *)) { + char out[PATH_MAX]; + unsigned h; + struct entry *e; + + if (!cacheable(path)) return real(path, resolved); + h = hash_of(path, KIND_REALPATH, 0, 0); + pthread_mutex_lock(&lock); + e = find(path, KIND_REALPATH, 0, 0, h); + if (e != NULL && e->value != NULL) { + size_t n = strlen(e->value) + 1; + char *result = resolved != NULL ? resolved : malloc(n); + if (result != NULL) memcpy(result, e->value, n); + pthread_mutex_unlock(&lock); + return result; + } + pthread_mutex_unlock(&lock); + if (real(path, out) == NULL) return NULL; + pthread_mutex_lock(&lock); + store(path, KIND_REALPATH, 0, 0, h, out); + pthread_mutex_unlock(&lock); + if (resolved != NULL) { + memcpy(resolved, out, strlen(out) + 1); + return resolved; + } + return strdup(out); +} + +static int cached_access(const char *path, int mode, int flags, int (*check)(const char *, int, int)) { + unsigned h; + int hit; + int result; + + if (!cacheable(path)) return check(path, mode, flags); + h = hash_of(path, KIND_ACCESS, mode, flags); + pthread_mutex_lock(&lock); + hit = find(path, KIND_ACCESS, mode, flags, h) != NULL; + pthread_mutex_unlock(&lock); + if (hit) return 0; + result = check(path, mode, flags); + if (result == 0) { + pthread_mutex_lock(&lock); + store(path, KIND_ACCESS, mode, flags, h, NULL); + pthread_mutex_unlock(&lock); + } + return result; +} + +static int (*next_faccessat(void))(int, const char *, int, int) { + static int (*real)(int, const char *, int, int); + + if (real == NULL) real = (int (*)(int, const char *, int, int))dlsym(RTLD_NEXT, "faccessat"); + return real; +} + +static int check_cwd(const char *path, int mode, int flags) { + int (*real)(int, const char *, int, int) = next_faccessat(); + + if (real == NULL) { + errno = ENOSYS; + return -1; + } + return real(AT_FDCWD, path, mode, flags); +} + +int access(const char *path, int mode) { + return cached_access(path, mode, 0, check_cwd); +} + +int euidaccess(const char *path, int mode) { + return cached_access(path, mode, AT_EACCESS, check_cwd); +} + +int eaccess(const char *path, int mode) { + return cached_access(path, mode, AT_EACCESS, check_cwd); +} + +int faccessat(int dirfd, const char *path, int mode, int flags) { + int (*real)(int, const char *, int, int); + + if (dirfd == AT_FDCWD) { + return cached_access(path, mode, flags, check_cwd); + } + real = next_faccessat(); + if (real == NULL) { + errno = ENOSYS; + return -1; + } + return real(dirfd, path, mode, flags); +} diff --git a/tools/linuxfs/preload/sysv.c b/tools/linuxfs/preload/sysv.c index 6b9a21dc8..36d7bdd70 100644 --- a/tools/linuxfs/preload/sysv.c +++ b/tools/linuxfs/preload/sysv.c @@ -7,7 +7,8 @@ * segment is a plain file that shmat maps. Objects are found by the inode of their file, which is * what the id is. semop applies its operations one by one (no all-or-nothing across a set) and * SEM_UNDO is accepted but not performed - enough for the client, which uses single-counter sets. - * Message queues stay unsupported. */ + * A message queue is a table of slots in its file: gamescope hands mangoapp (Deck mode's performance + * overlay) each frame's timings through one. */ #define _GNU_SOURCE #include #include @@ -15,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -23,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -396,6 +399,126 @@ int shmctl(int shmid, int cmd, struct shmid_ds *buf) { } } +/* ------------------------------------------------------------------ message queues */ + +/* Only what gamescope and mangoapp use: msgtyp 0 or > 0, IPC_NOWAIT and IPC_RMID. */ +#define MSG_MAGIC 0x574e4d51u /* "WNMQ" */ +#define MSG_SLOTS 32 + +struct msg_queue { + uint32_t magic; + _Atomic int32_t lock; /* 0 free, else the holder's pid */ + _Atomic int32_t changed; /* bumped on every send and receive; waiters sleep on it */ + uint64_t next_seq; + struct { uint64_t seq; long mtype; size_t len; char data[2048]; } slot[MSG_SLOTS]; /* seq 0: free */ +}; + +static struct msg_queue *msg_map(int id) { + int fd = open_by_id("msg", id); + if (fd < 0) return NULL; + struct msg_queue *q = mmap(NULL, sizeof(*q), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + close(fd); + if (q == MAP_FAILED) return NULL; + if (q->magic == MSG_MAGIC) return q; + munmap(q, sizeof(*q)); + errno = EINVAL; + return NULL; +} + +/* A process killed while holding the lock (Android ends sessions without warning) loses it. */ +static void msg_lock(struct msg_queue *q) { + for (int32_t owner = 0; !atomic_compare_exchange_strong(&q->lock, &owner, getpid()); owner = 0) { + if (kill(owner, 0) != 0 && errno == ESRCH) atomic_compare_exchange_strong(&q->lock, &owner, 0); + else futex(&q->lock, FUTEX_WAIT, owner, &(struct timespec){0, 20000000}); + } +} + +static void msg_unlock(struct msg_queue *q, int changed) { + atomic_store(&q->lock, 0); + futex(&q->lock, FUTEX_WAKE, 1, NULL); + if (changed) { + atomic_fetch_add(&q->changed, 1); + futex(&q->changed, FUTEX_WAKE, INT_MAX, NULL); + } +} + +int msgget(key_t key, int msgflg) { + int created; + int fd = open_object("msg", key, msgflg, &created); + if (fd < 0) return -1; + uint32_t magic = MSG_MAGIC; + if (created && (ftruncate(fd, sizeof(struct msg_queue)) != 0 || pwrite(fd, &magic, sizeof(magic), 0) != sizeof(magic))) { + close(fd); + return -1; + } + int id = object_id(fd); + close(fd); + return id; +} + +int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) { + struct msg_queue *q = msg_map(msqid); + if (!q) return -1; + if (msgsz > sizeof(q->slot[0].data) || *(const long *)msgp < 1) { munmap(q, sizeof(*q)); errno = EINVAL; return -1; } + for (;;) { + msg_lock(q); + int32_t seen = atomic_load(&q->changed); + for (int i = 0; i < MSG_SLOTS; i++) { + if (q->slot[i].seq) continue; + q->slot[i].mtype = *(const long *)msgp; + q->slot[i].len = msgsz; + memcpy(q->slot[i].data, (const long *)msgp + 1, msgsz); + q->slot[i].seq = ++q->next_seq; + msg_unlock(q, 1); + munmap(q, sizeof(*q)); + return 0; + } + msg_unlock(q, 0); + if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) { + munmap(q, sizeof(*q)); + if (msgflg & IPC_NOWAIT) errno = EAGAIN; + return -1; + } + } +} + +ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) { + if (msgtyp < 0) { errno = EINVAL; return -1; } + struct msg_queue *q = msg_map(msqid); + if (!q) return -1; + for (;;) { + msg_lock(q); + int32_t seen = atomic_load(&q->changed); + int best = -1; + for (int i = 0; i < MSG_SLOTS; i++) + if (q->slot[i].seq && (!msgtyp || q->slot[i].mtype == msgtyp) && (best < 0 || q->slot[i].seq < q->slot[best].seq)) + best = i; + if (best >= 0) { + size_t n = q->slot[best].len < msgsz ? q->slot[best].len : msgsz; + *(long *)msgp = q->slot[best].mtype; + memcpy((long *)msgp + 1, q->slot[best].data, n); + q->slot[best].seq = 0; + msg_unlock(q, 1); + munmap(q, sizeof(*q)); + return (ssize_t)n; + } + msg_unlock(q, 0); + if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) { + munmap(q, sizeof(*q)); + if (msgflg & IPC_NOWAIT) errno = ENOMSG; + return -1; + } + } +} + +int msgctl(int msqid, int cmd, struct msqid_ds *buf) { + if (cmd != IPC_RMID) { errno = EINVAL; return -1; } + pthread_mutex_lock(&g_lock); + int rc = unlink_by_id("msg", msqid); + pthread_mutex_unlock(&g_lock); + return rc; +} + /* * fork() carries over only the calling thread, so a lock another thread was holding at that * instant stays held in the child by a thread that is not there to release it. Taking it before diff --git a/tools/linuxfs/preload/tracefs.c b/tools/linuxfs/preload/tracefs.c new file mode 100644 index 000000000..17d45a01a --- /dev/null +++ b/tools/linuxfs/preload/tracefs.c @@ -0,0 +1,101 @@ +/* + * A trace instance for mangoapp where the kernel's tracefs is closed to the app. + * + * Valve's mangoapp (Deck mode's performance overlay) reads the GPU memory total on a Qualcomm + * display driver (msm_dpu / msm_drm) from the gpu_mem_total event, through a tracefs instance of + * its own - and aborts when tracefs_instance_create() fails, taking the whole overlay with it. + * Android mounts tracefs for root and the readtracefs group only, so it always fails here. + * + * The real calls run first. Only when they fail is the instance placed in an empty directory of + * the session's own, and reading its events answers with one gpu_mem_total record carrying the + * total KGSL - the GPU driver of every Adreno under Android - reports to the app. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +#define STANDIN_DIR "/tmp/droiddeck-tracefs" +#define KGSL_TOTAL "/sys/class/kgsl/kgsl/page_alloc" + +struct tracefs_instance; +struct tep_handle; +struct tep_event; + +/* The head of libtraceevent 1.8's struct tep_record (the version tools/mangoapp/packages.txt pins). */ +struct tep_record { + unsigned long long ts, offset; + long long missed_events; + int record_size, size; + void *data; + int cpu, ref_count, locked; + void *priv; +}; + +/* The event as Android kernels declare it (trace/events/gpu_mem.h). */ +static const char gpu_mem_total_format[] = + "name: gpu_mem_total\n" + "ID: 1\n" + "format:\n" + "\tfield:unsigned short common_type;\toffset:0;\tsize:2;\tsigned:0;\n" + "\tfield:unsigned char common_flags;\toffset:2;\tsize:1;\tsigned:0;\n" + "\tfield:unsigned char common_preempt_count;\toffset:3;\tsize:1;\tsigned:0;\n" + "\tfield:int common_pid;\toffset:4;\tsize:4;\tsigned:1;\n" + "\n" + "\tfield:uint32_t gpu_id;\toffset:8;\tsize:4;\tsigned:0;\n" + "\tfield:uint32_t pid;\toffset:12;\tsize:4;\tsigned:0;\n" + "\tfield:uint64_t size;\toffset:16;\tsize:8;\tsigned:0;\n" + "\n" + "print fmt: \"gpu_id=%u pid=%u size=%llu\", REC->gpu_id, REC->pid, REC->size\n"; + +static struct tracefs_instance *standin; + +struct tracefs_instance *tracefs_instance_create(const char *name) { + struct tracefs_instance *(*real)(const char *) = dlsym(RTLD_NEXT, "tracefs_instance_create"); + struct tracefs_instance *instance = real ? real(name) : NULL; + if (instance || !name) return instance; + struct tracefs_instance *(*alloc)(const char *, const char *) = dlsym(RTLD_NEXT, "tracefs_instance_alloc"); + if (!alloc) return NULL; + char path[PATH_MAX]; + mkdir(STANDIN_DIR, 0700); + mkdir(STANDIN_DIR "/instances", 0700); + snprintf(path, sizeof(path), STANDIN_DIR "/instances/%s", name); + mkdir(path, 0700); + return standin = alloc(STANDIN_DIR, name); +} + +struct tep_handle *tracefs_local_events(const char *tracing_dir) { + if (!tracing_dir || strncmp(tracing_dir, STANDIN_DIR "/", sizeof(STANDIN_DIR))) { + struct tep_handle *(*real)(const char *) = dlsym(RTLD_NEXT, "tracefs_local_events"); + return real ? real(tracing_dir) : NULL; + } + struct tep_handle *(*tep_alloc)(void) = dlsym(RTLD_DEFAULT, "tep_alloc"); + int (*parse)(struct tep_handle *, const char *, unsigned long, const char *) = dlsym(RTLD_DEFAULT, "tep_parse_event"); + struct tep_handle *tep = tep_alloc ? tep_alloc() : NULL; + if (tep && parse) parse(tep, gpu_mem_total_format, sizeof(gpu_mem_total_format) - 1, "gpu_mem"); + return tep; +} + +int tracefs_iterate_raw_events(struct tep_handle *tep, struct tracefs_instance *instance, void *cpus, int cpu_size, + int (*callback)(struct tep_event *, struct tep_record *, int, void *), void *context) { + if (!standin || instance != standin) { + int (*real)(struct tep_handle *, struct tracefs_instance *, void *, int, + int (*)(struct tep_event *, struct tep_record *, int, void *), void *) = + dlsym(RTLD_NEXT, "tracefs_iterate_raw_events"); + return real ? real(tep, instance, cpus, cpu_size, callback, context) : -1; + } + struct tep_event *(*find)(struct tep_handle *, int) = dlsym(RTLD_DEFAULT, "tep_find_event"); + struct tep_event *event = find && tep ? find(tep, 1) : NULL; + unsigned long long total; + FILE *f = fopen(KGSL_TOTAL, "r"); + int have = f && fscanf(f, "%llu", &total) == 1; + if (f) fclose(f); + if (!event || !have || !callback) return -1; + struct { uint16_t type; uint8_t flags, preempt; int32_t common_pid; uint32_t gpu_id, pid; uint64_t size; } data = { + .type = 1, .size = total}; + struct tep_record record = {.record_size = sizeof(data), .size = sizeof(data), .data = &data}; + return callback(event, &record, 0, context); +} diff --git a/tools/mangoapp/mangoapp b/tools/mangoapp/mangoapp index 6557ed559..e912be1a8 100644 --- a/tools/mangoapp/mangoapp +++ b/tools/mangoapp/mangoapp @@ -1,4 +1,21 @@ #!/bin/sh # gamescope --mangoapp runs `mangoapp` from PATH; this puts Valve's build beside the libraries the # runtime lacks (fmt 10, spdlog 1.13, glfw, libtracefs, libtraceevent), staged by the app. +# mangoapp reads its window through GLFW's X11 API. GLFW 3.4 takes XDG_SESSION_TYPE=wayland with a +# WAYLAND_DISPLAY as Wayland-only, and unset, libwayland falls back to wayland-0 - DroidDeck's own +# compositor, which shares XDG_RUNTIME_DIR - so both fail; x11 makes GLFW use gamescope's X server. +export XDG_SESSION_TYPE=x11 +# gamescope's reaper restarts mangoapp the moment it exits, with no backoff. One that dies at start +# (a stale session preload without the System V queue, a driver it crashes on) was started about +# once a second for the whole session, each start a full exec under proot - the Steam menu itself +# lagged. More than 5 starts in 60 s leaves the overlay off: this waits instead of exiting, so the +# reaper has nothing to restart until the session ends. +starts=/tmp/droiddeck-mangoapp-starts +now=$(date +%s) +recent=$(awk -v now="$now" '$1 > now - 60' "$starts" 2>/dev/null) +printf '%s\n%s\n' "$recent" "$now" | sed '/^$/d' > "$starts" +if [ "$(wc -l < "$starts")" -gt 5 ]; then + echo "mangoapp: started $(wc -l < "$starts") times in 60 s; the performance overlay stays off for this session" >&2 + exec sleep infinity +fi LD_LIBRARY_PATH=/usr/local/lib/mangoapp${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} exec /usr/local/lib/mangoapp/mangoapp "$@" diff --git a/tools/proot/PATCHES.md b/tools/proot/PATCHES.md index aa528b746..ef781dc8a 100644 --- a/tools/proot/PATCHES.md +++ b/tools/proot/PATCHES.md @@ -44,3 +44,39 @@ Ported from WinNative (`main`, 53836ca9, "Fix/performance and vac"): - `0009-tracee-relatives-sweep.patch` - tracees count their children, so a terminating thread with no children or ptracees no longer walks every tracee; the per-stop memory collector is emptied instead of freed and reallocated. + +Added for Flatpak: + +- `0010-new-mount-api-enosys.patch` - `open_tree`, `move_mount`, `fspick` and `mount_setattr` + answer `ENOSYS`. They take paths proot never translated, so libglnx's `open_tree(AT_FDCWD, "/")` + handed Flatpak a descriptor for the host's root and it tried to create directories there + (`mkdirat(root): Operation not permitted`); unsupported, libglnx falls back to `openat`. +- `0012-android-hardlink-denial.patch` - Android's SELinux policy denies apps hard links, so + `linkat` fails with `EACCES` and Flatpak could not create its repo (`Creating repo: linkat: + Permission denied`). `O_TMPFILE` answers `EOPNOTSUPP`, so libglnx writes a named temporary file + and renames it, and a denied link answers `EPERM`, on which ostree's checkout copies instead. +Added by DroidDeck: + +- `0011-kompat-utsname-only.patch` - `--kernel-release` (the guest's `DroidDeck` hostname) loads + kompat, whose filter traps `futex`, `fcntl`, `epoll_pwait`, `pselect6`, `pipe2`, `eventfd2`, + `socket` and more, and which strips `AT_SYSINFO_EHDR` on every `execve`, so glibc runs without + the vDSO. When the virtual release is not older than the real kernel and the hwcap is left + alone, every one of those handlers is a no-op: kompat now traces only `uname`, `sethostname` + and `setdomainname` and leaves the auxv as the kernel wrote it. On an SD 8 Gen 2 guest this + took a futex ping-pong from 467 to 97 us, `epoll_pwait` from 60 to 0.8 us and `fcntl` from + 40-107 to 0.4 us, and `clock_gettime` back to the vDSO. +- `0012-fake_id0-identity-only.patch` - `-i uid:gid` (for Xwayland's setgid/setuid before it runs + xkbcomp) loads fake_id0, whose filter traps every `fstat`/`newfstatat`/`stat` (entry and exit), + every `sendmsg` (all Wayland, X11, Chromium and PulseAudio traffic), `socket`, `getsockopt`, the + `get*id` family and the chown/chmod family. When the ids given are the ones proot really has and + are not 0, every one of those handlers is a no-op; fake_id0 now traces only the `set*id` family + and the xattr permission fixups, and leaves set-user-ID bits alone on `execve` (Android mounts the + app's data `nosuid`, so the kernel would not honour them either), which keeps the ids fixed. On an + x86_64 host build under the same options: `fstat` 41.7 -> 1.3 us, `sendmsg` 18.0 -> 2.5 us. +- `0013-seccomp-ioctl-by-request-and-kernel-exit-stops.patch` - every `ioctl` stopped on entry and + exit, which is every GPU submit and wait. The filter now traces only the requests enter.c and + exit.c act on (`TCSETSF`, the four termios2 requests, `FICLONE`) and allows the rest at once, and + the ioctl block is emitted first (after WinNative 53836ca9, which traces only the termios2 ones). + 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). diff --git a/tools/proot/patches/0010-new-mount-api-enosys.patch b/tools/proot/patches/0010-new-mount-api-enosys.patch new file mode 100644 index 000000000..87fd43d1f --- /dev/null +++ b/tools/proot/patches/0010-new-mount-api-enosys.patch @@ -0,0 +1,105 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: DroidDeck +Date: Tue, 29 Sep 2026 08:00:00 -0400 +Subject: [PATCH] syscall: answer the new mount API with ENOSYS + +open_tree(AT_FDCWD, "/") and its relatives take paths proot never +translates, so libglnx (Flatpak) got a descriptor for the host root and +created directories there. Unsupported, callers fall back to openat. +--- +diff --git a/src/syscall/enter.c b/src/syscall/enter.c +index 1d3b3fd..32d2503 100644 +--- a/src/syscall/enter.c ++++ b/src/syscall/enter.c +@@ -465,6 +465,15 @@ int translate_syscall_enter(Tracee *tracee) + status = -ENOSYS; + break; + ++ /* The new mount API opens and moves paths proot never sees: open_tree(AT_FDCWD, "/") ++ * hands back the host's root. Callers (libglnx, systemd) fall back to openat. */ ++ case PR_open_tree: ++ case PR_move_mount: ++ case PR_fspick: ++ case PR_mount_setattr: ++ status = -ENOSYS; ++ break; ++ + case PR_inotify_add_watch: + flags = peek_reg(tracee, CURRENT, SYSARG_3); + +diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c +index 0b381bb..6ba7b67 100644 +--- a/src/syscall/seccomp.c ++++ b/src/syscall/seccomp.c +@@ -457,6 +457,10 @@ static FilteredSysnum proot_sysnums[] = { + { PR_open, 0 }, + { PR_openat, 0 }, + { PR_openat2, 0 }, ++ { PR_open_tree, 0 }, ++ { PR_move_mount, 0 }, ++ { PR_fspick, 0 }, ++ { PR_mount_setattr, 0 }, + { PR_pivot_root, 0 }, + { PR_prctl, 0 }, + { PR_prlimit64, FILTER_SYSEXIT }, +diff --git a/src/syscall/sysnums-arm.h b/src/syscall/sysnums-arm.h +index e3f6f6b..ebf0afc 100644 +--- a/src/syscall/sysnums-arm.h ++++ b/src/syscall/sysnums-arm.h +@@ -358,6 +358,10 @@ static const Sysnum sysnums_arm[] = { + [ 397 ] = PR_statx, + [ 439 ] = PR_faccessat2, + [ 435 ] = PR_clone3, ++ [ 428 ] = PR_open_tree, ++ [ 429 ] = PR_move_mount, ++ [ 433 ] = PR_fspick, + [ 437 ] = PR_openat2, ++ [ 442 ] = PR_mount_setattr, + [ 452 ] = PR_fchmodat2, + }; +diff --git a/src/syscall/sysnums-arm64.h b/src/syscall/sysnums-arm64.h +index b257339..c68a1f8 100644 +--- a/src/syscall/sysnums-arm64.h ++++ b/src/syscall/sysnums-arm64.h +@@ -278,8 +278,12 @@ static const Sysnum sysnums_arm64[] = { + [ 289 ] = PR_pkey_alloc, + [ 290 ] = PR_pkey_free, + [ 291 ] = PR_statx, ++ [ 428 ] = PR_open_tree, ++ [ 429 ] = PR_move_mount, ++ [ 433 ] = PR_fspick, + [ 435 ] = PR_clone3, + [ 437 ] = PR_openat2, ++ [ 442 ] = PR_mount_setattr, + [ 439 ] = PR_faccessat2, + [ 452 ] = PR_fchmodat2, + }; +diff --git a/src/syscall/sysnums.list b/src/syscall/sysnums.list +index c221ddd..93ea2e2 100644 +--- a/src/syscall/sysnums.list ++++ b/src/syscall/sysnums.list +@@ -86,6 +86,7 @@ SYSNUM(flock) + SYSNUM(fork) + SYSNUM(fremovexattr) + SYSNUM(fsetxattr) ++SYSNUM(fspick) + SYSNUM(fstat) + SYSNUM(fstat64) + SYSNUM(fstatat64) +@@ -191,6 +192,8 @@ SYSNUM(mmap) + SYSNUM(mmap2) + SYSNUM(modify_ldt) + SYSNUM(mount) ++SYSNUM(mount_setattr) ++SYSNUM(move_mount) + SYSNUM(move_pages) + SYSNUM(mprotect) + SYSNUM(mpx) +@@ -221,6 +224,7 @@ SYSNUM(oldstat) + SYSNUM(olduname) + SYSNUM(open) + SYSNUM(open_by_handle_at) ++SYSNUM(open_tree) + SYSNUM(openat) + SYSNUM(openat2) + SYSNUM(pause) diff --git a/tools/proot/patches/0011-kompat-utsname-only.patch b/tools/proot/patches/0011-kompat-utsname-only.patch new file mode 100644 index 000000000..9c1949cce --- /dev/null +++ b/tools/proot/patches/0011-kompat-utsname-only.patch @@ -0,0 +1,64 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: DroidDeck +Date: Tue, 29 Sep 2026 00:00:00 +0000 +Subject: [PATCH] kompat: only trace the utsname calls when no older kernel is + emulated + +--- + src/extension/kompat/kompat.c | 29 +++++++++++++++++++++++++++-- + 1 file changed, 27 insertions(+), 2 deletions(-) + +diff --git a/src/extension/kompat/kompat.c b/src/extension/kompat/kompat.c +index 5c39942..4cb7dec 100644 +--- a/src/extension/kompat/kompat.c ++++ b/src/extension/kompat/kompat.c +@@ -985,6 +985,29 @@ static FilteredSysnum filtered_sysnums[] = { + FILTERED_SYSNUM_END, + }; + ++/* When the virtual kernel is not older than the actual one and the ++ * hwcap is left alone, the only thing left to emulate is the utsname ++ * itself: every other handler above returns without a change. */ ++static FilteredSysnum utsname_only_sysnums[] = { ++ { PR_setdomainname, FILTER_SYSEXIT }, ++ { PR_sethostname, FILTER_SYSEXIT }, ++ { PR_uname, FILTER_SYSEXIT }, ++ FILTERED_SYSNUM_END, ++}; ++ ++/** ++ * Return whether @config only renames the kernel identity (nodename, ++ * domainname, version string) without emulating an older kernel or ++ * another hwcap, in which case futex, fcntl, epoll_pwait, ... don't ++ * have to stop in the tracer and the vDSO can be left in place. ++ */ ++static bool utsname_only(const Config *config) ++{ ++ return config->actual_release != 0 ++ && config->virtual_release >= config->actual_release ++ && config->hwcap == (word_t) -1; ++} ++ + /** + * Handler for this @extension. It is triggered each time an @event + * occured. See ExtensionEvent for the meaning of @data1 and @data2. +@@ -1007,7 +1030,9 @@ int kompat_callback(Extension *extension, ExtensionEvent event, + if (status < 0) + return -1; + +- extension->filtered_sysnums = filtered_sysnums; ++ extension->filtered_sysnums = utsname_only(config) ++ ? utsname_only_sysnums ++ : filtered_sysnums; + return 0; + } + +@@ -1038,7 +1063,7 @@ int kompat_callback(Extension *extension, ExtensionEvent event, + + /* Note: this can be done only before PRoot pushes the + * load script into tracee's stack. */ +- if ((int) result >= 0 && sysnum == PR_execve) ++ if ((int) result >= 0 && sysnum == PR_execve && !utsname_only(config)) + adjust_elf_auxv(tracee, config); + return 0; + } diff --git a/tools/proot/patches/0012-android-hardlink-denial.patch b/tools/proot/patches/0012-android-hardlink-denial.patch new file mode 100644 index 000000000..e2d089fb3 --- /dev/null +++ b/tools/proot/patches/0012-android-hardlink-denial.patch @@ -0,0 +1,82 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: DroidDeck +Date: Tue, 29 Sep 2026 15:00:00 -0400 +Subject: [PATCH] syscall: work around Android's denial of hard links + +SELinux denies apps the file link permission, so linkat fails with +EACCES. libostree names its O_TMPFILE files with linkat and failed to +create the Flathub repo ("Creating repo: linkat: Permission denied"). +O_TMPFILE now answers EOPNOTSUPP, so libglnx falls back to a named +temporary file and a rename, and a denied link answers EPERM, which +ostree's checkout takes as a filesystem without hard links and copies. +--- +diff --git a/src/syscall/enter.c b/src/syscall/enter.c +index 8c3eb2e..4c28e10 100644 +--- a/src/syscall/enter.c ++++ b/src/syscall/enter.c +@@ -400,6 +400,13 @@ int translate_syscall_enter(Tracee *tracee) + + case PR_open: + flags = peek_reg(tracee, CURRENT, SYSARG_2); ++#ifdef __ANDROID__ ++ /* An O_TMPFILE file can only be named by linkat, which Android denies apps. */ ++ if ((flags & __O_TMPFILE) != 0) { ++ status = -EOPNOTSUPP; ++ break; ++ } ++#endif + + if ( ((flags & O_NOFOLLOW) != 0) + || ((flags & O_EXCL) != 0 && (flags & O_CREAT) != 0)) +@@ -518,6 +525,12 @@ int translate_syscall_enter(Tracee *tracee) + case PR_openat: + dirfd = peek_reg(tracee, CURRENT, SYSARG_1); + flags = peek_reg(tracee, CURRENT, SYSARG_3); ++#ifdef __ANDROID__ ++ if ((flags & __O_TMPFILE) != 0) { ++ status = -EOPNOTSUPP; ++ break; ++ } ++#endif + + status = get_sysarg_path(tracee, path, SYSARG_2); + if (status < 0) +diff --git a/src/syscall/exit.c b/src/syscall/exit.c +index df41084..5d981db 100644 +--- a/src/syscall/exit.c ++++ b/src/syscall/exit.c +@@ -544,6 +544,16 @@ void translate_syscall_exit(Tracee *tracee) + status = handle_statx_syscall(tracee, false); + break; + ++#ifdef __ANDROID__ ++ /* Android denies apps hard links with EACCES; EPERM is what callers such as ++ * libostree take as "no hard links here" and copy instead. */ ++ case PR_link: ++ case PR_linkat: ++ if ((int) syscall_result == -EACCES) ++ poke_reg(tracee, SYSARG_RESULT, -EPERM); ++ goto end; ++#endif ++ + case PR_ioctl: + if (peek_reg(tracee, ORIGINAL, SYSARG_2) == _IOW(0x94, 9, int) /* FICLONE */ && + (int) peek_reg(tracee, CURRENT, SYSARG_RESULT) == -EACCES) { +diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c +index 6d1ba47..8db9f45 100644 +--- a/src/syscall/seccomp.c ++++ b/src/syscall/seccomp.c +@@ -362,8 +362,13 @@ static FilteredSysnum proot_sysnums[] = { + { PR_lchown, 0 }, + { PR_lchown32, 0 }, + { PR_lgetxattr, 0 }, ++#ifdef __ANDROID__ ++ { PR_link, FILTER_SYSEXIT }, ++ { PR_linkat, FILTER_SYSEXIT }, ++#else + { PR_link, 0 }, + { PR_linkat, 0 }, ++#endif + { PR_listxattr, 0 }, + { PR_llistxattr, 0 }, + { PR_lremovexattr, 0 }, diff --git a/tools/proot/patches/0012-fake_id0-identity-only.patch b/tools/proot/patches/0012-fake_id0-identity-only.patch new file mode 100644 index 000000000..155b62b8e --- /dev/null +++ b/tools/proot/patches/0012-fake_id0-identity-only.patch @@ -0,0 +1,103 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: DroidDeck +Date: Tue, 29 Sep 2026 00:00:00 +0000 +Subject: [PATCH] fake_id0: only trace the set*id and xattr calls when the ids + are PRoot's own + +--- + src/extension/fake_id0/config.h | 5 ++++ + src/extension/fake_id0/fake_id0.c | 44 ++++++++++++++++++++++++++++++- + 2 files changed, 48 insertions(+), 1 deletion(-) + +diff --git a/src/extension/fake_id0/config.h b/src/extension/fake_id0/config.h +index 2e78783..5227ced 100644 +--- a/src/extension/fake_id0/config.h ++++ b/src/extension/fake_id0/config.h +@@ -2,6 +2,7 @@ + #define FAKE_ID0_CONFIG_H + + #include /* uid_t, gid_t */ ++#include /* bool, */ + + typedef struct { + uid_t ruid; +@@ -15,6 +16,10 @@ typedef struct { + gid_t fsgid; + + mode_t umask; ++ ++ /* The emulated ids are the ones PRoot really has: see ++ * identity_sysnums in fake_id0.c. */ ++ bool identity; + } Config; + + #endif /* FAKE_ID0_CONFIG_H */ +diff --git a/src/extension/fake_id0/fake_id0.c b/src/extension/fake_id0/fake_id0.c +index 9477f1c..fe08372 100644 +--- a/src/extension/fake_id0/fake_id0.c ++++ b/src/extension/fake_id0/fake_id0.c +@@ -352,6 +352,40 @@ static FilteredSysnum filtered_sysnums[] = { + FILTERED_SYSNUM_END, + }; + ++/* When the emulated ids are the ones PRoot really has, and the tracee ++ * is not root, every handler for the syscalls above but these is a ++ * no-op: stat and get*id report the real ids already, SCM_CREDENTIALS ++ * and SO_PEERCRED carry them, chown swaps an id for itself, and the ++ * permission and chroot fixups only apply to euid 0. The set*id ++ * family is still emulated (Android's app seccomp policy traps it) and ++ * so are the xattr permission fixups, which apply to any euid. An ++ * unprivileged set*id can only take an id the tracee already holds, ++ * and set-user-ID bits are not honoured in this mode (Android mounts ++ * the app's data nosuid, so the kernel would not honour them either), ++ * so the ids never change and the list stays sufficient. */ ++static FilteredSysnum identity_sysnums[] = { ++ { PR_fsetxattr, FILTER_SYSEXIT }, ++ { PR_lsetxattr, FILTER_SYSEXIT }, ++ { PR_setfsgid, FILTER_SYSEXIT }, ++ { PR_setfsgid32, FILTER_SYSEXIT }, ++ { PR_setfsuid, FILTER_SYSEXIT }, ++ { PR_setfsuid32, FILTER_SYSEXIT }, ++ { PR_setgid, FILTER_SYSEXIT }, ++ { PR_setgid32, FILTER_SYSEXIT }, ++ { PR_setregid, FILTER_SYSEXIT }, ++ { PR_setregid32, FILTER_SYSEXIT }, ++ { PR_setresgid, FILTER_SYSEXIT }, ++ { PR_setresgid32, FILTER_SYSEXIT }, ++ { PR_setresuid, FILTER_SYSEXIT }, ++ { PR_setresuid32, FILTER_SYSEXIT }, ++ { PR_setreuid, FILTER_SYSEXIT }, ++ { PR_setreuid32, FILTER_SYSEXIT }, ++ { PR_setuid, FILTER_SYSEXIT }, ++ { PR_setuid32, FILTER_SYSEXIT }, ++ { PR_setxattr, FILTER_SYSEXIT }, ++ FILTERED_SYSNUM_END, ++}; ++ + /** + * Restore the @node->mode for the given @node->path. + * +@@ -1051,6 +1085,11 @@ static int handle_sysexit_start(Tracee *tracee, Config *config) { + if ((int) result < 0 || tracee->status < 0 || sysnum != PR_execve) + return 0; + ++ /* The auxv already carries the real ids, and set-user-ID bits ++ * are not honoured in this mode: see identity_sysnums. */ ++ if (config->identity) ++ return 0; ++ + /* This has to be done before PRoot pushes the load + * script into tracee's stack. */ + if (!tracee->skip_proot_loader) +@@ -1119,7 +1158,10 @@ int fake_id0_callback(Extension *extension, ExtensionEvent event, intptr_t data1 + /* Set the umask to the typical linux value. */ + config->umask = 022; + +- extension->filtered_sysnums = filtered_sysnums; ++ config->identity = (uid != 0 && uid == (int) getuid() && gid == (int) getgid()); ++ extension->filtered_sysnums = config->identity ++ ? identity_sysnums ++ : filtered_sysnums; + return 0; + } + diff --git a/tools/proot/patches/0013-seccomp-ioctl-by-request-and-kernel-exit-stops.patch b/tools/proot/patches/0013-seccomp-ioctl-by-request-and-kernel-exit-stops.patch new file mode 100644 index 000000000..eaf62c565 --- /dev/null +++ b/tools/proot/patches/0013-seccomp-ioctl-by-request-and-kernel-exit-stops.patch @@ -0,0 +1,169 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: DroidDeck +Date: Tue, 29 Sep 2026 00:00:00 +0000 +Subject: [PATCH] seccomp: trace ioctl by request, drop exit stops the kernel + does not need + +--- + src/syscall/seccomp.c | 98 ++++++++++++++++++++++++++++++++++++++++++- + 1 file changed, 97 insertions(+), 1 deletion(-) + +diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c +index 0b381bb..1116ab2 100644 +--- a/src/syscall/seccomp.c ++++ b/src/syscall/seccomp.c +@@ -39,6 +39,11 @@ + #include /* uint*_t, UINT*_MAX, */ + #include + #include ++#include /* uname(2), */ ++#include /* sscanf(3), */ ++#include /* TCGETS2, TCSETS*2, */ ++#include /* struct termios2, */ ++#include /* FICLONE, */ + #include /* assert(3), */ + + #include "syscall/seccomp.h" +@@ -166,6 +171,46 @@ static int add_trace_prlimit_stack(struct sock_fprog *program, word_t syscall, i + return add_statements(program, LENGTH_TRACE_PRLIMIT_STACK, statements); + } + ++/** ++ * Append to @program->filter the statements that trace @syscall ++ * (ioctl) only for the requests enter.c and exit.c act on - the ++ * termios requests Android's policy denies an app on a pty, rewritten ++ * to ones it allows, and FICLONE, whose EACCES is turned into ++ * EOPNOTSUPP - and allow any other request at once. Every GPU submit ++ * and wait is an ioctl, so they no longer stop in the tracer, and the ++ * block is emitted first so they are also spared the rest of the list. ++ * (After WinNative, maxjivi05, 53836ca9.) ++ */ ++static int add_trace_ioctl_requests(struct sock_fprog *program, word_t syscall, int flag) ++{ ++ const size_t request_offset = offsetof(struct seccomp_data, args[1]); ++ ++ #define LENGTH_TRACE_IOCTL 10 ++ struct sock_filter statements[LENGTH_TRACE_IOCTL] = { ++ /* Not this syscall: skip the block, the accumulator ++ * still holds the syscall number. */ ++ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, syscall, 0, 9), ++ ++ /* Load the request's low word into the accumulator. */ ++ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, request_offset), ++ ++ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, TCSETSF, 5, 0), ++ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, TCGETS2, 4, 0), ++ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, TCSETS2, 3, 0), ++ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, TCSETSW2, 2, 0), ++ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, TCSETSF2, 1, 0), ++ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, (uint32_t) FICLONE, 0, 1), ++ ++ BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_TRACE + flag), ++ BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW) ++ }; ++ ++ DEBUG_FILTER("FILTER: trace if syscall == %ld and a termios2/TCSETSF/FICLONE request\n", ++ syscall); ++ ++ return add_statements(program, LENGTH_TRACE_IOCTL, statements); ++} ++ + static size_t trace_length(Sysnum sysnum) + { + switch (sysnum) { +@@ -174,6 +219,8 @@ static size_t trace_length(Sysnum sysnum) + return LENGTH_TRACE_SYSCALL_IF_ARG; + case PR_prlimit64: + return LENGTH_TRACE_PRLIMIT_STACK; ++ case PR_ioctl: ++ return LENGTH_TRACE_IOCTL; + default: + return LENGTH_TRACE_SYSCALL; + } +@@ -191,6 +238,8 @@ static int add_trace(struct sock_fprog *program, Sysnum sysnum, word_t syscall, + return add_trace_syscall_if_arg(program, syscall, 0, RLIMIT_STACK, flag); + case PR_prlimit64: + return add_trace_prlimit_stack(program, syscall, flag); ++ case PR_ioctl: ++ return add_trace_ioctl_requests(program, syscall, flag); + default: + return add_trace_syscall(program, syscall, flag); + } +@@ -329,7 +378,7 @@ static int set_seccomp_filters(const FilteredSysnum *sysnums) + + struct sock_fprog program = { .len = 0, .filter = NULL }; + size_t section_length; +- size_t i, j, k; ++ size_t i, j, k, pass; + int status; + + status = new_program_filter(&program); +@@ -355,8 +404,14 @@ static int set_seccomp_filters(const FilteredSysnum *sysnums) + if (status < 0) + goto end; + ++ /* Two passes: ioctl first, it is by far the most frequent ++ * syscall and almost every one of them is allowed. */ ++ for (pass = 0; pass < 2; pass++) + for (j = 0; j < seccomp_archs[i].nb_abis; j++) { + for (k = 0; sysnums[k].value != PR_void; k++) { ++ if ((sysnums[k].value == PR_ioctl) != (pass == 0)) ++ continue; ++ + /* Get the architecture specific syscall number. */ + syscall = detranslate_sysnum(seccomp_archs[i].abis[j], sysnums[k].value); + if (syscall == SYSCALL_AVOIDER) +@@ -572,12 +627,53 @@ int enable_syscall_filtering(const Tracee *tracee) + return 0; + } + ++/** ++ * Drop the exit stops PRoot only needs on kernels older than the one it ++ * runs on. The faccessat2 exit stop restores the arguments for glibc's ++ * fallback to faccessat on ENOSYS (kernels before 5.8, termux 5ba8b95); ++ * the statx one emulates the call when it fails, which only a kernel ++ * before 4.11 does for want of it - a statx Android's policy traps is ++ * emulated from SIGSYS instead. Both stops re-read and re-translate ++ * the path, and are paid on every call. ++ */ ++static void drop_unneeded_exit_stops(void) ++{ ++ static bool done = false; ++ struct utsname utsname; ++ int major, minor; ++ size_t i; ++ ++ if (done) ++ return; ++ done = true; ++ ++ if (uname(&utsname) < 0 || sscanf(utsname.release, "%d.%d", &major, &minor) != 2) ++ return; ++ ++ for (i = 0; proot_sysnums[i].value != PR_void; i++) { ++ switch (proot_sysnums[i].value) { ++ case PR_faccessat2: ++ if (major > 5 || (major == 5 && minor >= 8)) ++ proot_sysnums[i].flags &= ~FILTER_SYSEXIT; ++ break; ++ case PR_statx: ++ if (major > 4 || (major == 4 && minor >= 11)) ++ proot_sysnums[i].flags &= ~FILTER_SYSEXIT; ++ break; ++ default: ++ break; ++ } ++ } ++} ++ + static int collect_filtered_sysnums(TALLOC_CTX *context, const Tracee *tracee, + FilteredSysnum **filtered_sysnums) + { + Extension *extension; + int status; + ++ drop_unneeded_exit_stops(); ++ + /* Add the sysnums required by PRoot to the list of filtered + * sysnums. TODO: only if path translation is required. */ + status = merge_filtered_sysnums(context, filtered_sysnums, proot_sysnums); diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py new file mode 100644 index 000000000..8c37d1123 --- /dev/null +++ b/tools/tests/test_game_environment.py @@ -0,0 +1,92 @@ +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +MODULE = runpy.run_path(str(BIN / "bannerlator-game-env")) +COMPAT = runpy.run_path(str(BIN / "bannerlator-steam-compat")) + + +class GameEnvironmentTest(unittest.TestCase): + def test_profile_precedence_and_unset(self): + env = {"KEEP": "inherited", "REMOVE": "inherited", "CUSTOM": "launch option"} + config = {"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"REMOVE": None, "CUSTOM": "game", "EMPTY": ""}}} + self.assertEqual(MODULE["apply_config"](env, config, "42"), {"KEEP": "inherited", "CUSTOM": "game", "EMPTY": ""}) + self.assertEqual(env["REMOVE"], "inherited") + self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared") + + def test_invalid_configuration_is_atomic(self): + env = {"ORIGINAL": "unchanged"} + for entries in ({"A": "ok", "BAD=KEY": "x"}, {"A": "bad\0value"}, {"A": 1}): + with self.assertRaises(ValueError): + MODULE["apply_config"](env, {"version": 1, "shared": entries}, "42") + self.assertEqual(env, {"ORIGINAL": "unchanged"}) + + def test_game_ids_and_probes(self): + for prefix in ("", "/compatdata/0", "/compatdata/0-123", "/compatdata/nope", "/compatdata/4294967296"): + self.assertIsNone(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": prefix})) + self.assertEqual(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": "/a/compatdata/42/"}), "42") + self.assertEqual(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": "/a/compatdata/-1"}), "4294967295") + + def test_launch_reads_updates_preserves_argv_and_does_not_execute_values(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + config = home / ".config/droiddeck/game-environment.json" + config.parent.mkdir(parents=True) + probe = home / "fake-proton" + probe.write_text("#!/usr/bin/python3\nimport json, os, sys\nprint(json.dumps([os.environ.get('CUSTOM'), sys.argv[1:]]))\n") + probe.chmod(0o755) + env = {**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": "/compatdata/42"} + for value in ("first value", "$(touch " + str(home / "injected") + "); 'literal'=value"): + config.write_text(json.dumps({"version": 1, "shared": {"CUSTOM": value}})) + result = subprocess.check_output([sys.executable, str(BIN / "bannerlator-game-env"), str(probe), "waitforexitandrun", "path with spaces", "a=b"], env=env, text=True) + self.assertEqual(json.loads(result), [value, ["waitforexitandrun", "path with spaces", "a=b"]]) + self.assertFalse((home / "injected").exists()) + for verb, prefix in (("run", "/compatdata/42"), ("waitforexitandrun", "/compatdata/0")): + output = subprocess.check_output([sys.executable, str(BIN / "bannerlator-game-env"), str(probe), verb], env={**env, "STEAM_COMPAT_DATA_PATH": prefix, "CUSTOM": "original"}, text=True) + self.assertEqual(json.loads(output)[0], "original") + config.write_text("{broken") + result = subprocess.run([sys.executable, str(BIN / "bannerlator-game-env"), str(probe), "waitforexitandrun"], env={**env, "CUSTOM": "original"}, text=True, capture_output=True, check=True) + self.assertEqual(json.loads(result.stdout)[0], "original") + + def test_generated_valve_and_third_party_launchers_apply_configuration(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + steam = home / "Steam" + tools = steam / "compatibilitytools.d" + depot = steam / "steamapps/common" / COMPAT["SOURCES"][0] + (depot / "files/bin-arm64").mkdir(parents=True) + extra = tools / "custom-proton" + extra.mkdir(parents=True) + for base in (depot, extra): + proton = base / "proton" + proton.write_text("#!/usr/bin/python3\nimport json, os, sys\nprint(json.dumps([os.environ['CUSTOM'], sys.argv[1:]]))\nsys.exit(7)\n") + proton.chmod(0o755) + (extra / "toolmanifest.vdf").write_text('"manifest" { "commandline" "/proton %verb%" }') + COMPAT["build_tool"](str(tools / COMPAT["TOOL"])) + COMPAT["adopt_extras"](str(tools)) + config = home / ".config/droiddeck/game-environment.json" + config.parent.mkdir(parents=True) + config.write_text(json.dumps({"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"CUSTOM": "specific"}}})) + wrappers = (tools / COMPAT["TOOL"] / COMPAT["LAUNCHER"], extra / COMPAT["EXTRA_WRAPPER"]) + for wrapper in wrappers: + wrapper.write_text(wrapper.read_text().replace("/usr/local/bin/bannerlator-game-env", str(BIN / "bannerlator-game-env"))) + result = subprocess.run([str(wrapper), "waitforexitandrun", "game with spaces.exe"], + env={"PATH": os.defpath, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": "/compatdata/42", "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(steam)}, + text=True, capture_output=True) + self.assertEqual(result.returncode, 7, result.stderr) + self.assertEqual(json.loads(result.stdout), ["specific", ["waitforexitandrun", "game with spaces.exe"]]) + + def test_both_proton_wrappers_call_environment_launcher(self): + for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"): + subprocess.run(["bash", "-n"], input=script, text=True, check=True) + self.assertIn('exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env', script) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py new file mode 100644 index 000000000..34c96c5d6 --- /dev/null +++ b/tools/tests/test_steam_games.py @@ -0,0 +1,377 @@ +import importlib.machinery +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin' + + +def load(name): + loader = importlib.machinery.SourceFileLoader(name, str(BIN / name)) + spec = importlib.util.spec_from_loader(name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +imports = load('bannerlator-steam-games') +shortcuts = load('bannerlator-steam-shortcuts') +library = load('bannerlator-steam-library') + + +class ImportsTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.steam = self.root / 'Steam' + self.acct = self.steam / 'userdata/123' + self.folder = self.root / 'Games/Example' + self.folder.mkdir(parents=True) + self.exe = self.folder / 'Example.exe' + self.exe.write_bytes(b'game') + self.game = dict(name='Example', exe=str(self.exe), folder=str(self.folder), + dir=str(self.folder), appid=0x87654321) + + def snapshot(self, owned=True, account='123'): + imports.save_json(self.acct / 'config' / imports.STATE, + dict(account=account, owned={'42': owned}, + candidates={str(self.folder): 42}, + sources={str(self.folder): imports.source_stamp(self.game)})) + + def test_owned_uses_real_id_and_registers_installed_files(self): + self.snapshot() + games, routes = imports.route(self.steam, self.acct, [self.game]) + self.assertEqual([], games) + self.assertEqual({str(self.game['appid']): 42}, routes) + manifest = self.steam / 'steamapps/appmanifest_42.acf' + self.assertIn('"StateFlags" "4"', manifest.read_text()) + self.assertIn('"Universe" "1"', manifest.read_text()) + self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-42').resolve()) + self.assertEqual(b'game', self.exe.read_bytes()) + + def test_migrates_only_unchanged_legacy_import_manifests(self): + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + path = self.steam / 'steamapps/appmanifest_42.acf' + current = path.read_text() + legacy = current.replace(' "Universe" "1"\n', '').replace('"StateFlags" "4"', '"StateFlags" "2"') + path.write_text(legacy) + imports.route(self.steam, self.acct, [self.game]) + self.assertEqual(current, path.read_text()) + changed = legacy.replace('"StateFlags" "2"', '"StateFlags" "6"') + path.write_text(changed) + imports.route(self.steam, self.acct, [self.game]) + self.assertEqual(changed, path.read_text()) + + def test_unresolved_titles_are_retried_after_network_recovers(self): + listing = self.root / 'games.json' + listing.write_text(json.dumps([self.game])) + from unittest.mock import Mock + result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True}))) + with patch.object(imports, 'identify', side_effect=[None, 42]) as identify, \ + patch.object(imports, 'request_restart'), \ + patch.object(imports.time, 'monotonic', side_effect=[0, 301]), \ + patch.object(imports.time, 'sleep', side_effect=[None, RuntimeError('stop')]), \ + patch.object(imports.subprocess, 'run', return_value=result), \ + patch('builtins.print'): + with self.assertRaisesRegex(RuntimeError, 'stop'): + imports.watch(self.steam, listing) + self.assertEqual(2, identify.call_count) + snapshot = imports.read_json(self.acct / 'config' / imports.STATE, {}) + self.assertTrue(snapshot['owned']['42']) + + def run_watch(self, beats, routes=None, busy=False): + listing = self.root / 'games.json' + listing.write_text(json.dumps([self.game])) + if routes is not None: + imports.save_json(self.acct / 'config/.droiddeck-routes.json', routes) + if busy: + (self.steam / 'steamapps/downloading/7').mkdir(parents=True) + from unittest.mock import Mock + result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True}))) + with patch.object(imports, 'identify', return_value=42), \ + patch.object(imports, 'game_running', return_value=False), \ + patch.object(imports, 'request_restart') as restart, \ + patch.object(imports.time, 'monotonic', side_effect=list(range(0, 30 * beats, 30))), \ + patch.object(imports.time, 'sleep', side_effect=[None] * (beats - 1) + [RuntimeError('stop')]), \ + patch.object(imports.subprocess, 'run', return_value=result), \ + patch('builtins.print'): + with self.assertRaisesRegex(RuntimeError, 'stop'): + imports.watch(self.steam, listing) + return restart + + def test_newly_owned_game_restarts_the_client_once(self): + self.assertEqual(1, self.run_watch(3).call_count) + + def test_imported_game_does_not_restart_the_client(self): + self.assertEqual(0, self.run_watch(2, routes={'1': 42}).call_count) + + def test_restart_waits_for_downloads(self): + self.assertEqual(0, self.run_watch(2, busy=True).call_count) + + def test_unowned_unknown_and_different_account_stay_shortcuts(self): + for owned, account in [(False, '123'), (True, '456')]: + self.snapshot(owned, account) + self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game])) + (self.acct / 'config' / imports.STATE).unlink() + self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game])) + self.assertFalse((self.steam / 'steamapps').exists()) + + def winnative_manifest(self, flags='4', installdir='Example'): + path = self.folder.parent / imports.WINNATIVE / 'appmanifest_42.acf' + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('"AppState"\n{\n\t"appid"\t\t"42"\n\t"StateFlags"\t\t"%s"\n\t"installdir"\t\t"%s"\n' + '\t"buildid"\t\t"7"\n\t"InstalledDepots"\n\t{\n\t\t"43"\n\t\t{\n\t\t\t"manifest"\t\t"99"\n' + '\t\t\t"size"\t\t"4"\n\t\t}\n\t}\n}\n' % (flags, installdir)) + return path + + def test_winnative_manifest_carries_installed_build(self): + source = self.winnative_manifest() + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + text = (self.steam / 'steamapps/appmanifest_42.acf').read_text() + self.assertEqual(source.read_text().replace('"Example"', '"DroidDeck-42"'), text) + + def test_winnative_manifest_identifies_folder(self): + self.winnative_manifest() + with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError): + self.assertEqual(42, imports.identify(self.game)) + + def test_incomplete_winnative_manifest_is_ignored(self): + for flags, installdir in [('1026', 'Example'), ('4', 'Other')]: + self.winnative_manifest(flags, installdir) + self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42')) + + def test_depot_config_records_installed_depots(self): + config = self.folder / '.DepotDownloader/depot.config' + config.parent.mkdir() + config.write_text(json.dumps({'installedManifestIDs': {'43': 99}})) + self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42')) + (self.folder / '.download_complete').touch() + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + text = (self.steam / 'steamapps/appmanifest_42.acf').read_text() + self.assertIn('"InstalledDepots"\n {\n "43"\n {\n "manifest" "99"', text) + self.assertTrue(text.endswith(' }\n}\n')) + config.write_text(json.dumps({'installedManifestIDs': {'43': 0x7FFFFFFFFFFFFFFF}})) + self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42')) + + def test_bare_import_manifest_gains_installed_build(self): + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + self.winnative_manifest() + imports.route(self.steam, self.acct, [self.game]) + self.assertIn('"buildid"\t\t"7"', (self.steam / 'steamapps/appmanifest_42.acf').read_text()) + + def steam_fresh_install(self, downloaded='0'): + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + path = self.steam / 'steamapps/appmanifest_42.acf' + path.write_text('"AppState"\n{\n\t"appid"\t\t"42"\n\t"StateFlags"\t\t"6"\n\t"installdir"\t\t"DroidDeck-42"\n' + '\t"buildid"\t\t"0"\n\t"BytesDownloaded"\t\t"%s"\n\t"BytesStaged"\t\t"0"\n' + '\t"InstalledDepots"\n\t{\n\t}\n}\n' % downloaded) + self.winnative_manifest() + return path + + def test_queued_fresh_install_takes_installed_build(self): + path = self.steam_fresh_install() + imports.route(self.steam, self.acct, [self.game]) + self.assertIn('"buildid"\t\t"7"', path.read_text()) + + def test_started_fresh_install_is_left_to_steam(self): + for downloaded, staging in [('5', False), ('0', True)]: + path = self.steam_fresh_install(downloaded) + if staging: + (self.steam / 'steamapps/downloading/42').mkdir(parents=True) + before = path.read_text() + imports.route(self.steam, self.acct, [self.game]) + self.assertEqual(before, path.read_text()) + + def test_links_and_snapshots_from_the_old_mount_carry_over(self): + old = self.root / 'old-mount' + with patch.object(imports, 'LIBRARY', str(self.root / 'Games')), \ + patch.object(imports, 'LEGACY_LIBRARY', str(old)): + legacy_game = dict(self.game, folder=str(old / 'Example'), exe=str(old / 'Example/Example.exe')) + stamp = imports.source_stamp(self.game) + imports.save_json(self.acct / 'config' / imports.STATE, + dict(account='123', owned={'42': True}, candidates={legacy_game['folder']: 42}, + sources={legacy_game['folder']: [stamp[0], legacy_game['exe']] + stamp[2:]})) + link = self.steam / 'steamapps/common/DroidDeck-42' + link.parent.mkdir(parents=True) + link.symlink_to(legacy_game['folder'], target_is_directory=True) + games, routes = imports.route(self.steam, self.acct, [self.game]) + self.assertEqual([], games) + self.assertEqual({str(self.game['appid']): 42}, routes) + self.assertEqual(str(self.folder), imports.os.readlink(link)) + + def test_existing_manifest_is_never_overwritten(self): + manifest = self.steam / 'steamapps/appmanifest_42.acf' + manifest.parent.mkdir(parents=True) + manifest.write_text('Steam owns this file') + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + self.assertEqual('Steam owns this file', manifest.read_text()) + + def test_import_collision_falls_back_without_touching_files(self): + occupied = self.steam / 'steamapps/common/DroidDeck-42' + occupied.mkdir(parents=True) + self.snapshot() + self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game])) + self.assertTrue(occupied.is_dir()) + self.assertFalse(occupied.is_symlink()) + + def test_removed_folder_does_not_import(self): + self.snapshot() + self.exe.unlink() + self.folder.rmdir() + self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game])) + + def test_replaced_game_does_not_inherit_cached_ownership(self): + self.snapshot() + self.exe.write_bytes(b'a different game') + self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game])) + + def test_duplicate_owned_folders_share_one_steam_entry(self): + self.snapshot() + games, routes = imports.route(self.steam, self.acct, [self.game, self.game]) + self.assertEqual([], games) + self.assertEqual(1, len(routes)) + self.assertEqual(1, len(list((self.steam / 'steamapps').glob('*.acf')))) + + def test_explicit_appid_does_not_need_network(self): + (self.folder / 'steam_appid.txt').write_text('42\n') + with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError): + self.assertEqual(42, imports.identify(self.game)) + + def test_manifest_identity_uses_install_directory(self): + folder = self.root / 'second/steamapps/common/Custom Name' + folder.mkdir(parents=True) + (folder.parent.parent / 'appmanifest_42.acf').write_text('"AppState" { "installdir" "Custom Name" }') + game = dict(self.game, folder=str(folder), exe=str(folder / 'game.exe')) + with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError): + self.assertEqual(42, imports.identify(game)) + + def test_store_requires_unique_exact_title(self): + cases = [([{'id': 42, 'name': 'Example Deluxe'}], None), + ([{'id': 42, 'name': 'Example'}, {'id': 43, 'name': 'Example'}], None), + ([{'id': 42, 'name': 'EXAMPLE'}], 42)] + for items, expected in cases: + with patch.object(imports.urllib.request, 'urlopen') as request: + request.return_value.__enter__.return_value.read.return_value = json.dumps({'items': items}).encode() + self.assertEqual(expected, imports.identify(self.game)) + + def test_store_country_and_edition_suffixes(self): + for folder, store in [('FINAL FANTASY VII REMAKE', 'FINAL FANTASY VII REMAKE INTERGRADE'), + ('FINAL FANTASY XV', 'FINAL FANTASY XV WINDOWS EDITION')]: + with patch.object(imports.urllib.request, 'urlopen') as request: + request.return_value.__enter__.return_value.read.return_value = json.dumps({'items': [{'id': 42, 'name': store}]}).encode() + self.assertEqual(42, imports.identify(dict(self.game, name=folder))) + self.assertIn('cc=US&', request.call_args.args[0]) + + def test_edition_matching_rejects_ambiguous_titles_and_soundtracks(self): + with patch.object(imports.urllib.request, 'urlopen') as request: + request.return_value.__enter__.return_value.read.return_value = json.dumps({'items': [ + {'id': 42, 'name': 'Example WINDOWS EDITION'}, + {'id': 43, 'name': 'Example INTERGRADE'}, + {'id': 44, 'name': 'Example Soundtrack'}, + ]}).encode() + self.assertIsNone(imports.identify(self.game)) + + def test_corrupt_shortcuts_are_preserved(self): + path = self.acct / 'config/shortcuts.vdf' + path.parent.mkdir(parents=True) + original = b'corrupt' + path.write_bytes(original) + listing = self.root / 'games.json' + listing.write_text(json.dumps([self.game])) + run = subprocess.run(['python3', str(BIN / 'bannerlator-steam-shortcuts'), str(self.steam), str(listing)], capture_output=True) + self.assertEqual(1, run.returncode) + self.assertEqual(original, path.read_bytes()) + + def test_user_shortcuts_survive_owned_promotion(self): + self.snapshot() + path = self.acct / 'config/shortcuts.vdf' + manual = dict(shortcuts.shortcut(self.game), tags={'0': 'Personal'}, AppName='Manual') + path.write_bytes(shortcuts.write({'shortcuts': {'0': manual, '1': shortcuts.shortcut(self.game)}})) + listing = self.root / 'games.json' + listing.write_text(json.dumps([self.game])) + subprocess.run(['python3', str(BIN / 'bannerlator-steam-shortcuts'), str(self.steam), str(listing)], check=True, capture_output=True) + result = shortcuts.parse(path.read_bytes())['shortcuts'] + self.assertEqual([manual], list(result.values())) + self.assertEqual({str(self.game['appid']): 42}, json.loads((path.parent / '.droiddeck-routes.json').read_text())) + + +class LibraryRenameTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.steam = Path(temp.name) + self.vdf = self.steam / 'steamapps/libraryfolders.vdf' + self.vdf.parent.mkdir() + + def entry(self, index, path): + return '\t"%d"\n\t{\n\t\t"path"\t\t"%s"\n\t\t"contentid"\t\t"%d"\n\t}\n' % (index, path, 7 + index) + + def test_old_mount_keeps_its_entry_under_the_new_path(self): + self.vdf.write_text('"libraryfolders"\n{\n' + self.entry(0, '/root') + self.entry(1, '/mnt/bannerlator-sd') + '}\n') + with patch('builtins.print'): + library.rename(str(self.steam), '/mnt/bannerlator-sd', '/mnt/droiddeck-sd') + text = self.vdf.read_text() + self.assertIn('"path"\t\t"/mnt/droiddeck-sd"\n\t\t"contentid"\t\t"8"', text) + self.assertNotIn('bannerlator-sd', text) + + def test_old_mount_is_dropped_when_new_path_is_registered(self): + self.vdf.write_text('"libraryfolders"\n{\n' + self.entry(0, '/mnt/droiddeck-sd') + self.entry(1, '/mnt/bannerlator-sd') + '}\n') + with patch('builtins.print'): + library.rename(str(self.steam), '/mnt/bannerlator-sd', '/mnt/droiddeck-sd') + text = self.vdf.read_text() + self.assertEqual(1, text.count('"path"')) + self.assertIn('/mnt/droiddeck-sd', text) + + +class SteamProbeTest(unittest.TestCase): + def test_probe_reads_account_and_licenses_and_releases_handles(self): + import ctypes as C + from unittest.mock import Mock + objects, callbacks, calls = [], [], [] + + def interface(slots): + table = (C.c_void_p * 24)() + for slot, result, args, callback in slots: + fn = C.CFUNCTYPE(result, C.c_void_p, *args)(callback) + callbacks.append(fn) + table[slot] = C.cast(fn, C.c_void_p).value + obj = C.pointer(C.cast(table, C.POINTER(C.c_void_p))) + objects.extend([table, obj]) + return C.cast(obj, C.c_void_p).value + + user = interface([ + (1, C.c_bool, [], lambda _: True), + (2, C.c_uint64, [], lambda _: imports.BASE_ID + 123), + ]) + apps = interface([(6, C.c_bool, [C.c_uint32], lambda _, appid: appid == 42)]) + client = interface([ + (0, C.c_int, [], lambda _: 7), + (1, C.c_bool, [C.c_int], lambda _, pipe: calls.append(('pipe', pipe)) or True), + (2, C.c_int, [C.c_int], lambda _, pipe: 9), + (4, None, [C.c_int, C.c_int], lambda _, pipe, handle: calls.append(('user', pipe, handle))), + (5, C.c_void_p, [C.c_int, C.c_int, C.c_char_p], lambda _, handle, pipe, version: user if version == b'SteamUser021' else 0), + (15, C.c_void_p, [C.c_int, C.c_int, C.c_char_p], lambda _, handle, pipe, version: apps if version == b'STEAMAPPS_INTERFACE_VERSION008' else 0), + ]) + library = Mock() + library.CreateInterface.return_value = client + with patch.object(imports.C, 'CDLL', return_value=library): + result = imports.probe('/Steam', [42, 43]) + self.assertEqual('123', result['account']) + self.assertEqual({'42': True, '43': False}, result['owned']) + self.assertEqual([('user', 7, 9), ('pipe', 7)], calls) + library.CreateInterface.assert_called_once_with(b'SteamClient020', None) + + +if __name__ == '__main__': + unittest.main()