diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2804be1ec1..c2d4795375 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,30 +1,14 @@ name: Build APK - -# One job: the two glibc preload libraries the session needs, then the app around them. -# Nothing is built on a developer machine - this workflow is the only thing that produces an apk. -# -# This repo is private, so every minute here is billed. Three caches carry the cost of a rebuild -# down to what actually changed: -# • Gradle's own (dependencies, wrapper, build cache, configuration cache) via setup-gradle -# • the CMake/ninja tree, so a Kotlin-only change does not recompile the compositor -# • the two cross-compiled preloads, which also skips installing the cross toolchain -# A run that changes only Kotlin should not touch the C compiler at all. +run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1}', github.event.pull_request.number, github.event.pull_request.head.sha) || format('building {0} on {1}', github.ref_name, github.sha) }} on: push: branches: [ main ] - # Documentation changes cannot alter the apk, so they do not buy a build. paths-ignore: - '**/*.md' - 'LICENSE' - '.gitignore' - # A pull request against main builds by itself: the contributor's branch, as it would be once - # merged onto main, comes back as an apk on the run without anyone here pressing a button. - # Every push to the pull request rebuilds it and cancels the build it replaces; a draft waits - # until it is marked ready. pull_request_target rather than pull_request: GitHub does not run - # the latter at all while a pull request conflicts with main, and saying what conflicts is the - # point. The workflow file is always main's; the pull request's own code is checked out below. - pull_request_target: + pull_request: branches: [ main ] types: [ opened, synchronize, reopened, ready_for_review ] paths-ignore: @@ -35,38 +19,38 @@ on: permissions: contents: read - # The pull-request report below is one comment on the pull request, kept up to date. pull-requests: write -# A newer push makes the running build pointless; stop paying for it. concurrency: group: build-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true env: - # Bump to force the preload cache to miss (e.g. after changing a compiler flag below). PRELOAD_CACHE_VERSION: v1 jobs: build: - if: ${{ github.event_name != 'pull_request_target' || !github.event.pull_request.draft }} + name: Build APK + if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ubuntu-24.04 timeout-minutes: 45 steps: - # A pull request is checked out at its own head with full history, not at GitHub's merge - # ref: that ref does not exist while the pull request conflicts with main, and the point of - # the next step is to say so and show where. - uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || github.sha }} - # Full history: the merge below needs it (a shallow clone refuses to merge at all). + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} fetch-depth: 0 - # The pull request as it would be once merged onto main is what gets built. When it cannot - # be merged, the conflicting files and the conflicting hunks go into the run summary and the - # pull-request comment, and the job stops here: there is nothing coherent to build. + - name: No private key in the tree + run: | + set -euo pipefail + keys=$(git ls-files | grep -iE '\.(jks|keystore|p12|pfx|pk8|pem|key)$' | grep -vx 'keystore/testkey.p12' || true) + if [ -n "$keys" ]; then + echo "::error::a private key is committed - remove it from the history and make a new one: $keys" + exit 1 + fi + - name: Merge onto main, or say what conflicts - if: github.event_name == 'pull_request_target' + if: github.event_name == 'pull_request' run: | set -uo pipefail git config user.name "ci" @@ -85,7 +69,6 @@ jobs: fi FILES=$(git diff --name-only --diff-filter=U) if [ -z "$FILES" ]; then - # The merge did not even start (git said why): quote it rather than list nothing. { echo "### ERROR: Could not merge onto main (\`$BASE\`)" echo @@ -127,8 +110,6 @@ jobs: distribution: temurin java-version: '17' - # Caches ~/.gradle (dependencies, wrapper distribution, build cache, configuration cache) - # and prunes what the run did not use, so the entry cannot grow without bound. - uses: gradle/actions/setup-gradle@v4 with: cache-cleanup: on-success @@ -137,14 +118,30 @@ jobs: run: | NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}" VERSION=$(sed -n 's/^Pkg.Revision *= *//p' "$NDK/source.properties") - echo "NDK $VERSION at $NDK" echo "NDK_VERSION=$VERSION" >> "$GITHUB_ENV" - # ── The session's preloads ─────────────────────────────────────────────────────────── - # Both are glibc aarch64 libraries that live inside the rootfs, so they are cross-compiled - # here rather than by the NDK. They ship in assets (not in the runtime tarball) so a fix in - # either reaches an already-installed runtime on the next launch instead of waiting on a - # ~790 MB runtime re-host. Their inputs change rarely, so most runs restore them. + - name: Set the APK build label + id: build-label + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + BUILD_REF: ${{ github.ref_name }} + BUILD_SHA: ${{ github.sha }} + run: | + if [[ -n "$(git status --porcelain)" ]]; then + tree_state=dirty + else + tree_state=clean + fi + echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV" + if [[ -n "$PR_NUMBER" ]]; then + label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}" + else + label="${BUILD_REF} at ${BUILD_SHA:0:7}" + fi + echo "label=$label" >> "$GITHUB_OUTPUT" + echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" + - name: Cache the preloads id: preloads uses: actions/cache@v4 @@ -162,9 +159,6 @@ jobs: sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu >/dev/null D=app/src/main/assets/linuxfs mkdir -p "$D" - # Statically linked C++ runtime: this is preloaded into every Steam process, and Steam - # ships its own libstdc++ while rewriting LD_LIBRARY_PATH. Pulling the system one in - # ahead of it is a version conflict waiting to happen. Only libc is left as a dependency. aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ -pthread -std=c++17 -static-libstdc++ -static-libgcc \ -o "$D/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl @@ -172,26 +166,20 @@ jobs: aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ -o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so" - # The session's scripts travel the same way, for the same reason. for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")" done - # The SteamOS helpers the client calls in Deck mode, as no-op stubs (see each file). for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do [ -f "$f" ] && install -Dm644 "$f" "$D/${f#tools/linuxfs/overlay/}" done - # The patched gamescope, when a build of it has been published (tools/gamescope/release.env - # names the release and the archive's sha256); see tools/gamescope/PATCHES.md. if [ -f tools/gamescope/release.env ]; then . tools/gamescope/release.env - # Through the API: the repository is private, so the plain download URL answers 404. gh release download "${GAMESCOPE_TAG}" -R "${GITHUB_REPOSITORY}" -p gamescope.tzst -O gamescope.tzst echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c - tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D" test -f "$D/usr/local/bin/gamescope" rm gamescope.tzst fi - # The patched wlroots for the desktop's GPU renderers (tools/wlroots), the same way. if [ -f tools/wlroots/release.env ]; then . tools/wlroots/release.env gh release download "${WLROOTS_TAG}" -R "${GITHUB_REPOSITORY}" -p wlroots.tzst -O wlroots.tzst @@ -200,9 +188,6 @@ jobs: test -f "$D/usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so" rm wlroots.tzst fi - # Valve's aarch64 mangoapp for Deck mode's performance overlay, plus the five libraries the - # runtime lacks, pinned by sha256 in tools/mangoapp/packages.txt. Stored under the SONAME - # each is loaded by, as real files: assets cannot carry symlinks. M="$D/usr/local/lib/mangoapp" mkdir -p "$M" mango-pkgs grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do @@ -219,7 +204,6 @@ jobs: install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp" rm -rf mango-pkgs ls -l "$M" - # And the desktop's launcher and labwc defaults, staged over the desktop package's copies. install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop" install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu" install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu" @@ -229,10 +213,6 @@ jobs: install -Dm644 tools/linuxfs/desktop/firefox-droiddeck.js "$D/usr/lib/firefox/defaults/pref/droiddeck.js" ls -lR "$D" - # The daemon's AAudio sink (tools/aaudio-sink), compiled here against upstream PulseAudio 13 - # headers and the app's own libpulse*, then put into the audio bundle the apk carries. The - # committed bundle holds every other module and no sink, so a build without this step would - # have no audio - the unpack check in PulseAudioComponent would then fail loudly, not quietly. - name: Cache PulseAudio 13.0 source id: pa-src uses: actions/cache@v4 @@ -275,21 +255,17 @@ jobs: export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}" tools/proot/build.sh app/src/main/jniLibs/arm64-v8a - # Runs whether the preloads were built or restored: readelf reads any ELF whatever the host, - # so these assertions cost nothing and need no cross toolchain. - name: Check the preloads run: | set -euo pipefail D=app/src/main/assets/linuxfs NEED=$(readelf -d "$D/libfakeinput.so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p') - echo "libfakeinput NEEDED: $NEED" for bad in libstdc++.so.6 libgcc_s.so.1; do if printf '%s\n' "$NEED" | grep -qx "$bad"; then echo "::error::libfakeinput.so links $bad - the C++ runtime must stay static"; exit 1 fi done syms() { readelf -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; } - # The interposers are the whole point: if one is missing the client sees no controller. FAKE=$(syms "$D/libfakeinput.so") for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; } @@ -300,12 +276,7 @@ jobs: done test -f "$D/usr/local/bin/bannerlator-session" test -f "$D/usr/local/bin/bannerlator-proton-extra" - echo "preloads check out" - # ── The native build ───────────────────────────────────────────────────────────────── - # The compositor and adrenotools are the slowest part of a build and change least often. - # The key pins the C sources and the NDK; the restore-key still hands an older tree to - # ninja, which then rebuilds only the files that differ. - name: Cache the CMake build tree uses: actions/cache@v4 with: @@ -316,27 +287,14 @@ jobs: restore-keys: | cxx-${{ env.NDK_VERSION }}- - # Release, not debug: AGP quietly drops v1 (JAR) signing from a debug build once minSdk is - # 24 or higher, and the apk has to carry all three schemes. Nothing is minified either way. - # The whole log is kept so a failed build's errors can be quoted back on a pull request. - name: Build id: build + env: + DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} run: | set -o pipefail ./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log - - name: Describe the apk - run: | - set -euo pipefail - APK=$(find app/build/outputs/apk -name '*.apk' | head -1) - echo "apk: $APK" - ls -l "$APK" - sha256sum "$APK" - unzip -l "$APK" | grep -E 'lib/arm64-v8a|assets/linuxfs' | awk 'NR <= 30' # awk reads to the end: head would break the pipe under pipefail - - # Every NEEDED of every library we ship must resolve inside the apk or on the device. The - # first build shipped libwayland-server.so without libffi.so, and the app died on - # System.loadLibrary the moment a session started - a check this step would have caught. - name: Check the native dependency closure run: | set -euo pipefail @@ -344,8 +302,6 @@ jobs: WORK=$(mktemp -d) unzip -q "$APK" 'lib/arm64-v8a/*' -d "$WORK" cd "$WORK/lib/arm64-v8a" - # Provided by the platform, so never packaged. libstdc++.so is Android's minimal system - # C++ runtime; the Termux PTY JNI library has this in its NEEDED list. SYSTEM="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so libstdc++.so libGLESv2.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so libOpenSLES.so libmediandk.so libcamera2ndk.so libsync.so libneuralnetworks.so" @@ -353,19 +309,13 @@ jobs: for so in *.so; do for need in $(readelf -d "$so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p'); do [ -f "$need" ] && continue - # $SYSTEM spans lines; unquoted echo folds its newlines to spaces, or the last - # name on each line could never match (libaaudio.so did not, for the relay helper). case " $(echo $SYSTEM) " in *" $need "*) continue ;; esac echo "::error::$so needs $need, which is neither in the apk nor a platform library" fail=1 done done - [ "$fail" = 0 ] && echo "every NEEDED resolves" exit $fail - # AGP signs with v2+v3 and drops v1 whenever minSdk is 24 or higher, and setting - # enableV1Signing in the DSL does not move it. Re-signing here with apksigner is the one way - # to be sure of what the apk carries: zipalign first, then all three schemes explicitly. - name: Sign with the testkey (v1 + v2 + v3) run: | set -euo pipefail @@ -379,18 +329,12 @@ jobs: --out "$APK" "$APK.aligned" rm -f "$APK.aligned" "$APK.idsig" - # The apk must stay installable over the last one, and on every Android version: that means - # one stable key and all three signature schemes. Cheap to assert, easy to lose silently. - name: Check the signature run: | set -euo pipefail APK=$(find app/build/outputs/apk -name '*.apk' | head -1) APKSIGNER=$(find "$ANDROID_HOME/build-tools" -name apksigner | sort -V | tail -1) - # --min-sdk-version 21: apksigner only verifies the schemes an apk's own minSdk requires, - # so at minSdk 26 it reports v1 as false whether or not the JAR signature is there. - # Asking it to verify from 21 makes it actually look. "$APKSIGNER" verify --min-sdk-version 21 --verbose --print-certs "$APK" | tee /tmp/sig.txt - # And the files themselves, which is what an old installer reads. unzip -l "$APK" | grep -qE 'META-INF/.*\.(SF|RSA|DSA)$' \ || { echo "::error::apk carries no JAR signature files"; exit 1; } for scheme in "v1 scheme (JAR signing): true" "v2 scheme (APK Signature Scheme v2): true" \ @@ -400,12 +344,8 @@ jobs: grep -qi "CN=Android, OU=Android, O=Android" /tmp/sig.txt \ || { echo "::error::apk is not signed with the AOSP testkey"; exit 1; } - # ── The pull-request report ────────────────────────────────────────────────────────── - # One comment per pull request, rewritten on every push: whether it merges, and when the - # build failed, the compiler's own errors with paths made short. Fork pull requests carry a - # read-only token and cannot comment; the same text is in the run summary either way. - name: Report on the pull request - if: always() && github.event_name == 'pull_request_target' + if: always() && github.event_name == 'pull_request' continue-on-error: true env: GH_TOKEN: ${{ github.token }} @@ -425,7 +365,7 @@ jobs: success) echo "### Build passed" echo - echo "The apk is the \`droiddeck-apk\` artifact on [this run]($RUN_URL) (signed with the same test key as every build, so it installs over any other)." + echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key. After approval, a maintainer can run **PR Release Publish** from \`main\` to create an APK that installs over the release." ;; failure) echo "### ERROR: Build failed" @@ -452,7 +392,6 @@ jobs: ;; esac echo - echo "_Updated on every push to this pull request._" } > /tmp/pr-report.md cat /tmp/pr-report.md >> "$GITHUB_STEP_SUMMARY" ID=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR}/comments" --paginate --jq ".[] | select(.body | startswith(\"$MARK\")) | .id" | head -1 || true) @@ -468,5 +407,16 @@ jobs: path: app/build/outputs/apk/release/*.apk if-no-files-found: error retention-days: 30 - # An apk is a zip already; compressing it again buys nothing and costs seconds. compression-level: 0 + + sign: + needs: build + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + permissions: + contents: read + actions: read + uses: ./.github/workflows/sign.yml + with: + environment: signing-main + variants: '["standard"]' + secrets: inherit diff --git a/.github/workflows/pr-release-publish.yml b/.github/workflows/pr-release-publish.yml new file mode 100644 index 0000000000..72ef506be7 --- /dev/null +++ b/.github/workflows/pr-release-publish.yml @@ -0,0 +1,150 @@ +name: PR Release Publish +run-name: sign PR #${{ inputs.pr_number }} with the release key + +on: + workflow_dispatch: + inputs: + pr_number: + description: Open, approved pull request + required: true + type: number + +permissions: + actions: read + contents: read + pull-requests: read + +concurrency: + group: pr-release-${{ inputs.pr_number }} + cancel-in-progress: false + +jobs: + authorize: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + outputs: + run_id: ${{ steps.gate.outputs.run_id }} + head_sha: ${{ steps.gate.outputs.head_sha }} + label: ${{ steps.gate.outputs.label }} + steps: + - name: Check the PR, review, and build + id: gate + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr_number }} + run: | + set -euo pipefail + pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") + jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null + head=$(jq -r '.head.sha' <<<"$pr") + base=$(jq -r '.base.sha' <<<"$pr") + + run_id=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \ + --event pull_request --commit "$head" \ + --json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 | + jq -r --arg head "$head" '[.[] | select(.headSha == $head)] | + sort_by([.createdAt, .attempt]) | last | + select(.status == "completed" and .conclusion == "success") | .databaseId // empty') + [[ -n "$run_id" ]] || { echo '::error::The latest PR build is not green'; exit 1; } + run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id") + jq -e --arg head "$head" --arg base "$base" --argjson number "$PR_NUMBER" ' + .event == "pull_request" and .head_sha == $head and .conclusion == "success" and + 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) + mkdir -p "$RUNNER_TEMP/stable" "$RUNNER_TEMP/pr" + gh release download "$stable_tag" -R The412Banner/DroidDeck \ + -p "DroidDeck-$stable_tag.apk" -D "$RUNNER_TEMP/stable" + gh run download "$run_id" -R "$GITHUB_REPOSITORY" -n droiddeck-apk -D "$RUNNER_TEMP/pr" + mapfile -t apks < <(find "$RUNNER_TEMP/pr" -type f -name '*.apk') + [[ ${#apks[@]} == 1 ]] || { echo '::error::Expected one PR APK'; exit 1; } + package_line() { + "$tools/aapt" dump badging "$1" | sed -n "s/^package: name='\\([^']*\\)' versionCode='\\([^']*\\)'.*/\\1 \\2/p" + } + stable=$(package_line "$RUNNER_TEMP/stable/DroidDeck-$stable_tag.apk") + candidate=$(package_line "${apks[0]}") + [[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" == "$stable" ]] || { + echo "::error::PR package/versionCode '$candidate' differs from stable '$stable'"; exit 1; + } + + current=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") + jq -e --arg head "$head" --arg base "$base" ' + .state == "open" and .draft == false and .base.ref == "main" and + .head.sha == $head and .base.sha == $base + ' <<<"$current" >/dev/null + [[ $(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" + echo "label=PR.$PR_NUMBER-${head:0:7}" + } >> "$GITHUB_OUTPUT" + + sign: + needs: authorize + uses: ./.github/workflows/sign.yml + with: + environment: signing-main + variants: '["standard"]' + run_id: ${{ needs.authorize.outputs.run_id }} + label: ${{ needs.authorize.outputs.label }} + artifact: droiddeck-pr-signed + secrets: inherit + + publish: + needs: [authorize, sign] + runs-on: ubuntu-24.04 + permissions: + actions: read + contents: read + steps: + - uses: actions/download-artifact@v4 + with: + name: droiddeck-pr-signed-standard + path: signed + - name: Publish to DroidDeck-CI when configured + env: + GH_TOKEN: ${{ secrets.DROIDDECK_CI_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 + 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 + Commit: $HEAD_SHA + APK SHA-256: $sha" + if ! gh release view "$tag" -R "$repo" >/dev/null 2>&1; then + gh release create "$tag" -R "$repo" --target main --title "PR #$PR_NUMBER" --notes "$notes" --prerelease + fi + gh release upload "$tag" "signed/$apk" -R "$repo" --clobber + gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease + gh api "repos/$repo/releases/tags/$tag" | + jq -r --arg keep "$apk" '.assets[] | select(.name | endswith(".apk")) | select(.name != $keep) | .id' | + while IFS= read -r id; do + gh api --method DELETE "repos/$repo/releases/assets/$id" >/dev/null + done diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000000..2620b96dfa --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,60 @@ +name: Release APKs +run-name: release ${{ inputs.version }} from main ${{ github.sha }} + +on: + workflow_dispatch: + inputs: + version: + description: Version for the file names, e.g. 0.1.7 + required: true + +permissions: + contents: read + actions: read + +concurrency: + group: release + cancel-in-progress: false + +jobs: + find: + name: find the main build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + outputs: + run_id: ${{ steps.find.outputs.run_id }} + variants: ${{ steps.find.outputs.variants }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - id: find + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + [[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || { echo "::error::version '$VERSION': letters, digits, . _ - only"; exit 1; } + runs=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml --branch main --commit "$GITHUB_SHA" \ + --status success --json databaseId,event,headSha -L 20) + id=$(jq -r --arg sha "$GITHUB_SHA" \ + '[.[] | select(.headSha == $sha and (.event == "push" or .event == "workflow_dispatch"))][0].databaseId // empty' <<<"$runs") + if [ -z "$id" ]; then + echo "::error::main ${GITHUB_SHA::7} has no successful Build APK run yet: wait for it, then release" + exit 1 + fi + variants=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .) + echo "run_id=$id" >> "$GITHUB_OUTPUT" + echo "variants=$variants" >> "$GITHUB_OUTPUT" + echo "Signing Build APK run $id (main ${GITHUB_SHA::7}) as $VERSION: $variants" >> "$GITHUB_STEP_SUMMARY" + + sign: + needs: find + uses: ./.github/workflows/sign.yml + with: + environment: release + variants: ${{ needs.find.outputs.variants }} + run_id: ${{ needs.find.outputs.run_id }} + label: ${{ inputs.version }} + artifact: droiddeck-release + secrets: inherit diff --git a/.github/workflows/sign.yml b/.github/workflows/sign.yml new file mode 100644 index 0000000000..cad16ca037 --- /dev/null +++ b/.github/workflows/sign.yml @@ -0,0 +1,95 @@ +name: Sign APKs + +on: + workflow_call: + inputs: + environment: + type: string + required: true + variants: + description: JSON array of names from tools/release/variants.txt + type: string + required: true + run_id: + description: The Build APK run whose apk to sign; empty for the calling run's own + type: string + default: '' + label: + description: Goes in the file names (a version); empty for - + type: string + default: '' + artifact: + type: string + default: droiddeck-signed + +permissions: + contents: read + actions: read + +jobs: + sign: + name: sign ${{ matrix.variant }} + runs-on: ubuntu-24.04 + timeout-minutes: 15 + environment: ${{ inputs.environment }} + strategy: + fail-fast: false + matrix: + variant: ${{ fromJSON(inputs.variants) }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: The apk (this run's build) + if: inputs.run_id == '' + uses: actions/download-artifact@v4 + with: + name: droiddeck-apk + path: in + + - name: The apk (a main build) + if: inputs.run_id != '' + env: + GH_TOKEN: ${{ github.token }} + RUN: ${{ inputs.run_id }} + run: gh run download "$RUN" -R "$GITHUB_REPOSITORY" -n droiddeck-apk -D in + + - name: Sign + env: + RELEASE_KEYSTORE_B64: ${{ secrets.RELEASE_KEYSTORE_B64 }} + RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} + RELEASE_KEY_ALIAS: droiddeck + ENVIRONMENT: ${{ inputs.environment }} + VARIANT: ${{ matrix.variant }} + LABEL: ${{ inputs.label }} + run: | + set -euo pipefail + if [ -z "$RELEASE_KEYSTORE_B64" ]; then + echo "::error::environment '$ENVIRONMENT' has no signing key: run tools/release/make-release-key.sh once" + exit 1 + fi + export RELEASE_KEYSTORE="$RUNNER_TEMP/release.p12" + ( umask 077; base64 -d <<<"$RELEASE_KEYSTORE_B64" > "$RELEASE_KEYSTORE" ) + BUILD_TOOLS=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -n1) + export BUILD_TOOLS + [ -n "$LABEL" ] || LABEL="${GITHUB_REF_NAME//\//-}-${GITHUB_SHA::7}" + suffix=$(awk -v v="$VARIANT" '!/^#/ && $1 == v { print $3 }' tools/release/variants.txt) + [ "$suffix" = - ] && suffix= + apks=(in/*.apk) + [ ${#apks[@]} = 1 ] && [ -f "${apks[0]}" ] || { echo "::error::expected one apk in the build"; exit 1; } + mkdir -p out + out="out/DroidDeck-$LABEL$suffix.apk" + tools/release/sign-apk.sh "${apks[0]}" "$VARIANT" "$out" + ( cd out && sha256sum -- *.apk > "SHA256SUMS-$VARIANT.txt" && cat "SHA256SUMS-$VARIANT.txt" ) + echo "- \`$(basename "$out")\` - $(cut -c1-16 "out/SHA256SUMS-$VARIANT.txt")…" >> "$GITHUB_STEP_SUMMARY" + + - name: Forget the key + if: always() + run: rm -f "$RUNNER_TEMP/release.p12" + + - uses: actions/upload-artifact@v4 + with: + name: ${{ inputs.artifact }}-${{ matrix.variant }} + path: out/* + if-no-files-found: error diff --git a/.gitignore b/.gitignore index c1cf2c5f96..244bb5f33d 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,15 @@ app/src/main/jniLibs/arm64-v8a/libproot-loader.so # Kotlin compiler session files (build-tool state, never source). .kotlin/ + +# Signing keys never enter the repo (DroidDeck's lives in GitHub environment secrets; see +# tools/release/make-release-key.sh). keystore/testkey.p12 is the public AOSP testkey. +*.jks +*.keystore +*.p12 +*.pfx +*.pk8 +*.pem +!keystore/testkey.p12 +droiddeck-release-key/ +password.txt diff --git a/app/build.gradle b/app/build.gradle index 413b4e2238..dcc9db8519 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -4,6 +4,51 @@ plugins { apply plugin: 'kotlin-android' apply plugin: 'org.jetbrains.kotlin.plugin.compose' +def gitValue = { List arguments -> + try { + def output = providers.exec { + commandLine(['git'] + arguments) + workingDir rootProject.projectDir + ignoreExitValue = true + } + output.result.get().exitValue == 0 ? output.standardOutput.asText.get().trim() : null + } catch (Exception ignored) { + null + } +} + +def buildLabel = providers.environmentVariable('DROIDDECK_BUILD_LABEL').getOrNull() +if (buildLabel == null || buildLabel.trim().isEmpty()) { + def eventName = providers.environmentVariable('GITHUB_EVENT_NAME').getOrNull() + def eventPath = providers.environmentVariable('GITHUB_EVENT_PATH').getOrNull() + if (eventName == 'pull_request_target' && eventPath) { + try { + def eventFile = layout.file(providers.provider { new File(eventPath) }) + def eventText = providers.fileContents(eventFile).asText.get() + def pullRequest = new groovy.json.JsonSlurper().parseText(eventText).pull_request + if (pullRequest?.number && pullRequest?.head?.sha) { + buildLabel = "pr${pullRequest.number} at ${pullRequest.head.sha.take(7)}" + } + } catch (Exception ignored) { + } + } + if (buildLabel == null || buildLabel.trim().isEmpty()) { + def branch = providers.environmentVariable('GITHUB_REF_NAME').getOrNull() + ?: gitValue(['branch', '--show-current']) ?: 'local' + def commit = providers.environmentVariable('GITHUB_SHA').getOrNull() + ?.take(7) ?: gitValue(['rev-parse', '--short=7', 'HEAD']) ?: 'unknown' + buildLabel = "${branch} at ${commit}" + } +} +def buildOrigin = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true' ? 'remote' : 'local' +def treeState = providers.environmentVariable('DROIDDECK_BUILD_TREE_STATE').getOrNull() +if (!(treeState in ['clean', 'dirty'])) { + def status = gitValue(['status', '--porcelain']) + treeState = status == null ? 'unknown' : (status.isEmpty() ? 'clean' : 'dirty') +} +buildLabel = "${buildOrigin} ${treeState} · ${buildLabel}" +def escapedBuildLabel = buildLabel.replace('\\', '\\\\').replace('"', '\\"') + android { namespace 'com.droiddeck.launcher' compileSdk 34 @@ -18,8 +63,9 @@ android { // file out of its own data directory, and this app's entire job is to exec a rootfs: // proot, gamescope, the Steam client and everything it launches all live under files/. targetSdkVersion 28 - versionCode 7 - versionName "0.1.6" + versionCode 8 + versionName "0.1.7" + buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\"" ndk { abiFilters 'arm64-v8a' @@ -87,6 +133,7 @@ android { buildFeatures { compose true + buildConfig true } compileOptions { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 362a87d12d..0fe0362886 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -55,9 +55,12 @@ + Home launch either back into a running Steam session or to the regular front end. + Off until the user turns on "Use as a Home screen" (Setup): while it is disabled the + app is not a Home app at all - not offered, not in the "choose Home" list. --> + + + + + + diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 55fb521586..5b7642bb7d 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -465,17 +465,23 @@ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_ /* Each Wine process is a separate client with its own wl_pointer / wl_keyboard. */ struct seat_pointer { struct wl_resource *ptr; struct wl_resource *focus; }; struct seat_keyboard { struct wl_resource *kb; struct wl_resource *focus; }; +struct seat_touch { struct wl_resource *touch; struct wl_resource *focus; }; #define MAX_PTRS 32 +#define MAX_TOUCH_POINTS 32 static struct seat_pointer g_ptrs[MAX_PTRS]; static int g_nptrs; static struct seat_keyboard g_kbs[MAX_PTRS]; static int g_nkbs; +static struct seat_touch g_touches[MAX_PTRS]; +static int g_ntouches; +struct active_touch { struct surface *surface; int pointer_fallback; }; +static struct active_touch g_touch_points[MAX_TOUCH_POINTS]; +static void touch_cancel_surface(struct surface *surface); static struct surface *g_grab; /* no-desktop fallback: surface holding the button */ static struct surface *g_key_target; /* no-desktop fallback: last clicked surface */ static struct surface *g_ime_click; /* last clicked program window: where text input goes */ static int g_input_pipe[2] = {-1, -1}; -/* type 0 = pointer (p1=action 0down/1move/2up, p2=x, p3=y); type 1 = key (p1=evdev, p2=state 1down/0up) */ -struct input_msg { int type; int p1; int p2; int p3; }; +struct input_msg { int type; int p1; int p2; int p3; int p4; }; /* Pointer constraints (zwp_pointer_constraints_v1) and relative pointers * (zwp_relative_pointer_manager_v1); see the "pointer constraints" section. */ @@ -1002,6 +1008,7 @@ static void surface_resource_destroy(struct wl_resource *r) { if (!s) return; for (int i = 0; i < g_nptrs; i++) if (g_ptrs[i].focus == r) g_ptrs[i].focus = NULL; 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_grab == s) g_grab = NULL; if (g_key_target == s) g_key_target = NULL; if (g_ime_click == s) g_ime_click = NULL; @@ -2401,6 +2408,10 @@ static void keyboard_res_destroy(struct wl_resource *r) { } static void touch_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static const struct wl_touch_interface touch_impl = { .release = touch_release }; +static void touch_res_destroy(struct wl_resource *r) { + for (int i = 0; i < g_ntouches; i++) + if (g_touches[i].touch == r) { g_touches[i] = g_touches[--g_ntouches]; break; } +} static void seat_get_pointer(struct wl_client *c, struct wl_resource *r, uint32_t id) { struct wl_resource *p = wl_resource_create(c, &wl_pointer_interface, wl_resource_get_version(r), id); @@ -2432,7 +2443,13 @@ static void seat_get_keyboard(struct wl_client *c, struct wl_resource *r, uint32 } static void seat_get_touch(struct wl_client *c, struct wl_resource *r, uint32_t id) { struct wl_resource *t = wl_resource_create(c, &wl_touch_interface, wl_resource_get_version(r), id); - if (t) wl_resource_set_implementation(t, &touch_impl, NULL, NULL); + if (!t) { wl_client_post_no_memory(c); return; } + wl_resource_set_implementation(t, &touch_impl, NULL, touch_res_destroy); + if (g_ntouches < MAX_PTRS) { + g_touches[g_ntouches].touch = t; + g_touches[g_ntouches].focus = NULL; + g_ntouches++; + } } static void seat_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static const struct wl_seat_interface seat_impl = { @@ -2442,7 +2459,7 @@ static const struct wl_seat_interface seat_impl = { static void bind_seat(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { struct wl_resource *r = wl_resource_create(c, &wl_seat_interface, ver, id); wl_resource_set_implementation(r, &seat_impl, NULL, NULL); - wl_seat_send_capabilities(r, WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD); + wl_seat_send_capabilities(r, WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD | WL_SEAT_CAPABILITY_TOUCH); if (ver >= 2) wl_seat_send_name(r, "bannerlator-seat"); } @@ -2466,6 +2483,9 @@ static struct seat_keyboard *keyboard_for(struct wl_client *client) { #define for_each_keyboard_of(client, sk) \ for (int _i = 0; _i < g_nkbs; _i++) \ if (((sk) = &g_kbs[_i]), wl_resource_get_client((sk)->kb) == (client)) +#define for_each_touch_of(client, st) \ + for (int _i = 0; _i < g_ntouches; _i++) \ + if (((st) = &g_touches[_i]), wl_resource_get_client((st)->touch) == (client)) /* Topmost window whose scene rectangle contains the point (no-desktop fallback). */ static struct surface *toplevel_at(double x, double y) { @@ -3000,6 +3020,179 @@ static void deliver_pointer(const struct input_msg *m) { pointer_event(x, y, m->p1 == 1 ? 0 : BTN_LEFT, m->p1 == 0); } +static void input_output_to_scene(int px, int py, double *x, double *y) { + int w, h, ow, oh; + scene_size(&w, &h); + vkp_output_size(&ow, &oh); + if (ow <= 0 || oh <= 0 || + !vkp_output_to_scene((double)px * ow / INPUT_SPACE_W, (double)py * oh / INPUT_SPACE_H, x, y)) { + *x = (double)px * w / INPUT_SPACE_W; + *y = (double)py * h / INPUT_SPACE_H; + } + if (*x < 0) *x = 0; + if (*y < 0) *y = 0; + if (*x > w - 1) *x = w - 1; + if (*y > h - 1) *y = h - 1; +} + +static int touch_points_for_client(struct wl_client *client) { + for (int i = 0; i < MAX_TOUCH_POINTS; i++) { + struct surface *surface = g_touch_points[i].surface; + if (surface && wl_resource_get_client(surface->resource) == client) return 1; + } + return 0; +} + +static void touch_frame(struct wl_client *client) { + struct seat_touch *st; + for_each_touch_of(client, st) + if (wl_resource_get_version(st->touch) >= WL_TOUCH_FRAME_SINCE_VERSION) + wl_touch_send_frame(st->touch); +} + +static void touch_cancel_client(struct wl_client *client) { + struct seat_touch *st; + int release_pointer = 0; + for_each_touch_of(client, st) { + if (st->focus) wl_touch_send_cancel(st->touch); + st->focus = NULL; + } + for (int i = 0; i < MAX_TOUCH_POINTS; i++) { + struct surface *surface = g_touch_points[i].surface; + if (surface && wl_resource_get_client(surface->resource) == client) { + release_pointer |= g_touch_points[i].pointer_fallback; + memset(&g_touch_points[i], 0, sizeof(g_touch_points[i])); + } + } + if (release_pointer) pointer_button(BTN_LEFT, 0); + wl_display_flush_clients(g_display); +} + +static void touch_cancel_all(void) { + int release_pointer = 0; + for (int i = 0; i < g_ntouches; i++) { + if (g_touches[i].focus) wl_touch_send_cancel(g_touches[i].touch); + g_touches[i].focus = NULL; + } + for (int i = 0; i < MAX_TOUCH_POINTS; i++) + release_pointer |= g_touch_points[i].pointer_fallback; + memset(g_touch_points, 0, sizeof(g_touch_points)); + if (release_pointer) pointer_button(BTN_LEFT, 0); + wl_display_flush_clients(g_display); +} + +static void touch_cancel_surface(struct surface *surface) { + struct wl_client *client = wl_resource_get_client(surface->resource); + for (int i = 0; i < MAX_TOUCH_POINTS; i++) + if (g_touch_points[i].surface == surface) { + touch_cancel_client(client); + return; + } +} + +static struct surface *touch_target_at(double x, double y) { + struct surface *target = toplevel_at(x, y); + if (target) return target; + if (g_desktop) return g_desktop; + return g_grab ? g_grab : g_key_target; +} + +static void touch_down(int id, double x, double y) { + if (id < 0 || id >= MAX_TOUCH_POINTS) return; + struct surface *target = touch_target_at(x, y); + if (!target) return; + struct wl_client *client = wl_resource_get_client(target->resource); + int any_active = 0; + for (int i = 0; i < MAX_TOUCH_POINTS; i++) { + struct surface *active = g_touch_points[i].surface; + if (!active) continue; + any_active = 1; + if (active != target) { + touch_cancel_all(); + any_active = 0; + break; + } + } + if (g_touch_points[id].surface) touch_cancel_client(client); + struct seat_touch *st; + int has_touch = 0; + for_each_touch_of(client, st) has_touch = 1; + if (!has_touch) { + if (any_active) return; + g_touch_points[id].surface = target; + g_touch_points[id].pointer_fallback = 1; + pointer_event(x, y, BTN_LEFT, 1); + wl_display_flush_clients(g_display); + return; + } + int tx = 0, ty = 0; + if (target != g_desktop && target->placed) { tx = target->x; ty = target->y; } + wl_fixed_t fx = wl_fixed_from_double(x - tx), fy = wl_fixed_from_double(y - ty); + int sent = 0; + for_each_touch_of(client, st) { + st->focus = target->resource; + wl_touch_send_down(st->touch, wl_display_next_serial(g_display), now_ms(), + target->resource, id, fx, fy); + sent = 1; + } + if (!sent) return; + g_touch_points[id].surface = target; + touch_frame(client); + wl_display_flush_clients(g_display); +} + +static void touch_motion(int id, double x, double y) { + if (id < 0 || id >= MAX_TOUCH_POINTS) return; + struct surface *target = g_touch_points[id].surface; + if (!target) return; + if (g_touch_points[id].pointer_fallback) { + pointer_event(x, y, 0, 0); + wl_display_flush_clients(g_display); + return; + } + struct wl_client *client = wl_resource_get_client(target->resource); + int tx = 0, ty = 0; + if (target != g_desktop && target->placed) { tx = target->x; ty = target->y; } + wl_fixed_t fx = wl_fixed_from_double(x - tx), fy = wl_fixed_from_double(y - ty); + struct seat_touch *st; + for_each_touch_of(client, st) + if (st->focus == target->resource) + wl_touch_send_motion(st->touch, now_ms(), id, fx, fy); + touch_frame(client); + wl_display_flush_clients(g_display); +} + +static void touch_up(int id, double x, double y) { + if (id < 0 || id >= MAX_TOUCH_POINTS) return; + struct surface *target = g_touch_points[id].surface; + if (!target) return; + if (g_touch_points[id].pointer_fallback) { + memset(&g_touch_points[id], 0, sizeof(g_touch_points[id])); + pointer_event(x, y, BTN_LEFT, 0); + wl_display_flush_clients(g_display); + return; + } + struct wl_client *client = wl_resource_get_client(target->resource); + struct seat_touch *st; + for_each_touch_of(client, st) + if (st->focus == target->resource) + wl_touch_send_up(st->touch, wl_display_next_serial(g_display), now_ms(), id); + memset(&g_touch_points[id], 0, sizeof(g_touch_points[id])); + touch_frame(client); + if (!touch_points_for_client(client)) + for_each_touch_of(client, st) st->focus = NULL; + wl_display_flush_clients(g_display); +} + +static void deliver_touch(const struct input_msg *m) { + double x, y; + input_output_to_scene(m->p3, m->p4, &x, &y); + if (m->p1 == 0) touch_down(m->p2, x, y); + else if (m->p1 == 1) touch_motion(m->p2, x, y); + else if (m->p1 == 2) touch_up(m->p2, x, y); + else if (m->p1 == 3) touch_cancel_all(); +} + static void key_event(uint32_t evdev, int pressed); struct wl_resource *banner_ime_target(void); static void deliver_key(const struct input_msg *m) { @@ -3068,6 +3261,7 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { case 4: scroll_event(m.p1); break; case 5: on_vsync(((int64_t)m.p1 << 32) | (uint32_t)m.p2); break; case 6: pointer_delta(m.p1 / 256.0, m.p2 / 256.0); break; /* relative motion, 1/256 px */ + case 7: deliver_touch(&m); break; default: deliver_pointer(&m); break; } } @@ -3078,7 +3272,14 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { * dispatches it. x/y are in INPUT_SPACE (0..1919, 0..1079) over the whole output. */ void banner_wayland_send_pointer(int action, int x, int y) { if (g_input_pipe[1] < 0) return; - struct input_msg m = { 0, action, x, y }; + struct input_msg m = { 0, action, x, y, 0 }; + ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); + (void)n; +} + +void banner_wayland_send_touch(int action, int pointer_id, int x, int y) { + if (g_input_pipe[1] < 0) return; + struct input_msg m = { 7, action, pointer_id, x, y }; ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); (void)n; } @@ -3086,7 +3287,7 @@ void banner_wayland_send_pointer(int action, int x, int y) { /* Called from JNI. Queues a key event. evdev = Linux input keycode (e.g. KEY_A=30); state 1=down 0=up. */ void banner_wayland_send_key(int evdev, int state) { if (g_input_pipe[1] < 0) return; - struct input_msg m = { 1, evdev, state, 0 }; + struct input_msg m = { 1, evdev, state, 0, 0 }; ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); (void)n; } @@ -3094,7 +3295,7 @@ void banner_wayland_send_key(int evdev, int state) { /* Called from JNI on every screen refresh (Choreographer). */ void banner_wayland_vsync(int64_t frame_time_ns) { if (g_input_pipe[1] < 0) return; - struct input_msg m = { 5, (int)(frame_time_ns >> 32), (int)(uint32_t)frame_time_ns, 0 }; + struct input_msg m = { 5, (int)(frame_time_ns >> 32), (int)(uint32_t)frame_time_ns, 0, 0 }; ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); (void)n; } @@ -3104,7 +3305,7 @@ void banner_wayland_vsync(int64_t frame_time_ns) { * 6 = relative motion by a,b in 1/256 pixel (the app's Relative Mouse / captured-mouse path). */ void banner_wayland_send_scene_input(int type, int a, int b) { if (g_input_pipe[1] < 0) return; - struct input_msg m = { type, a, b, 0 }; + struct input_msg m = { type, a, b, 0, 0 }; ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); (void)n; } diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 9698e1cfd2..2125a5c088 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -23,6 +23,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 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); @@ -271,6 +272,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendPointer( banner_wayland_send_pointer(action, x, y); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendTouch( + JNIEnv *env, jclass clazz, jint action, jint pointer_id, jint x, jint y) { + banner_wayland_send_touch(action, pointer_id, x, y); +} + /* 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( diff --git a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt index 8be97a55ca..f71ca928a8 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher +import android.app.ActivityOptions import android.app.role.RoleManager import android.graphics.Bitmap import android.content.ComponentName @@ -21,6 +22,25 @@ object HomeApp { val icon: Bitmap?, ) + /** + * Whether the app offers itself as a Home app at all. HomeActivity is declared disabled and + * only enabled when the user turns on "Use as a Home screen": a player who does not want a + * launcher never gets Android's "which Home app?" question, and it is one apk either way. + * The setting is the component's own state, which Android keeps across updates. + */ + fun isHomeScreenEnabled(context: Context): Boolean = + context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) == + PackageManager.COMPONENT_ENABLED_STATE_ENABLED + + /** Turned off while DroidDeck is the Home app, the phone goes back to its own launcher. */ + fun setHomeScreenEnabled(context: Context, enabled: Boolean) { + context.packageManager.setComponentEnabledSetting( + ComponentName(context, HomeActivity::class.java), + if (enabled) PackageManager.COMPONENT_ENABLED_STATE_ENABLED else PackageManager.COMPONENT_ENABLED_STATE_DISABLED, + PackageManager.DONT_KILL_APP, + ) + } + fun isDefault(context: Context): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val roles = context.getSystemService(RoleManager::class.java) @@ -73,11 +93,19 @@ object HomeApp { return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) } - fun launch(context: Context, app: LaunchableApp) { + fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) { val intent = Intent(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_LAUNCHER) .setComponent(ComponentName(app.packageName, app.className)) - context.startActivity(intent) + if (displayId == null) { + context.startActivity(intent) + return + } + // Keep the target app's task separate from DroidDeck. Without this, Android can put the + // app on top of the caller's task and move the entire task to the chosen display. + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId) + context.startActivity(intent, options.toBundle()) } fun isActiveSteamSession(): Boolean = diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 092682004f..1d50ac50ad 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -4,12 +4,14 @@ import android.Manifest import android.content.Intent import java.io.File import android.content.pm.PackageManager +import android.hardware.display.DisplayManager import android.net.Uri import android.provider.OpenableColumns import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log +import android.view.Display import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts @@ -47,6 +49,7 @@ import com.droiddeck.launcher.ui.CreditsDialog import com.droiddeck.launcher.ui.FrontEndScreen import com.droiddeck.launcher.ui.FrontEndState import com.droiddeck.launcher.ui.FrontEndActions +import com.droiddeck.launcher.frontend.CoverArt import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.ui.DroidDeckTheme import com.droiddeck.launcher.ui.RomsDialog @@ -54,6 +57,8 @@ import com.droiddeck.launcher.files.InAppFilePicker import com.droiddeck.launcher.session.SessionArtifacts import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.GameStorage +import com.droiddeck.launcher.input.SecondScreenDisplay +import com.droiddeck.launcher.input.SecondScreenDisplays /** * The whole app outside a session: is the runtime installed, is there a newer one, frame @@ -104,6 +109,7 @@ class MainActivity : ComponentActivity() { private var phantomWarning by mutableStateOf(null) private var directAudio by mutableStateOf(false) private var clientDirectAudio by mutableStateOf(false) + private var forceFullscreen by mutableStateOf(true) private var mic by mutableStateOf(false) private var linuxRows by mutableStateOf>(emptyList()) /** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */ @@ -169,6 +175,7 @@ class MainActivity : ComponentActivity() { private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) + private var backActionsInverted by mutableStateOf(false) private var renderer by mutableStateOf("vulkan") private var gameStorage by mutableStateOf("") private var storageOptions by mutableStateOf>>(emptyList()) @@ -182,8 +189,16 @@ class MainActivity : ComponentActivity() { private var logsEnabled by mutableStateOf(true) private var showRoms by mutableStateOf(false) private var homeAppSelected by mutableStateOf(false) + private var homeScreenEnabled by mutableStateOf(false) private var defaultHomeLabel by mutableStateOf(null) private var androidApps by mutableStateOf>(emptyList()) + private var secondScreenDisplays by mutableStateOf>(emptyList()) + private lateinit var displayManager: DisplayManager + private val secondScreenDisplayListener = object : DisplayManager.DisplayListener { + override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays() + override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays() + override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays() + } private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { refreshHomeAppState() @@ -209,7 +224,9 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager theme = SessionPrefs.theme(this) + backActionsInverted = SessionPrefs.backActionsInverted(this) setContent { DroidDeckTheme(theme) { val sm = settingsMode @@ -232,14 +249,18 @@ class MainActivity : ComponentActivity() { pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else null, theme = theme, isHomeApp = homeAppSelected, + homeScreenEnabled = homeScreenEnabled, defaultHomeLabel = defaultHomeLabel, androidApps = androidApps, + secondScreenDisplays = secondScreenDisplays, packages = packageRows, packageCatalogLoading = catalogLoading, packageBusyId = pkgId, packageStage = pkgStage, packagePercent = pkgPercent, sessionRunning = SessionState.running, + backActionsInverted = backActionsInverted, + buildLabel = BuildConfig.BUILD_LABEL, ), FrontEndActions( onPlay = { startSession(Intent(this, SessionActivity::class.java)) }, @@ -299,7 +320,18 @@ class MainActivity : ComponentActivity() { onPageBack = { settingsMode = null; showPerformance = false; showProtons = false }, onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id }, onHomeApp = { manageHomeApp() }, - onAndroidApp = { app -> launchAndroidApp(app) }, + onHomeScreen = { on -> + HomeApp.setHomeScreenEnabled(this, on) + refreshHomeAppState() + }, + onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) }, + onBackActionsInverted = { inverted -> + SessionPrefs.setBackActionsInverted(this, inverted) + backActionsInverted = inverted + }, + onCheckLatestBuild = { + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml"))) + }, ), page = page, ) @@ -354,6 +386,7 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() refreshHomeAppState() + refreshSecondScreenDisplays() refresh() // Added games' art (a store lookup for what the folders lack) starts here, not only when // the cog opens. @@ -362,17 +395,36 @@ class MainActivity : ComponentActivity() { if (!busy) Thread({ checkCatalog() }, "catalog").start() } + override fun onStart() { + super.onStart() + displayManager.registerDisplayListener(secondScreenDisplayListener, ui) + refreshSecondScreenDisplays() + } + + override fun onStop() { + displayManager.unregisterDisplayListener(secondScreenDisplayListener) + super.onStop() + } + private fun refreshHomeAppState() { - homeAppSelected = HomeApp.isDefault(this) + homeScreenEnabled = HomeApp.isHomeScreenEnabled(this) + homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this) defaultHomeLabel = HomeApp.defaultLabel(this) androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList() } - private fun launchAndroidApp(app: HomeApp.LaunchableApp) { + private fun refreshSecondScreenDisplays() { + if (!::displayManager.isInitialized) return + secondScreenDisplays = SecondScreenDisplays.available(displayManager) + } + + private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) { try { - HomeApp.launch(this, app) + HomeApp.launch(this, app, displayId) } catch (_: Exception) { - android.widget.Toast.makeText(this, "Could not open ${app.label}", android.widget.Toast.LENGTH_SHORT).show() + val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen" + else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId" + android.widget.Toast.makeText(this, "Could not open ${app.label} on $target", android.widget.Toast.LENGTH_SHORT).show() } } @@ -515,8 +567,10 @@ class MainActivity : ComponentActivity() { touchMode = touchMode, suspendPolicy = suspendPolicy, oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null, + backActionsInverted = backActionsInverted, directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null, clientDirectAudio = clientDirectAudio, + forceFullscreen = if (mode == SessionService.MODE_STEAM) forceFullscreen else null, mic = if (mode == SessionService.MODE_STEAM) mic else null, renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null, gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null, @@ -546,8 +600,13 @@ class MainActivity : ComponentActivity() { 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 }, + onBackActionsInverted = { inverted -> + SessionPrefs.setBackActionsInverted(this, inverted) + backActionsInverted = inverted + }, onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on }, onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on }, + onForceFullscreen = { on -> SessionPrefs.setForceFullscreen(this, on); forceFullscreen = on }, onMic = { on -> SessionPrefs.setMicEnabled(this, on) mic = on @@ -641,8 +700,10 @@ class MainActivity : ComponentActivity() { touchMode = SessionPrefs.touchMode(this) suspendPolicy = SessionPrefs.suspendPolicy(this, mode) oscMode = SessionPrefs.oscMode(this) + backActionsInverted = SessionPrefs.backActionsInverted(this) directAudio = SessionPrefs.directAudio(this) clientDirectAudio = SessionPrefs.clientDirectAudio(this) + forceFullscreen = SessionPrefs.forceFullscreen(this) mic = SessionPrefs.micEnabled(this) renderer = SessionPrefs.desktopRenderer(this) gameStorage = SessionPrefs.gameStorage(this) @@ -885,6 +946,12 @@ class MainActivity : ComponentActivity() { } else emptyList() val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null } ui.post { steamGames = games; 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 })) { + val refreshed = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null } + ui.post { emulatorList = refreshed } + } }, "library").start() } diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 6c83cddba0..2d0c3c2438 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -8,9 +8,12 @@ import android.os.Bundle import android.os.Environment import android.os.Handler import android.os.Looper +import android.os.SystemClock import android.util.Log +import android.view.InputDevice import android.view.KeyEvent import android.view.MotionEvent +import android.view.ViewConfiguration import android.view.Display import android.view.SurfaceHolder import android.view.SurfaceView @@ -21,6 +24,7 @@ import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.OnBackPressedCallback 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 @@ -35,6 +39,7 @@ import com.droiddeck.launcher.input.OnScreenControls import com.droiddeck.launcher.input.PadBridge import com.droiddeck.launcher.input.PointerGestures import com.droiddeck.launcher.input.SecondScreenDisplay +import com.droiddeck.launcher.input.SecondScreenDisplays import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.input.TouchpadGestures import com.droiddeck.launcher.runtime.LinuxRuntime @@ -58,6 +63,7 @@ import com.droiddeck.launcher.ui.DroidDeckTheme import com.droiddeck.launcher.wayland.CompositorHost import com.droiddeck.launcher.wayland.WaylandCompositor import java.io.File +import kotlin.math.abs /** * The session's screen: our Wayland compositor presenting onto this activity's Surface, and the @@ -72,25 +78,56 @@ import java.io.File */ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var surfaceView: SurfaceView + private lateinit var sessionOverlay: ComposeView private lateinit var loading: LoadingState private lateinit var hud: PerfHud private var padBridge: PadBridge? = null private var onScreenControls: OnScreenControls? = null private var keyboard: KeyboardHost? = null private var watching = true - private lateinit var gestures: PointerGestures private lateinit var touchpad: TouchpadGestures private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f)) private var cursorVisible by mutableStateOf(false) private val cursorHide = Runnable { cursorVisible = false } private val uiHandler = Handler(Looper.getMainLooper()) + private var pendingBackAction: Runnable? = null + private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN + private var drawerDirectionDownTime = 0L + private var drawerDirectionDeviceId = -1 + private var drawerDirectionRepeatCount = 0 + private val drawerFirstRepeatDelayMs = ViewConfiguration.getKeyRepeatTimeout().toLong() + private val drawerSlowRepeatIntervalMs = maxOf( + ViewConfiguration.getKeyRepeatDelay().toLong(), DRAWER_SLOW_REPEAT_FLOOR_MS, + ) + private val drawerDirectionRepeat = object : Runnable { + override fun run() { + if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) return + + val now = SystemClock.uptimeMillis() + val heldMs = now - drawerDirectionDownTime + val progress = ((heldMs - drawerFirstRepeatDelayMs).toFloat() / DRAWER_REPEAT_ACCELERATION_MS) + .coerceIn(0f, 1f) + val intervalMs = ( + drawerSlowRepeatIntervalMs + + (DRAWER_FAST_REPEAT_INTERVAL_MS - drawerSlowRepeatIntervalMs) * progress + ).toLong() + + dispatchDrawerKey(KeyEvent.ACTION_DOWN, ++drawerDirectionRepeatCount, now) + uiHandler.postDelayed(this, intervalMs) + } + } + private val resumeKeysDown = mutableSetOf>() // Compose reads these; the activity writes them. private var drawerOpen by mutableStateOf(false) + private var drawerPage by mutableIntStateOf(0) + private var drawerControllerActive by mutableStateOf(false) + private var backActionsInverted by mutableStateOf(false) /** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */ 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) @@ -147,7 +184,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { padBridge = bridge onScreenControls = OnScreenControls(this, bridge).also { root.addView(it) } keyboard = KeyboardHost(this).also { root.addView(it) } - gestures = PointerGestures(PointerGestures.slop(this), pointerListener) touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener) // One arrow, ours: Android draws a system pointer for a mouse over any window, and the // session already draws the pointer it is sent. @@ -175,14 +211,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // One Compose layer for every menu and overlay. Touches nothing in it consumes fall // through to the pad and the game underneath. - root.addView(ComposeView(this).apply { + sessionOverlay = ComposeView(this).apply { + isFocusable = true + isFocusableInTouchMode = true setContent { DroidDeckTheme { CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density) if (hud.text.isNotEmpty()) HudText(hud.text) if (loading.visible) LoadingOverlay(loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended) // Opening the drawer takes the controller away from the game: release its pad. - androidx.compose.runtime.LaunchedEffect(drawerOpen) { if (drawerOpen) padBridge?.releaseAll() } + androidx.compose.runtime.LaunchedEffect(drawerOpen) { + if (drawerOpen) { + padBridge?.releaseAll() + androidx.compose.runtime.withFrameNanos { } + val requested = sessionOverlay.requestFocus() + Log.i(TAG, "drawer root focus requested=$requested focused=${sessionOverlay.hasFocus()}") + } else { + releaseDrawerDirection() + } + } // The PC keyboard takes it too, for moving over the keys; the drawer opens over it. androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) padBridge?.releaseAll() } if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard( @@ -190,11 +237,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() }, onClose = { pcKeyboardOpen = false }, ) - SessionDrawer(drawerOpen, DrawerActions( + SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions( steam = SessionState.mode == SessionService.MODE_STEAM, + title = if (SessionState.mode == SessionService.MODE_RUN) + com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: "Game" else null, isHomeApp = isHomeApp, androidApps = androidApps, hudOn = hudOn, + fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null, frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier, lsfgReady = LsfgNative.isInstalled(this@SessionActivity), oscMode = oscMode, touchMode = touchMode, @@ -204,6 +254,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { secondScreenDisplays = secondScreenDisplays, 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) readPrefs() @@ -212,22 +263,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() }, onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen }, onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null, - onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ - drawerOpen = false - padBridge?.triggerQam() - }) else null, + onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null, + backActionsInverted = backActionsInverted, + onBackActionsInverted = { inverted -> + SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted) + backActionsInverted = inverted + }, onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, onSecondScreenMode = ::selectSecondScreenMode, onSecondScreenDisplay = ::selectSecondScreenDisplay, - onLaunchAndroidApp = { app -> + onLaunchAndroidApp = { app, displayId -> drawerOpen = false try { - HomeApp.launch(this@SessionActivity, app) + HomeApp.launch(this@SessionActivity, app, displayId) } catch (_: Exception) { - Toast.makeText(this@SessionActivity, "Could not open ${app.label}", Toast.LENGTH_SHORT).show() + val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen" + else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId" + Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show() } }, onBackground = { drawerOpen = false; moveTaskToBack(true) }, @@ -239,7 +294,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } } - }) + } + root.addView(sessionOverlay) setContentView(root) handleHomeGuideIntent(intent) @@ -252,13 +308,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } SessionState.endListener = endListener - // Back opens the drawer (and closes it again). Leaving the session running in the - // background and ending it are both actions in there, so neither can happen by accident - // from a button a game might also be reading. + // A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord. + // The single action waits out the double-press window so the two actions stay distinct. onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { // The PC keyboard closes first (B on a controller), then Back is the drawer again. - if (pcKeyboardOpen && !drawerOpen) pcKeyboardOpen = false else drawerOpen = !drawerOpen + when { + drawerOpen -> drawerOpen = false + pcKeyboardOpen -> pcKeyboardOpen = false + else -> routeBackAction() + } } }) watchSession() @@ -277,6 +336,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { }, 90) } + private fun triggerSteamQam() { + drawerOpen = false + padBridge?.triggerQam() + } + + private fun routeBackAction() { + pendingBackAction?.let { pending -> + uiHandler.removeCallbacks(pending) + pendingBackAction = null + performBackAction(double = true) + return + } + val pending = Runnable { + pendingBackAction = null + performBackAction(double = false) + } + pendingBackAction = pending + uiHandler.postDelayed(pending, BACK_DOUBLE_PRESS_TIMEOUT_MS) + } + + private fun performBackAction(double: Boolean) { + val isSteam = SessionState.mode == SessionService.MODE_STEAM + val opensQam = isSteam && (double xor backActionsInverted) + if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen + } + private fun handleHomeGuideIntent(incoming: Intent?) { if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return incoming.action = null @@ -286,6 +371,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun readPrefs() { hudOn = SessionPrefs.hudEnabled(this) + fillScreen = SessionPrefs.forceFullscreen(this) touchMode = SessionPrefs.touchMode(this) frameGenLabel = FrameGen.label(this) frameGenEngine = FrameGen.engine(this) @@ -293,6 +379,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { fexPreset = SessionPrefs.fexPreset(this) oscMode = SessionPrefs.oscMode(this) shapeMode = SessionPrefs.shapeMode(this) + backActionsInverted = SessionPrefs.backActionsInverted(this) } // ── Compositor ────────────────────────────────────────────────────────────────────────── @@ -481,7 +568,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // Wider than 16:9 is fine - games and the client cope with a phone's 20:9 - so the // panel's aspect is kept above that, unless the user pinned 16:9 for a foldable, and the // compositor letterboxes onto a squarer panel. - // "Exactly this panel" drops that floor, for a 4:3 or 3:2 handheld whose games should + // "Match screen" drops that floor, for a 4:3 or 3:2 handheld whose games should // fill it. val aspect = when (SessionPrefs.shapeMode(this)) { SessionPrefs.SHAPE_WIDE -> 16f / 9f @@ -620,10 +707,41 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> return super.dispatchKeyEvent(event) } - // With the drawer open the controller drives the drawer, not the game: Android's own - // handling moves focus with the d-pad and stick, and its fallbacks make A select and B Back - // (which closes the drawer) - the same as on the app's main screen. - if ((drawerOpen || pcKeyboardOpen) && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event) + val fromController = event.device != null && PadBridge.isFromController(event.device) + if (fromController && event.action == KeyEvent.ACTION_DOWN) { + if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus() + drawerControllerActive = true + } + if (drawerOpen) { + if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { + drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else 2) % 3 + releaseDrawerDirection() + } + return true + } + val handled = super.dispatchKeyEvent(event) + if (event.action == KeyEvent.ACTION_DOWN) { + Log.i(TAG, "drawer key=${KeyEvent.keyCodeToString(event.keyCode)} handled=$handled viewFocused=${sessionOverlay.hasFocus()}") + } + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK) { + if (!handled && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) drawerOpen = false + releaseDrawerDirection() + } + return true + } + val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START + val resumeKeyId = event.deviceId to event.keyCode + if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) { + if (event.action == KeyEvent.ACTION_DOWN) { + resumeKeysDown.add(resumeKeyId) + if (event.repeatCount == 0 && SessionState.suspended) SessionService.resume(this) + } else if (event.action == KeyEvent.ACTION_UP) { + resumeKeysDown.remove(resumeKeyId) + } + return true + } + if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event) if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true // A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the // activity, which opens the drawer. @@ -665,18 +783,102 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { - if ((drawerOpen || pcKeyboardOpen) && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event) + if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) { + if (!drawerControllerActive) sessionOverlay.requestFocus() + drawerControllerActive = true + if (event.actionMasked == MotionEvent.ACTION_MOVE && + event.isFromSource(InputDevice.SOURCE_JOYSTICK) + ) { + dispatchDrawerDirection(event) + } + return true + } + if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection() + if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event) if (padBridge?.onMotionEvent(event) == true) return true if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true return super.dispatchGenericMotionEvent(event) } - /** - * The pointer. Touch goes through [PointerGestures] (tap, hold, drag, two-finger scroll); a - * mouse arrives with real buttons and a wheel and is forwarded as it is. Every position is - * mapped through the letterboxed rectangle into the compositor's fixed 1920x1080 pointer - * space, and the arrow is drawn where the app last sent the pointer. - */ + override fun dispatchTouchEvent(event: MotionEvent): Boolean { + if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { + drawerControllerActive = false + } + return super.dispatchTouchEvent(event) + } + + private fun dispatchDrawerDirection(event: MotionEvent) { + val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X) + val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y) + val hatActive = maxOf(abs(hatX), abs(hatY)) >= DRAWER_HAT_THRESHOLD + val x = if (hatActive) hatX else centeredStickAxis(event, MotionEvent.AXIS_X) + val y = if (hatActive) hatY else centeredStickAxis(event, MotionEvent.AXIS_Y) + val directionThreshold = if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) { + DRAWER_STICK_ENTER_THRESHOLD + } else { + DRAWER_STICK_EXIT_THRESHOLD + } + val previousWasHorizontal = drawerDirectionKey == KeyEvent.KEYCODE_DPAD_LEFT || + drawerDirectionKey == KeyEvent.KEYCODE_DPAD_RIGHT + val horizontalWins = if (previousWasHorizontal) { + abs(x) >= abs(y) * DRAWER_ACTIVE_DIRECTION_MARGIN + } else { + abs(x) > abs(y) * DRAWER_DIRECTION_MARGIN + } + val keyCode = when { + maxOf(abs(x), abs(y)) < directionThreshold -> KeyEvent.KEYCODE_UNKNOWN + horizontalWins && x < 0f -> KeyEvent.KEYCODE_DPAD_LEFT + horizontalWins -> KeyEvent.KEYCODE_DPAD_RIGHT + y < 0f -> KeyEvent.KEYCODE_DPAD_UP + else -> KeyEvent.KEYCODE_DPAD_DOWN + } + val now = SystemClock.uptimeMillis() + if (keyCode == drawerDirectionKey) return + + Log.i(TAG, "drawer axis source=${event.source} x=$x y=$y direction=$keyCode") + releaseDrawerDirection() + if (keyCode == KeyEvent.KEYCODE_UNKNOWN) return + + drawerDirectionKey = keyCode + drawerDirectionDeviceId = event.deviceId + drawerDirectionDownTime = now + drawerDirectionRepeatCount = 0 + dispatchDrawerKey(KeyEvent.ACTION_DOWN, 0, now) + uiHandler.postDelayed(drawerDirectionRepeat, drawerFirstRepeatDelayMs) + } + + /** Use Android's per-device flat region, then rescale the remaining stick travel to 0..1. */ + private fun centeredStickAxis(event: MotionEvent, axis: Int): Float { + val value = event.getAxisValue(axis) + val flat = (event.device?.getMotionRange(axis, event.source)?.flat ?: 0f) + .coerceIn(0f, 0.95f) + val magnitude = abs(value) + if (magnitude <= flat) return 0f + + val centered = ((magnitude - flat) / (1f - flat)).coerceIn(0f, 1f) + return if (value < 0f) -centered else centered + } + + private fun releaseDrawerDirection() { + uiHandler.removeCallbacks(drawerDirectionRepeat) + if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) return + dispatchDrawerKey(KeyEvent.ACTION_UP, 0, SystemClock.uptimeMillis()) + drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN + drawerDirectionDeviceId = -1 + drawerDirectionRepeatCount = 0 + } + + private fun dispatchDrawerKey(action: Int, repeatCount: Int, eventTime: Long) { + val event = KeyEvent( + drawerDirectionDownTime, eventTime, action, drawerDirectionKey, + repeatCount, 0, drawerDirectionDeviceId, 0, 0, InputDevice.SOURCE_DPAD, + ) + if (action == KeyEvent.ACTION_DOWN && repeatCount == 0) { + Log.i(TAG, "drawer synthetic key=${KeyEvent.keyCodeToString(drawerDirectionKey)} viewFocused=${sessionOverlay.hasFocus()}") + } + super.dispatchKeyEvent(event) + } + private val pointerListener = object : PointerGestures.Listener { override fun onMove(x: Float, y: Float) = movePointer(x, y) override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { @@ -716,14 +918,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun refreshSecondScreenDisplays() { if (!::displayManager.isInitialized) return val primaryId = display?.displayId ?: windowManager.defaultDisplay.displayId - val candidates = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION) - .asSequence() - .filter { it.isValid && it.displayId != primaryId && (it.flags and Display.FLAG_PRESENTATION) != 0 } - .map { target -> - val mode = target.mode - SecondScreenDisplay(target.displayId, "${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}") - } - .toList() + val candidates = SecondScreenDisplays.available(displayManager, primaryId) val oldIds = secondScreenDisplays.map { it.id }.toSet() secondScreenDisplays = candidates val newIds = candidates.map { it.id }.toSet() @@ -784,6 +979,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onQam = { if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam() }, + onClose = { selectSecondScreenMode(SecondScreenMode.NONE) }, ) secondScreenPresentation = presentation } @@ -844,7 +1040,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } return touchpad.onTouch(event) } - return gestures.onTouch(event) + val rect = drawnRect() ?: return false + fun sendTouch(action: Int, index: Int) { + val x = ((event.getX(index) - rect.left) / rect.width()).coerceIn(0f, 1f) + val y = ((event.getY(index) - rect.top) / rect.height()).coerceIn(0f, 1f) + WaylandCompositor.nativeSendTouch(action, event.getPointerId(index), (x * 1919f).toInt(), (y * 1079f).toInt()) + } + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> sendTouch(0, event.actionIndex) + MotionEvent.ACTION_MOVE -> for (index in 0 until event.pointerCount) sendTouch(1, index) + MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> sendTouch(2, event.actionIndex) + MotionEvent.ACTION_CANCEL -> WaylandCompositor.nativeSendTouch(3, -1, 0, 0) + else -> return false + } + return true } /** A mouse: hover moves, buttons press, the wheel scrolls. Android sends buttons as touch @@ -885,7 +1094,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { SessionPrefs.OSC_ALWAYS -> true SessionPrefs.OSC_STEAM_QAM -> true SessionPrefs.OSC_NEVER -> false - else -> !PadBridge.anyControllerConnected() + // Auto: the touch pad when there is no controller - except on the desktop, where the + // screen is a touchpad for the pointer and a pad over it would be in the way. A game + // started from the rail, or Steam, gets it; the drawer turns it on anywhere. + else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP } if (show == (controls.visibility == View.VISIBLE)) return if (!show) controls.releaseAll() @@ -941,6 +1153,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onPause() { (getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener) + releaseDrawerDirection() // A button held when the app goes away would stay held in the ring for the whole session. onScreenControls?.releaseAll() keyboard?.takeIf { it.shown }?.hide() @@ -975,6 +1188,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // Deliberately does NOT end the session: this activity can be destroyed while the user is // in another app, and the whole point of the service is that Steam survives that. watching = false + releaseDrawerDirection() + pendingBackAction?.let(uiHandler::removeCallbacks) + pendingBackAction = null closeSecondScreen(reset = true) if (::hud.isInitialized) hud.stop() padBridge?.stop() @@ -991,6 +1207,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { companion object { private const val TAG = "SessionActivity" + private const val BACK_DOUBLE_PRESS_TIMEOUT_MS = 500L + private const val DRAWER_HAT_THRESHOLD = 0.5f + private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f + private const val DRAWER_STICK_EXIT_THRESHOLD = 0.35f + private const val DRAWER_DIRECTION_MARGIN = 1.15f + private const val DRAWER_ACTIVE_DIRECTION_MARGIN = 0.85f + private const val DRAWER_SLOW_REPEAT_FLOOR_MS = 240L + private const val DRAWER_FAST_REPEAT_INTERVAL_MS = 90L + private const val DRAWER_REPEAT_ACCELERATION_MS = 1_400L /** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */ private const val SCALE_FIT = 1 private const val ALIGN_CENTER = 0 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 060efb5b93..498eb1fd24 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -149,6 +149,7 @@ object DeviceReport { k("Skip xalia", SessionPrefs.noXalia(context)) k("proot without seccomp", SessionPrefs.prootNoSeccomp(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") k("Microphone", SessionPrefs.micEnabled(context)) k("On-screen controls", SessionPrefs.oscMode(context)) diff --git a/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt b/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt new file mode 100644 index 0000000000..c5bbef88e7 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt @@ -0,0 +1,243 @@ +package com.droiddeck.launcher.files + +import android.content.Context +import android.content.pm.ProviderInfo +import android.content.res.AssetFileDescriptor +import android.database.Cursor +import android.database.MatrixCursor +import android.graphics.Point +import android.os.CancellationSignal +import android.os.ParcelFileDescriptor +import android.provider.DocumentsContract.Document +import android.provider.DocumentsContract.Root +import android.provider.DocumentsProvider +import android.webkit.MimeTypeMap +import com.droiddeck.launcher.R +import java.io.File +import java.io.FileNotFoundException +import java.io.IOException +import java.nio.file.FileVisitResult +import java.nio.file.Files +import java.nio.file.LinkOption +import java.nio.file.Path +import java.nio.file.SimpleFileVisitor +import java.nio.file.attribute.BasicFileAttributes + +/** + * The app's own data folder (the Linux runtime, settings, logs) in Android's file picker, under the + * app's name beside the phone's storage - what MT Manager's "documents provider" injection does, as + * part of the app. Only the system's documents UI can bind it (MANAGE_DOCUMENTS); another app sees + * a file only when the user picks it there. + * + * A document id is the file's absolute path, and nothing outside the data folder is ever handed out + * or accepted: every id is resolved and checked to lie inside it. + */ +class AppFilesProvider : DocumentsProvider() { + private lateinit var base: File + private lateinit var baseCanonical: String + + override fun attachInfo(context: Context, info: ProviderInfo) { + super.attachInfo(context, info) + base = context.dataDir + baseCanonical = base.canonicalPath + } + + override fun onCreate() = true + + override fun queryRoots(projection: Array?): Cursor { + val ctx = context!! + val result = MatrixCursor(projection ?: ROOT_COLUMNS) + result.newRow().apply { + add(Root.COLUMN_ROOT_ID, ROOT_ID) + add(Root.COLUMN_DOCUMENT_ID, base.absolutePath) + add(Root.COLUMN_TITLE, titleFor(ctx)) + add(Root.COLUMN_SUMMARY, null) + add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE or Root.FLAG_SUPPORTS_SEARCH or Root.FLAG_SUPPORTS_IS_CHILD) + add(Root.COLUMN_MIME_TYPES, "*/*") + add(Root.COLUMN_AVAILABLE_BYTES, base.freeSpace) + add(Root.COLUMN_ICON, R.mipmap.ic_launcher) + } + return result + } + + override fun queryDocument(documentId: String, projection: Array?): Cursor = + MatrixCursor(projection ?: DOCUMENT_COLUMNS).also { addRow(it, fileFor(documentId)) } + + override fun queryChildDocuments(parentDocumentId: String, projection: Array?, sortOrder: String?): Cursor { + val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS) + // A link in the runtime that leads out of the data folder (/etc/localtime and the like) is + // left out rather than listed as something that cannot be opened. + fileFor(parentDocumentId).listFiles()?.filter { inside(it) }?.forEach { addRow(result, it) } + return result + } + + override fun openDocument(documentId: String, mode: String, signal: CancellationSignal?): ParcelFileDescriptor = + ParcelFileDescriptor.open(fileFor(documentId), ParcelFileDescriptor.parseMode(mode)) + + override fun openDocumentThumbnail(documentId: String, sizeHint: Point?, signal: CancellationSignal?): AssetFileDescriptor { + val file = fileFor(documentId) + return AssetFileDescriptor(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY), 0, file.length()) + } + + override fun createDocument(parentDocumentId: String, mimeType: String, displayName: String): String { + val parent = fileFor(parentDocumentId) + val name = displayName.substringAfterLast('/') + var file = File(parent, name) + var n = 2 + while (file.exists()) file = File(parent, "$name (${n++})") + val made = try { + if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile() + } catch (e: IOException) { + false + } + if (!made) throw FileNotFoundException("could not create ${file.path}") + return file.absolutePath + } + + override fun deleteDocument(documentId: String) { + val file = fileFor(documentId) + if (file.absolutePath == base.absolutePath) throw FileNotFoundException("the app folder itself is not deleted") + try { + deleteTree(file.toPath()) + } catch (e: IOException) { + throw FileNotFoundException("could not delete $documentId: ${e.message}") + } + } + + /** + * Deletes a file or a folder and what is in it without ever following a link: the runtime holds + * links to places outside it, and deleting a folder must remove the link, not what it points at. + */ + private fun deleteTree(root: Path) { + if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) { + Files.delete(root) + return + } + Files.walkFileTree(root, object : SimpleFileVisitor() { + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + Files.delete(file) + return FileVisitResult.CONTINUE + } + + override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult { + if (exc != null) throw exc + Files.delete(dir) + return FileVisitResult.CONTINUE + } + }) + } + + override fun removeDocument(documentId: String, parentDocumentId: String) = deleteDocument(documentId) + + override fun renameDocument(documentId: String, displayName: String): String { + val file = fileFor(documentId) + val target = File(file.parentFile, displayName.substringAfterLast('/')) + if (target.exists() || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId") + return target.absolutePath + } + + override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String { + val source = fileFor(sourceDocumentId) + val targetParent = fileFor(targetParentDocumentId) + if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder") + val target = File(targetParent, source.name) + if (target.exists() || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId") + return target.absolutePath + } + + override fun getDocumentType(documentId: String): String = mimeOf(fileFor(documentId)) + + override fun isChildDocument(parentDocumentId: String, documentId: String): Boolean { + val parent = runCatching { fileFor(parentDocumentId).absolutePath }.getOrNull() ?: return false + val child = runCatching { fileFor(documentId).absolutePath }.getOrNull() ?: return false + return child == parent || child.startsWith("$parent/") + } + + override fun querySearchDocuments(rootId: String, query: String, projection: Array?): Cursor { + val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS) + val needle = query.lowercase() + val pending = ArrayDeque(listOf(base)) + var visited = 0 + // The runtime is tens of thousands of files: a bounded walk, not the whole tree. + while (pending.isNotEmpty() && result.count < 50 && visited++ < 20000) { + val f = pending.removeFirst() + if (!inside(f)) continue + if (f.isDirectory) f.listFiles()?.let { pending.addAll(it) } + else if (f.name.lowercase().contains(needle)) addRow(result, f) + } + return result + } + + /** The file an id names, when it exists and lies inside the data folder (links followed). */ + private fun fileFor(documentId: String): File { + val f = File(documentId) + if (!f.isAbsolute || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files") + if (!f.exists()) throw FileNotFoundException("$documentId not found") + return f + } + + private fun inside(f: File): Boolean { + // The folder's own entries are listed as they are; a link is judged by where it leads. + val abs = f.absoluteFile.normalize().path + if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false + val real = runCatching { f.canonicalPath }.getOrNull() ?: return false + return real == baseCanonical || real.startsWith("$baseCanonical/") + } + + private fun addRow(result: MatrixCursor, file: File) { + var flags = 0 + if (file.isDirectory) { + if (file.canWrite()) flags = flags or Document.FLAG_DIR_SUPPORTS_CREATE + } else if (file.canWrite()) { + flags = flags or Document.FLAG_SUPPORTS_WRITE + } + if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true) { + flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or + Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE + } + val mime = mimeOf(file) + if (mime.startsWith("image/")) flags = flags or Document.FLAG_SUPPORTS_THUMBNAIL + result.newRow().apply { + add(Document.COLUMN_DOCUMENT_ID, file.absolutePath) + add(Document.COLUMN_DISPLAY_NAME, if (file.absolutePath == base.absolutePath) titleFor(context!!) else file.name) + add(Document.COLUMN_SIZE, if (file.isDirectory) null else file.length()) + add(Document.COLUMN_MIME_TYPE, mime) + add(Document.COLUMN_LAST_MODIFIED, file.lastModified()) + add(Document.COLUMN_FLAGS, flags) + } + } + + private fun mimeOf(file: File): String { + if (file.isDirectory) return Document.MIME_TYPE_DIR + val ext = file.extension.lowercase() + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) ?: "application/octet-stream" + } + + companion object { + private const val ROOT_ID = "app" + + private val ROOT_COLUMNS = arrayOf( + Root.COLUMN_ROOT_ID, Root.COLUMN_MIME_TYPES, Root.COLUMN_FLAGS, Root.COLUMN_ICON, + Root.COLUMN_TITLE, Root.COLUMN_SUMMARY, Root.COLUMN_DOCUMENT_ID, Root.COLUMN_AVAILABLE_BYTES, + ) + private val DOCUMENT_COLUMNS = arrayOf( + Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME, + Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE, + ) + + /** + * The name in the picker. The same app ships under other package names (for the performance + * modes some phones give only named apps); each says which it is, so four installs are not + * four identical "DroidDeck" entries. + */ + fun titleFor(context: Context): String { + val name = context.getString(R.string.app_name) + return when (context.packageName) { + "com.tencent.ig" -> "$name PUBG" + "com.antutu.benchmark.full" -> "$name AnTuTu" + "com.ludashi.benchmark" -> "$name Ludashi" + else -> name + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/CoverArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/CoverArt.kt new file mode 100644 index 0000000000..cf7f151aa3 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/CoverArt.kt @@ -0,0 +1,260 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context +import android.graphics.BitmapFactory +import android.util.Log +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.RandomAccessFile +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder + +/** + * Box art for the emulators' games, found and kept on the device: the front end shows a disc image + * with nothing but its emulator's logo otherwise. + * + * In order: the name of the file against RetroArch's thumbnail collection for the system + * (libretro-thumbnails, named after the standard disc-dump names - "Need for Speed - Underground 2 + * (USA)"), first exactly and then loosely (tags dropped, the same region preferred) against the + * collection's list of names; then the disc's own ID, read from the image - PS2 serials against + * xlenore/ps2-covers (what PCSX2 and ARMSX2 download from), GameCube/Wii IDs against GameTDB (what + * Dolphin uses). A PS3 disc image gives its own PS3_GAME/ICON0.PNG first: the libretro PS3 + * collection is small. A cover is downloaded once into files/covers; a game none of them has is not + * asked about again for a few days. + */ +object CoverArt { + private const val TAG = "CoverArt" + private const val MISS_RETRY_MS = 3L * 24 * 3600 * 1000 + private const val INDEX_TTL_MS = 14L * 24 * 3600 * 1000 + /** Downloads in one pass, so a first visit to a big library does not hold the network for long. */ + private const val MAX_PER_PASS = 40 + + /** The emulator's systems in libretro-thumbnails, in the order they are tried. */ + private val collections = mapOf( + "rpcs3" to listOf("Sony_-_PlayStation_3"), + "armsx2" to listOf("Sony_-_PlayStation_2"), + "duckstation" to listOf("Sony_-_PlayStation"), + "ppsspp" to listOf("Sony_-_PlayStation_Portable"), + "dolphin" to listOf("Nintendo_-_GameCube", "Nintendo_-_Wii"), + "melonds" to listOf("Nintendo_-_Nintendo_DS"), + "cemu" to listOf("Nintendo_-_Wii_U"), + ) + + private fun root(context: Context) = File(context.filesDir, "covers") + + /** The file name, as the cover is kept under: a game keeps its art when its folder moves. */ + private fun keyOf(rom: Library.Rom): String = + rom.hostPath.name.replace(Regex("[^A-Za-z0-9._() -]"), "_").take(150) + + private fun coverFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.img") + private fun missFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.miss") + + /** A cover already on the device for this game, or null. */ + fun cached(context: Context, rom: Library.Rom): File? = coverFile(context, rom).takeIf { it.isFile && it.length() > 0 } + + private fun wanted(context: Context, rom: Library.Rom): Boolean { + if (rom.art != null || cached(context, rom) != null || rom.emulatorId !in collections) return false + val miss = missFile(context, rom) + return !(miss.isFile && System.currentTimeMillis() - miss.lastModified() < MISS_RETRY_MS) + } + + /** + * Looks for covers for the games that have none, on the calling (background) thread. True when + * at least one was found, so the caller rebuilds the list to show it. + */ + fun fetchMissing(context: Context, roms: List): Boolean { + var found = false + var tries = 0 + for (rom in roms) { + if (!wanted(context, rom)) continue + if (++tries > MAX_PER_PASS) break + val target = coverFile(context, rom) + // A PS3 disc carries its own cover (PS3_GAME/ICON0.PNG, not encrypted): no download. + if (rom.emulatorId == "rpcs3" && try { copyPs3Icon(rom.hostPath, target) } catch (e: Exception) { false }) { + Log.i(TAG, "${rom.name}: ICON0.PNG from the disc") + missFile(context, rom).delete() + found = true + continue + } + val url = try { findUrl(context, rom) } catch (e: Exception) { Log.w(TAG, "${rom.name}: $e"); null } + if (url != null && download(url, target)) { + Log.i(TAG, "${rom.name}: $url") + missFile(context, rom).delete() + found = true + } else { + missFile(context, rom).apply { parentFile?.mkdirs(); writeText(url ?: "") } + } + } + return found + } + + private fun findUrl(context: Context, rom: Library.Rom): String? { + val name = rom.hostPath.nameWithoutExtension.removeSuffix(".dec") + for (collection in collections.getValue(rom.emulatorId)) { + // Exactly the dump name first: no listing needed. + val exact = thumbnailUrl(collection, name) + if (exists(exact)) return exact + // Then loosely, against the collection's names. + nearest(name, names(context, collection))?.let { return thumbnailUrl(collection, it) } + } + // The disc's own ID. + return when (rom.emulatorId) { + "armsx2" -> ps2Serial(rom.hostPath)?.let { "https://raw.githubusercontent.com/xlenore/ps2-covers/main/covers/default/$it.jpg" } + "dolphin" -> nintendoDiscId(rom.hostPath)?.let { id -> + val region = when (id.getOrNull(3)) { 'P' -> "EN"; 'J' -> "JA"; 'K' -> "KO"; else -> "US" } + "https://art.gametdb.com/wii/cover/$region/$id.png" + } + else -> null + }?.takeIf { exists(it) } + } + + /** libretro-thumbnails replaces these in a title's file name. */ + private fun thumbName(title: String) = title.replace(Regex("[&*/:`<>?\\\\|\"]"), "_") + + private fun thumbnailUrl(collection: String, title: String) = + "https://raw.githubusercontent.com/libretro-thumbnails/$collection/master/Named_Boxarts/" + + URLEncoder.encode("${thumbName(title)}.png", "UTF-8").replace("+", "%20") + + // ---- loose matching ------------------------------------------------------------------------ + + private fun tags(name: String): List = Regex("[(\\[]([^)\\]]*)[)\\]]").findAll(name).map { it.groupValues[1].lowercase() }.toList() + + /** A title without its tags, articles and punctuation: "Legend of Zelda, The (USA)" = "legend of zelda". */ + private fun base(name: String): String = name + .replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), " ") + .lowercase() + .replace(Regex("[^a-z0-9]+"), " ") + .split(' ').filter { it.isNotEmpty() && it != "the" && it != "a" } + .joinToString(" ") + + private fun nearest(name: String, candidates: List): String? { + if (candidates.isEmpty()) return null + val want = base(name) + if (want.isEmpty()) return null + val same = candidates.filter { base(it) == want } + if (same.isEmpty()) return null + val region = tags(name).firstOrNull { it in setOf("usa", "europe", "japan", "world", "korea") } ?: "usa" + return same.firstOrNull { region in tags(it) } ?: same.firstOrNull { "usa" in tags(it) } ?: same.first() + } + + /** The titles in a collection's Named_Boxarts (no extension), kept for a fortnight. */ + private fun names(context: Context, collection: String): List { + val cache = File(root(context), "index-$collection.txt") + if (cache.isFile && System.currentTimeMillis() - cache.lastModified() < INDEX_TTL_MS) return cache.readLines() + val list = try { + val top = JSONArray(get("https://api.github.com/repos/libretro-thumbnails/$collection/contents/") ?: return cachedOr(cache)) + val sha = (0 until top.length()).map { top.getJSONObject(it) }.firstOrNull { it.optString("name") == "Named_Boxarts" } + ?.optString("sha") ?: return cachedOr(cache) + val tree = JSONObject(get("https://api.github.com/repos/libretro-thumbnails/$collection/git/trees/$sha") ?: return cachedOr(cache)) + .getJSONArray("tree") + (0 until tree.length()).map { tree.getJSONObject(it).optString("path") } + .filter { it.endsWith(".png") }.map { it.removeSuffix(".png") } + } catch (e: Exception) { + Log.w(TAG, "index $collection: $e"); return cachedOr(cache) + } + cache.parentFile?.mkdirs() + cache.writeText(list.joinToString("\n")) + return list + } + + private fun cachedOr(cache: File): List = if (cache.isFile) cache.readLines() else emptyList() + + // ---- disc IDs ------------------------------------------------------------------------------ + + /** + * A file's bytes from an ISO 9660 image by path ("PS3_GAME/ICON0.PNG"), or null. Primary volume + * names only (upper case, ";1" suffix), which is what PS2 and PS3 discs use. + */ + private fun isoFile(file: File, path: String, maxSize: Int): ByteArray? { + if (!file.name.endsWith(".iso", ignoreCase = true)) return null + RandomAccessFile(file, "r").use { f -> + fun read(lba: Long, length: Int): ByteArray = ByteArray(length).also { f.seek(lba * 2048); f.readFully(it) } + fun le32(b: ByteArray, at: Int) = (b[at].toLong() and 0xff) or ((b[at + 1].toLong() and 0xff) shl 8) or + ((b[at + 2].toLong() and 0xff) shl 16) or ((b[at + 3].toLong() and 0xff) shl 24) + val pvd = read(16, 2048) + if (String(pvd, 1, 5, Charsets.US_ASCII) != "CD001") return null + var lba = le32(pvd, 156 + 2) + var size = le32(pvd, 156 + 10) + val parts = path.split('/') + for ((i, part) in parts.withIndex()) { + val dir = read(lba, size.toInt().coerceAtMost(256 * 1024)) + var at = 0 + var hit = false + while (at < dir.size) { + val len = dir[at].toInt() and 0xff + if (len == 0) { at = (at / 2048 + 1) * 2048; continue } + val name = String(dir, at + 33, dir[at + 32].toInt() and 0xff, Charsets.US_ASCII).substringBefore(';') + if (name.equals(part, ignoreCase = true)) { + lba = le32(dir, at + 2); size = le32(dir, at + 10); hit = true; break + } + at += len + } + if (!hit) return null + if (i == parts.lastIndex) return if (size in 1..maxSize) read(lba, size.toInt()) else null + } + } + return null + } + + private fun copyPs3Icon(file: File, target: File): Boolean { + val png = isoFile(file, "PS3_GAME/ICON0.PNG", 4 * 1024 * 1024) ?: return false + target.parentFile?.mkdirs() + val tmp = File(target.path + ".part") + tmp.writeBytes(png) + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeFile(tmp.path, bounds) + return if (bounds.outWidth > 0 && tmp.renameTo(target)) true else { tmp.delete(); false } + } + + /** "SLUS-21065" from a PS2 .iso's SYSTEM.CNF (BOOT2 = cdrom0:\SLUS_210.65;1), or null. */ + private fun ps2Serial(file: File): String? { + val cnf = String(isoFile(file, "SYSTEM.CNF", 4096) ?: return null, Charsets.US_ASCII) + val m = Regex("BOOT2\\s*=\\s*cdrom0:\\\\?([A-Z]{4})_(\\d{3})\\.(\\d{2})").find(cnf) ?: return null + return "${m.groupValues[1]}-${m.groupValues[2]}${m.groupValues[3]}" + } + + /** The six-character ID of a GameCube/Wii disc image (.iso/.gcm, or .wbfs), or null. */ + private fun nintendoDiscId(file: File): String? { + val offset = when (file.extension.lowercase()) { "iso", "gcm" -> 0L; "wbfs" -> 0x200L; else -> return null } + RandomAccessFile(file, "r").use { f -> + val b = ByteArray(6); f.seek(offset); f.readFully(b) + val id = String(b, Charsets.US_ASCII) + return id.takeIf { it.all { c -> c.isLetterOrDigit() } } + } + } + + // ---- network ------------------------------------------------------------------------------- + + private fun open(url: String, method: String = "GET"): HttpURLConnection = + (URL(url).openConnection() as HttpURLConnection).apply { + requestMethod = method + connectTimeout = 10_000 + readTimeout = 20_000 + instanceFollowRedirects = true + setRequestProperty("User-Agent", "DroidDeck") + } + + private fun exists(url: String): Boolean = try { + val c = open(url, "HEAD"); val ok = c.responseCode == 200; c.disconnect(); ok + } catch (e: Exception) { false } + + private fun get(url: String): String? = try { + val c = open(url) + if (c.responseCode != 200) { c.disconnect(); null } else c.inputStream.bufferedReader().use { it.readText() } + } catch (e: Exception) { Log.w(TAG, "$url: $e"); null } + + /** Saves the image at [url] to [target] if it really is an image. */ + private fun download(url: String, target: File): Boolean = try { + val c = open(url) + if (c.responseCode != 200) { c.disconnect(); false } else { + target.parentFile?.mkdirs() + val tmp = File(target.path + ".part") + c.inputStream.use { input -> tmp.outputStream().use { input.copyTo(it) } } + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeFile(tmp.path, bounds) + if (bounds.outWidth > 0 && tmp.renameTo(target)) true else { tmp.delete(); false } + } + } catch (e: Exception) { Log.w(TAG, "$url: $e"); false } +} 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 c56971aae3..e255d314b6 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -71,11 +71,24 @@ object Library { Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")), Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()), ) + /** + * A dump's file name as a title: its tags - (USA), (En,Fr,Es,Pt), [!], (v1.01) - identify the + * file and are dropped for reading ("Tomb Raider (USA) (En,Fr,Es,Pt)" -> "Tomb Raider"). The + * file keeps them, and the cover lookup still uses them. + */ + private fun displayTitle(name: String): String = + name.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), "").trim().ifEmpty { name } + + /** Every system folder name the specs claim, so a loose-file scan of the root skips them. */ + private val systemFolders: Set by lazy { specs.flatMap { it.folders }.toSet() } private val installedIds = mapOf( "rpcs3" to "rpcs3", "armsx2" to "armsx2", "dolphin" to "dolphin", "duckstation" to "duckstation", "melonds" to "melonds", "cemu" to "cemu", "ppsspp" to "emulators", "retroarch" to "emulators", ) + /** 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 + /** Desktop catalog package that supplies this emulator. */ fun packageId(emulatorId: String): String? = installedIds[emulatorId] @@ -85,37 +98,68 @@ object Library { return specs.map { spec -> val games = ArrayList() if (romsRoot != null && spec.exts.isNotEmpty()) { - // The system's folder(s), matched without regard to case, then the root itself for - // a file left loose there - and one folder deeper, since a dump usually comes as a - // folder named for the game with the image inside it. + // The system's folder(s), matched without regard to case, and up to three folders + // inside them - a dump usually comes as a folder named for the game with the image + // inside it, and people sort those into folders of their own (ps2/games//). + // The root itself only one deep, for a file left loose there. val systemDirs = romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() in spec.folders }.orEmpty().toList() val dirs = LinkedHashSet() - for (top in systemDirs + romsRoot) { - dirs.add(top) - top.listFiles { f -> f.isDirectory }?.forEach { dirs.add(it) } - } + // A BIOS folder holds the console's firmware, not games (psx/bios/SCPH1001.BIN). + for (top in systemDirs) top.walkTopDown().maxDepth(3).onEnter { it.name.lowercase() !in firmwareFolders } + .filter { it.isDirectory }.forEach { dirs.add(it) } + dirs.add(romsRoot) + // ...and not into another system's folder: a PS3 .iso in ps3/ is not a PS2 game. + romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() !in systemFolders }?.forEach { dirs.add(it) } for (dir in dirs) { // A PS3 disc dump is a folder with PS3_GAME in it; RPCS3 boots the folder. if (spec.id == "rpcs3" && File(dir, "PS3_GAME").isDirectory) { val rel = dir.relativeTo(romsRoot).path - games.add(Rom(dir.name, dir, "/root/ROMs/$rel", spec.id)) + games.add(Rom(displayTitle(dir.name), dir, "/root/ROMs/$rel", spec.id, + // The dump carries its own art, as an installed package does. + art = File(dir, "PS3_GAME/ICON0.PNG").takeIf { it.isFile })) continue } - dir.listFiles()?.sortedBy { it.name.lowercase() }?.forEach { f -> + val files = dir.listFiles()?.sortedBy { it.name.lowercase() }.orEmpty() + // A disc sheet (.cue, .gdi) names its track files and a playlist (.m3u) its + // discs: the sheet is the game, what it names is part of it. A .bin beside a + // .cue of the same name is a track even when the sheet can't be read. + val parts = files.filter { it.isFile && it.extension.lowercase() in sheetExts }.flatMap(::sheetParts).toSet() + files.forEach { f -> val ext = f.extension.lowercase() - // A .bin beside a .cue is a track, not a game. - if (f.isFile && ext in spec.exts && !(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) { + if (f.isFile && ext in spec.exts && f.name.lowercase() !in parts && + !(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) { val rel = f.relativeTo(romsRoot).path - games.add(Rom(f.nameWithoutExtension.removeSuffix(".dec"), f, "/root/ROMs/$rel", spec.id)) + games.add(Rom(displayTitle(f.nameWithoutExtension.removeSuffix(".dec")), f, "/root/ROMs/$rel", spec.id)) } } } } if (spec.id == "rpcs3") games.addAll(rpcs3Installed(context)) - Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), games) + // A cover found for the game before (CoverArt) where it has no art of its own. + val withArt = games.map { g -> if (g.art != null) g else CoverArt.cached(context, g)?.let { Rom(g.name, g.hostPath, g.guestPath, g.emulatorId, it) } ?: g } + Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), withArt) } } + private val firmwareFolders = setOf("bios", "firmware") + private val sheetExts = setOf("cue", "gdi", "m3u") + + /** The file names (lower case) a .cue, .gdi or .m3u refers to, from its own folder. */ + private fun sheetParts(sheet: File): List = runCatching { + if (sheet.length() > 64 * 1024) return emptyList() + sheet.readLines().mapNotNull { line -> + val t = line.trim() + when (sheet.extension.lowercase()) { + // FILE "Tekken 3 (USA) (Track 1).bin" BINARY + "cue" -> Regex("^FILE\\s+\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1) + ?: Regex("^FILE\\s+(\\S+)", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1) + // 1 0 4 2352 "track01.bin" 0 / 1 0 4 2352 track01.bin 0 + "gdi" -> Regex("\"([^\"]+)\"").find(t)?.groupValues?.get(1) ?: t.split(Regex("\\s+")).getOrNull(4) + else -> t.takeIf { it.isNotEmpty() && !it.startsWith("#") } + } + }.map { File(it.replace('\\', '/')).name.lowercase() } + }.getOrDefault(emptyList()) + /** * What RPCS3 has installed on its own HDD - packages (PSN games) land in dev_hdd0/game/ * with a PARAM.SFO for the title and an EBOOT to boot - as RPCS3's own file list would show @@ -170,6 +214,11 @@ object Library { /** How the emulator is told which game to boot, on its command line. */ fun launchArgs(emulatorId: String, guestPath: String): List = when (emulatorId) { "rpcs3" -> listOf("--no-gui", guestPath) + // Straight into the game in its controller-driven full-screen UI (first-time setup there + // too), and gone when the game is quit from its pause menu (guide button): -batch. + "armsx2" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath) + // DuckStation shares PCSX2's flags (src/duckstation-qt/qthost.cpp): the same launch and exit. + "duckstation" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath) "dolphin" -> listOf("-e", guestPath) "cemu" -> listOf("-g", guestPath) else -> listOf(guestPath) 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 86daa46204..85fc94ca8c 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt @@ -1,5 +1,8 @@ package com.droiddeck.launcher.input +import android.hardware.display.DisplayManager +import android.view.Display + /** The control surface shown on a secondary Android display during a Linux session. */ enum class SecondScreenMode(val id: String, val label: String) { NONE("none", "None"), @@ -8,3 +11,19 @@ enum class SecondScreenMode(val id: String, val label: String) { } data class SecondScreenDisplay(val id: Int, val label: String) + +/** The presentation-capable displays shared by the session controls and Android app launcher. */ +object SecondScreenDisplays { + fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List = + displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION) + .asSequence() + .filter { it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 } + .map { target -> + val mode = target.mode + SecondScreenDisplay( + target.displayId, + "${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}", + ) + } + .toList() +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt index 7654917e98..2de78f99c6 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt @@ -31,12 +31,18 @@ object DesktopCatalog { return try { val json = JSONObject(body) val arr = json.getJSONArray("packages") + // A package built per memory page size (ARMSX2: 4K and 16K kernels) names the others + // under "pages"; the device's own size picks one, and the top-level file is the 4K one. + val pageSize = try { + android.system.Os.sysconf(android.system.OsConstants._SC_PAGESIZE).toString() + } catch (e: Exception) { "4096" } (0 until arr.length()).map { i -> val o = arr.getJSONObject(i) + val file = o.optJSONObject("pages")?.optJSONObject(pageSize) ?: o Entry( o.getString("id"), o.getString("name"), o.optInt("tier", 1), o.optString("version", ""), - o.optString("kind", "tar"), o.getString("url"), o.optString("sha256", ""), - o.optLong("size", 0L), o.optString("notes", ""), + o.optString("kind", "tar"), file.getString("url"), file.optString("sha256", ""), + file.optLong("size", 0L), o.optString("notes", ""), o.optString("icon", "applications-games"), o.optString("category", "Game"), ) } 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 a2c1dbe772..c44ead89a8 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -13,6 +13,12 @@ object SessionPrefs { const val OSC_STEAM_QAM = "steam-qam" const val OSC_NEVER = "never" + const val BACK_MENU_THEN_QAM = "1: menu 2: QAM" + const val BACK_QAM_THEN_MENU = "1: QAM 2: menu" + + fun backActionsOrder(inverted: Boolean): String = + if (inverted) BACK_QAM_THEN_MENU else BACK_MENU_THEN_QAM + private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE) fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true) @@ -21,6 +27,13 @@ object SessionPrefs { prefs(context).edit().putBoolean("hud", on).apply() } + /** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */ + fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false) + + fun setBackActionsInverted(context: Context, inverted: Boolean) { + prefs(context).edit().putBoolean("backActionsInverted", inverted).apply() + } + const val TOUCH_AUTO = "auto" const val TOUCH_PAD = "touchpad" const val TOUCH_DIRECT = "direct" @@ -39,9 +52,9 @@ object SessionPrefs { /** The choices the settings offer, in order. */ val shapeChoices = listOf( - SHAPE_AUTO to "The panel's shape (16:9 or wider)", - SHAPE_EXACT to "Exactly this panel (4:3, 3:2…)", - SHAPE_WIDE to "16:9 with bars", + SHAPE_AUTO to "Auto (16:9+)", + SHAPE_EXACT to "Match screen", + SHAPE_WIDE to "Always 16:9", ) /** @@ -87,6 +100,32 @@ object SessionPrefs { prefs(context).edit().putBoolean("clientDirectAudio", on).apply() } + /** + * Steam only: gamescope makes every game window the size of the screen. A game that resizes + * its own window when it loses focus (FlatOut) otherwise comes back smaller, drawn in a + * corner; a game that sets its own resolution and never looks at its window again (Quake 3) + * instead draws small in the bottom-left of the stretched one. On unless turned off. + */ + fun forceFullscreen(context: Context): Boolean = prefs(context).getBoolean("forceFullscreen", true) + + fun setForceFullscreen(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("forceFullscreen", on).apply() + writeForceFullscreenFlag(context) + } + + /** + * The same choice as a file the running session watches, so the drawer can change it live: + * the session hands every change to gamescope, which reads GAMESCOPE_FORCE_WINDOWS_FULLSCREEN + * off its root window whenever it changes. Written again at every session start so a file left + * by an earlier session never disagrees with the setting. + */ + fun writeForceFullscreenFlag(context: Context) { + runCatching { + java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-fill") + .writeText(if (forceFullscreen(context)) "1\n" else "0\n") + } + } + /** * DirectAudio for games: their Wine audio driver talks to the relay helper on this side. On * unless the user turned it off. 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 f2911c22ac..5fa6f3c5d7 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -304,6 +304,10 @@ class SessionService : Service() { if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=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_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. 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 052630cc78..5c73281b7c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -1,8 +1,18 @@ package com.droiddeck.launcher.ui +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.foundation.focusGroup +import androidx.compose.ui.focus.FocusDirection +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.onFocusChanged import android.graphics.Bitmap import android.os.Build import android.provider.Settings +import android.view.Display import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility @@ -54,6 +64,7 @@ import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -64,6 +75,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator @@ -76,6 +88,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.snapshotFlow +import kotlinx.coroutines.flow.first import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -97,7 +111,14 @@ import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.input.InputMode 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.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset @@ -106,8 +127,11 @@ import androidx.compose.ui.unit.sp import androidx.compose.ui.zIndex import coil.compose.AsyncImage import com.droiddeck.launcher.R +import com.droiddeck.launcher.HomeApp import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.input.SecondScreenDisplay +import com.droiddeck.launcher.session.SessionPrefs import java.io.File import kotlin.math.roundToInt @@ -133,14 +157,18 @@ class FrontEndState( val pageKey: String? = null, val theme: String = Themes.PAPER, val isHomeApp: Boolean = false, + val homeScreenEnabled: Boolean = false, val defaultHomeLabel: String? = null, - val androidApps: List = emptyList(), + val androidApps: List = emptyList(), + val secondScreenDisplays: List = emptyList(), val packages: List? = null, val packageCatalogLoading: Boolean = false, val packageBusyId: String? = null, val packageStage: String? = null, val packagePercent: Int = -1, val sessionRunning: Boolean = false, + val backActionsInverted: Boolean = false, + val buildLabel: String = "local", ) class FrontEndActions( @@ -168,7 +196,10 @@ class FrontEndActions( val onPageBack: () -> Unit = {}, val onTheme: (String) -> Unit = {}, val onHomeApp: () -> Unit = {}, - val onAndroidApp: (com.droiddeck.launcher.HomeApp.LaunchableApp) -> Unit = {}, + val onHomeScreen: (Boolean) -> Unit = {}, + val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> }, + val onBackActionsInverted: (Boolean) -> Unit = {}, + val onCheckLatestBuild: () -> Unit = {}, ) @@ -227,16 +258,102 @@ private fun Modifier.shine(trigger: Boolean, strength: Float = 0.22f): Modifier } +/** + * Controller focus on the front end: each rail item's requester and the page's main button (Play, + * Open desktop, Open , Launch...). The pane leaves, to the left, for the selected rail + * item - whatever tile or button it leaves from - and remembers that control, so coming back in + * lands on it again; a page not yet visited enters on its main button. + */ +private class FrontFocus { + val rail = HashMap() + val primary = FocusRequester() + var primaryAttached by mutableStateOf(0) + var railFocused by mutableStateOf(false) + fun railFor(key: String): FocusRequester = rail.getOrPut(key) { FocusRequester() } + // The pane's controls by id (a tile's key, a button's label), how many of each are on screen, + // and the last one focused. + val items = HashMap() + val attached = HashMap() + var last: String? = null + // The first tile of the page's grid: Down from the page's buttons goes to it, not to whichever + // tile happens to sit under the button. + val firstTile = FocusRequester() + var firstTileAttached = 0 + fun paneEntry(): FocusRequester { + val id = last + return when { + id == PRIMARY && primaryAttached > 0 -> primary + id != null && id != PRIMARY && (attached[id] ?: 0) > 0 -> items.getValue(id) + primaryAttached > 0 -> primary + else -> FocusRequester.Default + } + } + companion object { const val PRIMARY = "\u0000primary" } +} + +/** Down from this button goes to the first tile of the page's grid, when there is one. */ +@Composable +private fun Modifier.downToFirstTile(): Modifier { + val ff = LocalFrontFocus.current ?: return this + return this.focusProperties { down = if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default } +} + +/** Marks the first tile of the page's grid. */ +@Composable +private fun Modifier.firstTile(): Modifier { + val ff = LocalFrontFocus.current ?: return this + DisposableEffect(Unit) { + ff.firstTileAttached++ + onDispose { ff.firstTileAttached-- } + } + return this.focusRequester(ff.firstTile) +} + +/** Lets the pane come back to this control: it is remembered when focused. */ +@Composable +private fun Modifier.paneItem(id: String): Modifier { + val ff = LocalFrontFocus.current ?: return this + val req = remember(id) { ff.items.getOrPut(id) { FocusRequester() } } + DisposableEffect(id) { + ff.attached[id] = (ff.attached[id] ?: 0) + 1 + onDispose { ff.attached[id] = (ff.attached[id] ?: 1) - 1 } + } + return this.focusRequester(req).onFocusChanged { if (it.isFocused) ff.last = id } +} + +private val LocalFrontFocus = staticCompositionLocalOf { null } + @Composable fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) { + val frontFocus = remember { FrontFocus() } + CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) } +} + +@OptIn(ExperimentalComposeUiApi::class) +@Composable +private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) { var selected by rememberSaveable { mutableStateOf("steam") } + var appToChooseDisplay by remember { mutableStateOf(null) } val colors = MaterialTheme.colorScheme val ctx = LocalContext.current BackHandler(enabled = s.pageKey != null && page != null) { a.onPageBack() } + // Back (and B) from a game or an emulator steps out one level, as its "‹" link does, instead + // of leaving the app: a game -> its emulator (or Steam), an emulator -> Desktop. + BackHandler( + enabled = (s.pageKey == null || page == null) && + (selected.startsWith("app:") || selected.startsWith("emu:") || selected.startsWith("rom:")), + ) { + selected = when { + selected.startsWith("app:") -> "steam" + selected.startsWith("emu:") -> "desktop" + else -> "emu:" + selected.removePrefix("rom:").substringBefore(':') + } + } LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" } remember { Motion.scale = Settings.Global.getFloat(ctx.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f); true } - BoxWithConstraints(modifier = Modifier.fillMaxSize().background(colors.background).systemBarsPadding()) { + var anyFocused by remember { mutableStateOf(false) } + BoxWithConstraints(modifier = Modifier.fillMaxSize().background(colors.background).systemBarsPadding().onFocusChanged { anyFocused = it.hasFocus }) { val wide = maxWidth >= 640.dp val railSelection = when { s.pageKey == "performance" || s.pageKey == "protons" -> "setup" @@ -257,9 +374,66 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () - modifier = if (wide) Modifier.width(236.dp).fillMaxHeight() else Modifier.fillMaxWidth().height(maxHeight * 0.42f), ) } - val content: @Composable (Modifier) -> Unit = { m -> Pane(s, selected, a, page, m) { selected = it } } + // The app opens with the selected rail item focused, so a controller sees where it is. An + // app starts in touch mode, where clickables refuse focus, so leave it first (a touch goes + // straight back to it); a request before the window has focus is dropped, so wait for + // that and retry until it sticks. + val window = LocalWindowInfo.current + val inputMode = LocalInputModeManager.current + LaunchedEffect(Unit) { + snapshotFlow { window.isWindowFocused }.first { it } + repeat(20) { + if (frontFocus.railFocused) return@LaunchedEffect + if (inputMode.inputMode != InputMode.Keyboard) inputMode.requestInputMode(InputMode.Keyboard) + runCatching { frontFocus.railFor(railSelection).requestFocus() } + kotlinx.coroutines.delay(100) + } + } + // A tile or button that opens a page goes away with the page it was on, and focus with it; + // the pad then had nothing to move from (a press landed back on the rail's first item). So + // once the new page is in, a controller lands on its main button. + val inputModeManager = LocalInputModeManager.current + LaunchedEffect(selected, s.pageKey) { + kotlinx.coroutines.delay(450) + if (!anyFocused && inputModeManager.inputMode == InputMode.Keyboard) runCatching { + if (frontFocus.primaryAttached > 0) frontFocus.primary.requestFocus() + else frontFocus.railFor(railSelection).requestFocus() + } + } + val back = if (wide) FocusDirection.Left else FocusDirection.Up + val paneFocus = Modifier + .focusProperties { + enter = { frontFocus.paneEntry() } + exit = { dir -> + if (dir == back) frontFocus.rail[railSelection] ?: FocusRequester.Default else FocusRequester.Default + } + } + .focusGroup() + val content: @Composable (Modifier) -> Unit = { m -> + Pane(s, selected, a, page, m.then(paneFocus), { selected = it }) { app -> + if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null) + else appToChooseDisplay = app + } + } if (wide) Row(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxHeight()) } else Column(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxWidth()) } + + appToChooseDisplay?.let { app -> + val secondaryDisplay = s.secondScreenDisplays.firstOrNull() + ChooseAppDisplayDialog( + app = app, + secondaryDisplay = secondaryDisplay, + onPrimary = { + appToChooseDisplay = null + a.onAndroidApp(app, Display.DEFAULT_DISPLAY) + }, + onSecondary = { + appToChooseDisplay = null + secondaryDisplay?.let { a.onAndroidApp(app, it.id) } + }, + onDismiss = { appToChooseDisplay = null }, + ) + } } } @@ -271,82 +445,89 @@ private fun Rail( ) { val colors = MaterialTheme.colorScheme Column( - modifier = modifier.background(colors.surface).verticalScroll(rememberScrollState()).padding(horizontal = 10.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(2.dp), + modifier = modifier.background(colors.surface).padding(horizontal = 10.dp, vertical = 12.dp), ) { - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 8.dp, bottom = 10.dp)) { - Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(30.dp)) - Spacer(Modifier.width(10.dp)) - Column { - Text("DroidDeck", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) - val status = when { - s.busy -> if (s.percent >= 0) "${s.stage} ${s.percent}%" else s.stage - !s.ready -> "runtime not installed" - s.available != null && s.available != s.installed -> "runtime update available" - else -> null + Column( + modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 8.dp, bottom = 10.dp)) { + Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(30.dp)) + Spacer(Modifier.width(10.dp)) + Column { + Text("DroidDeck", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) + val status = when { + s.busy -> if (s.percent >= 0) "${s.stage} ${s.percent}%" else s.stage + !s.ready -> "runtime not installed" + s.available != null && s.available != s.installed -> "runtime update available" + else -> null + } + if (status != null) Text(status, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) } - if (status != null) Text(status, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) } - } - AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { - LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) - } + AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { + LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) + } - var lastRunning by remember { mutableStateOf("") } - if (s.running != null) lastRunning = s.running - AnimatedVisibility( - s.running != null, - enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)) + slideInVertically(Motion.sp(0.6f)) { -it / 2 }, - exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)), - ) { RunningTile(lastRunning, a.onResume) } + var lastRunning by remember { mutableStateOf("") } + if (s.running != null) lastRunning = s.running + AnimatedVisibility( + s.running != null, + enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)) + slideInVertically(Motion.sp(0.6f)) { -it / 2 }, + exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)), + ) { RunningTile(lastRunning, a.onResume) } - val pal = LocalPalette.current - var navOrigin by remember { mutableStateOf(Offset.Zero) } - val positions = remember { mutableStateMapOf() } - Box(modifier = Modifier.fillMaxWidth().onGloballyPositioned { val o = it.positionInRoot(); if (o != navOrigin) navOrigin = o }) { - val target = positions[selected]?.translate(-navOrigin) - val y by animateFloatAsState(target?.top ?: 0f, Motion.sp(0.72f, Spring.StiffnessLow), label = "indY") - val x by animateFloatAsState(target?.left ?: 0f, Motion.sp(0.9f), label = "indX") - val h by animateFloatAsState(target?.height ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indH") - val w by animateFloatAsState(target?.width ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indW") - val alpha by animateFloatAsState(if (target != null) 1f else 0f, Motion.tw(250), label = "indA") - val density = LocalDensity.current - Box( - modifier = Modifier - .offset { IntOffset(x.roundToInt(), y.roundToInt()) } - .width(with(density) { w.toDp() }).height(with(density) { h.toDp() }) - .alpha(alpha) - .graphicsLayer { shadowElevation = 6.dp.toPx(); shape = Shape10; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal } - .clip(Shape10) - .background(Brush.linearGradient(listOf(colors.primary, pal.primary2))), + val pal = LocalPalette.current + var navOrigin by remember { mutableStateOf(Offset.Zero) } + val positions = remember { mutableStateMapOf() } + Box(modifier = Modifier.fillMaxWidth().onGloballyPositioned { val o = it.positionInRoot(); if (o != navOrigin) navOrigin = o }) { + val target = positions[selected]?.translate(-navOrigin) + val y by animateFloatAsState(target?.top ?: 0f, Motion.sp(0.72f, Spring.StiffnessLow), label = "indY") + val x by animateFloatAsState(target?.left ?: 0f, Motion.sp(0.9f), label = "indX") + val h by animateFloatAsState(target?.height ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indH") + val w by animateFloatAsState(target?.width ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indW") + val alpha by animateFloatAsState(if (target != null) 1f else 0f, Motion.tw(250), label = "indA") + val density = LocalDensity.current + Box( + modifier = Modifier + .offset { IntOffset(x.roundToInt(), y.roundToInt()) } + .width(with(density) { w.toDp() }).height(with(density) { h.toDp() }) + .alpha(alpha) + .graphicsLayer { shadowElevation = 6.dp.toPx(); shape = Shape10; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal } + .clip(Shape10) + .background(Brush.linearGradient(listOf(colors.primary, pal.primary2))), + ) + val register: (String, LayoutCoordinates) -> Unit = { key, c -> + val o = c.positionInRoot(); val r = Rect(o.x, o.y, o.x + c.size.width, o.y + c.size.height) + if (positions[key] != r) positions[key] = r + } + val unregister: (String) -> Unit = { positions.remove(it) } + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + if (s.isHomeApp) { + NavItem("Android apps", "android-apps", selected == "android-apps", count = s.androidApps.size, + register = register, unregister = unregister) { onSelect("android-apps") } + } + NavItem("Steam", "steam", selected == "steam", count = s.steamGames.size, register = register, unregister = unregister) { onSelect("steam") } + NavItem("Desktop", "desktop", selected == "desktop", count = s.emulators.count { it.installed }, register = register, unregister = unregister) { onSelect("desktop") } + NavItem("Setup", "setup", selected == "setup", register = register, unregister = unregister) { onSelect("setup") } + Spacer(Modifier.height(6.dp)) + } + } + + val creditsSrc = remember { MutableInteractionSource() } + val creditsHot = rememberHot(creditsSrc) + Text( + "credits", fontSize = 11.sp, color = if (creditsHot) LocalPalette.current.signal else colors.onSurfaceVariant, + modifier = Modifier.clip(Shape10) + .border(2.dp, if (creditsHot) LocalPalette.current.signal else Color.Transparent, Shape10) + .hoverable(creditsSrc).clickable(interactionSource = creditsSrc, indication = null, onClick = a.onCredits) + .padding(horizontal = 10.dp, vertical = 8.dp), ) - val register: (String, LayoutCoordinates) -> Unit = { key, c -> - val o = c.positionInRoot(); val r = Rect(o.x, o.y, o.x + c.size.width, o.y + c.size.height) - if (positions[key] != r) positions[key] = r - } - val unregister: (String) -> Unit = { positions.remove(it) } - Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) { - if (s.isHomeApp) { - NavItem("Android apps", "android-apps", selected == "android-apps", count = s.androidApps.size, - register = register, unregister = unregister) { onSelect("android-apps") } - } - NavItem("Steam", "steam", selected == "steam", count = s.steamGames.size, register = register, unregister = unregister) { onSelect("steam") } - NavItem("Desktop", "desktop", selected == "desktop", count = s.emulators.count { it.installed }, register = register, unregister = unregister) { onSelect("desktop") } - NavItem("Setup", "setup", selected == "setup", register = register, unregister = unregister) { onSelect("setup") } - Spacer(Modifier.height(6.dp)) - } } - - // Outlined when a controller is on it, like every other control; the ripple alone was - // a faint box on the dark rail. - val creditsSrc = remember { MutableInteractionSource() } - val creditsHot = rememberHot(creditsSrc) - Text( - "credits", fontSize = 11.sp, color = if (creditsHot) LocalPalette.current.signal else colors.onSurfaceVariant, - modifier = Modifier.clip(Shape10) - .border(2.dp, if (creditsHot) LocalPalette.current.signal else Color.Transparent, Shape10) - .hoverable(creditsSrc).clickable(interactionSource = creditsSrc, indication = null, onClick = a.onCredits) - .padding(horizontal = 10.dp, vertical = 8.dp), + BuildStatus( + label = s.buildLabel, + onCheckLatest = a.onCheckLatestBuild, + modifier = Modifier.align(Alignment.Start).padding(start = 8.dp, top = 4.dp, bottom = 2.dp), ) } } @@ -391,6 +572,9 @@ private fun NavItem( val colors = MaterialTheme.colorScheme val src = remember { MutableInteractionSource() } val focused by src.collectIsFocusedAsState() + val frontFocus = if (register != null && key != "x") LocalFrontFocus.current else null + val railRequester = frontFocus?.railFor(key) + if (frontFocus != null) LaunchedEffect(focused) { if (focused) frontFocus.railFocused = true } val hovered by src.collectIsHoveredAsState() val pressed by src.collectIsPressedAsState() val fg by animateColorAsState(if (current) colors.onPrimary else if (muted) colors.onSurfaceVariant else colors.onBackground, Motion.tw(280), label = "navFg") @@ -403,6 +587,7 @@ private fun NavItem( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() .then(if (register != null && key != "x") Modifier.onGloballyPositioned { register(key, it) } else Modifier) + .then(if (railRequester != null) Modifier.focusRequester(railRequester) else Modifier) .then(if (small && i >= 0 && register != null) Modifier.staggerIn(i) else Modifier) .graphicsLayer { scaleX = scale; scaleY = scale } .clip(Shape10) @@ -429,7 +614,10 @@ private fun NavItem( @Composable -private fun Pane(s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier, onSelect: (String) -> Unit) { +private fun Pane( + s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier, + onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit, +) { Box(modifier = modifier) { val wash: Pair = when { s.pageKey != null && page != null -> null to 250f @@ -450,7 +638,48 @@ private fun Pane(s: FrontEndState, selected: String, a: FrontEndActions, page: ( .apply { targetContentZIndex = 1f } }, label = "pane", - ) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect) } + ) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick) } + } +} + +@Composable +private fun BuildStatus(label: String, onCheckLatest: () -> Unit, modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val interaction = remember { MutableInteractionSource() } + val hot = rememberHot(interaction) + val contextDivider = label.indexOf(" · ") + val context = if (contextDivider >= 0) label.substring(0, contextDivider) else "" + val identity = if (contextDivider >= 0) label.substring(contextDivider + 3) else label + val identityDivider = identity.lastIndexOf(" at ") + val branch = (if (identityDivider >= 0) identity.substring(0, identityDivider) else identity).substringAfterLast('/') + val commit = if (identityDivider >= 0) identity.substring(identityDivider + 4) else "" + Column( + verticalArrangement = Arrangement.spacedBy(1.dp), + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(6.dp)) + .semantics { contentDescription = "Build $label. Check for newest build." } + .hoverable(interaction) + .clickable( + interactionSource = interaction, + indication = LocalIndication.current, + role = Role.Button, + onClick = onCheckLatest, + ) + .heightIn(min = 44.dp) + .padding(horizontal = 4.dp, vertical = 3.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + modifier = Modifier.fillMaxWidth(), + ) { + Text(branch, modifier = Modifier.weight(1f), fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = if (hot) colors.onSurfaceVariant else colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis) + if (commit.isNotEmpty()) Text("@$commit", fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1) + Icon(Icons.Filled.Refresh, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.82f), modifier = Modifier.size(12.dp)) + } + if (context.isNotEmpty()) Text(context, fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1) } } @@ -479,7 +708,10 @@ private fun romFor(s: FrontEndState, selected: String): Pair Unit) { +private fun Content( + s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier, + onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit, +) { val colors = MaterialTheme.colorScheme Column(modifier = modifier.padding(horizontal = 22.dp, vertical = 18.dp)) { when { @@ -495,7 +727,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi null, null, "android:${app.packageName}", - onClick = { a.onAndroidApp(app) }, + onClick = { onAndroidAppClick(app) }, iconBitmap = app.icon, ) }) @@ -506,7 +738,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Rise(3) { Actions { // Enabled without a runtime: the session's loading screen installs it first. - PrimaryButton("Play", enabled = !s.busy, onClick = a.onPlay) + PrimaryButton("Play", enabled = !s.busy, main = true, onClick = a.onPlay) SecondaryButton("Steam Desktop UI", enabled = !s.busy, onClick = a.onPlayDesktopUi) Cog(a.onSteamSettings) } @@ -532,7 +764,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Row { Column(modifier = Modifier.weight(1f)) { Actions { - PrimaryButton("Launch", enabled = s.ready && !s.busy) { a.onSteamGame(g) } + PrimaryButton("Launch", enabled = s.ready && !s.busy, main = true) { a.onSteamGame(g) } Cog(a.onSteamSettings) Chip(if (s.ready) "● ready" else "runtime missing", ok = s.ready) } @@ -552,7 +784,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Rise(3) { Actions { // Enabled without a runtime or the desktop: the session's loading screen installs them first. - PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, onClick = a.onDesktop) + PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, main = true, onClick = a.onDesktop) Cog(a.onDesktopSettings) } } @@ -578,7 +810,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Rise(3) { Actions { Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp)) - PrimaryButton("Open ${e.name}", enabled = s.ready && !s.busy) { a.onEmulator(e) } + PrimaryButton("Open ${e.name}", enabled = s.ready && !s.busy, main = true) { a.onEmulator(e) } SecondaryButton("ROMs folder", onClick = a.onRoms) if (pkg != null) SecondaryButton( if (pkg.kind == "appimage") "Remove" else "Forget", @@ -655,7 +887,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Spacer(Modifier.height(14.dp)) Actions { Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp)) - PrimaryButton("Launch in ${e.name}", enabled = s.ready && !s.busy) { a.onRom(g) } + PrimaryButton("Launch in ${e.name}", enabled = s.ready && !s.busy, main = true) { a.onRom(g) } Chip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false) } } @@ -699,12 +931,19 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) { ActionRow("ROMs folder", s.romsDir ?: "Choose where emulator games are stored", "Choose", a.onRoms) } SettingsGroup("Session") { + ChoiceRow( + host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted), + listOf( + false to SessionPrefs.BACK_MENU_THEN_QAM, + true to SessionPrefs.BACK_QAM_THEN_MENU, + ), s.backActionsInverted, onPick = a.onBackActionsInverted, + ) SettingsRow("Frame generation", "Select the frame generation mode") { Box { ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" } - AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { + AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus -> val need = if (s.lsfgReady) null else "Install Lossless Scaling in Steam" - MenuItem("Off", checked = s.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null } + MenuItem("Off", checked = s.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null } for (m in 2..4) MenuItem("Win-FG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_WINFG && s.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null } for (m in 2..4) MenuItem("LSFG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_LSFG && s.frameGenMultiplier == m, enabled = s.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null } } @@ -725,12 +964,24 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) { SettingsRow("Theme", "Choose the launcher appearance") { Box { ValueChip(Themes.byId(s.theme).label, host.open == "theme") { host.open = if (host.open == "theme") null else "theme" } - AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = "Theme") { - for (t in Themes.all) MenuItem(t.label, checked = s.theme == t.id) { a.onTheme(t.id); host.open = null } + AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = "Theme") { firstItemFocus -> + Themes.all.forEachIndexed { index, theme -> + MenuItem(theme.label, checked = s.theme == theme.id, focusRequester = if (index == 0) firstItemFocus else null) { + a.onTheme(theme.id) + host.open = null + } + } } } } - ActionRow("Default Home app", s.defaultHomeLabel ?: "Choose a Home app", "Choose", a.onHomeApp) + ToggleRow( + host, "home-screen", "Use as a Home screen", + if (s.homeScreenEnabled) "DroidDeck can be the phone's Home app" else "Off: DroidDeck is never offered as a Home app", + s.homeScreenEnabled, + ) { a.onHomeScreen(it) } + if (s.homeScreenEnabled) { + ActionRow("Default Home app", s.defaultHomeLabel ?: "Choose a Home app", "Choose", a.onHomeApp) + } } } } @@ -781,9 +1032,16 @@ private fun Chip(t: String, ok: Boolean) { private fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value @Composable -private fun PrimaryButton(text: String, enabled: Boolean = true, onClick: () -> Unit) { +private fun PrimaryButton(text: String, enabled: Boolean = true, main: Boolean = false, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current + // The page's main button is where the pane is entered from the rail. + val frontFocus = if (main) LocalFrontFocus.current else null + if (frontFocus != null) DisposableEffect(Unit) { + frontFocus.primaryAttached++ + onDispose { frontFocus.primaryAttached-- } + } + val track = (if (frontFocus == null) Modifier.paneItem("btn:$text") else Modifier).downToFirstTile() val src = remember { MutableInteractionSource() } val hot = rememberHot(src) && enabled val pressed by src.collectIsPressedAsState() @@ -791,7 +1049,8 @@ private fun PrimaryButton(text: String, enabled: Boolean = true, onClick: () -> val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift") Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier + modifier = track + .then(if (frontFocus != null) Modifier.focusRequester(frontFocus.primary).onFocusChanged { if (it.isFocused) frontFocus.last = FrontFocus.PRIMARY } else Modifier) .graphicsLayer { scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal } .clip(Shape12) .background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant))) @@ -817,9 +1076,10 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, onClick: () 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( - modifier = Modifier.graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12) + modifier = Modifier.paneItem("btn:$text").downToFirstTile().graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12) .alpha(if (enabled) 1f else 0.5f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 16.dp, vertical = 11.dp), ) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) } } @@ -834,7 +1094,7 @@ private fun Cog(onClick: () -> Unit) { val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "cogEdge") Box( contentAlignment = Alignment.Center, - modifier = Modifier.size(42.dp).clip(Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, Shape12) + modifier = Modifier.paneItem("cog").downToFirstTile().size(42.dp).clip(Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, Shape12) .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(18.dp).rotate(rot)) } } @@ -849,7 +1109,7 @@ private fun Poster(art: File?, name: String, modifier: Modifier) { .graphicsLayer { alpha = t.value; translationY = (1f - t.value) * 16.dp.toPx(); rotationZ = (1f - t.value) * 2f; scaleX = 0.94f + 0.06f * t.value; scaleY = scaleX; shadowElevation = 22.dp.toPx(); shape = Shape12; clip = false } .clip(Shape12).background(artBrush(hueOf(name))), ) { - if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + if (art != null) CoverImage(art, Modifier.fillMaxSize()) else Text(name, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.align(Alignment.BottomStart).padding(8.dp), maxLines = 3, overflow = TextOverflow.Ellipsis) } } @@ -875,7 +1135,8 @@ private fun ArtGrid(tiles: List, wide: Boolean = false) { for (t in row) key(t.key) { val src = remember { MutableInteractionSource() } val hot = rememberHot(src) - Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot) } + val track = Modifier.paneItem("tile:" + t.key).then(if (t === tiles.first()) Modifier.firstTile() else Modifier) + Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot, track) } } } } @@ -884,7 +1145,7 @@ private fun ArtGrid(tiles: List, wide: Boolean = false) { } @Composable -private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean) { +private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean, track: Modifier) { val colors = MaterialTheme.colorScheme val pressed by src.collectIsPressedAsState() val scale by animateFloatAsState(if (pressed) 0.97f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "tileScale") @@ -893,7 +1154,7 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera val pal = LocalPalette.current val ring by animateColorAsState(if (hot) pal.signal else Color.Transparent, Motion.tw(220), label = "tileRing") Column( - modifier = Modifier + 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) @@ -921,13 +1182,41 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera } } +/** + * Art for a portrait (2:3) tile. Box art fills it; wide art - a PS3 disc's ICON0, a game's header - + * is shown whole over a blurred, darkened copy of itself instead of losing its sides to the crop. + */ +@Composable +private fun CoverImage(art: File, modifier: Modifier) { + var wideArt by remember(art) { mutableStateOf(false) } + Box(modifier) { + if (wideArt) { + AsyncImage( + model = art, contentDescription = null, contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize().graphicsLayer { scaleX = 1.2f; scaleY = 1.2f }.blur(14.dp), + ) + Spacer(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.45f))) + } + AsyncImage( + model = art, contentDescription = null, + contentScale = if (wideArt) ContentScale.Fit else ContentScale.Crop, + onSuccess = { state -> + val size = state.painter.intrinsicSize + if (size.width > size.height * 1.1f) wideArt = true + }, + modifier = Modifier.fillMaxSize(), + ) + } +} + @Composable private fun Art(art: File?, iconRes: Int?, label: String, modifier: Modifier, wide: Boolean = false, iconBitmap: Bitmap? = null) { val colors = MaterialTheme.colorScheme val ratio = if (art == null && (iconRes != null || iconBitmap != null)) 1f else if (wide) 16f / 9f else 2f / 3f Box(modifier = modifier.aspectRatio(ratio).background(if (art == null && iconRes == null && iconBitmap == null) artBrush(hueOf(label)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surface)))) { when { - art != null -> AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + art != null -> if (wide) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + else CoverImage(art, Modifier.fillMaxSize()) iconRes != null -> Image(painterResource(iconRes), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(if (wide) 10.dp else 8.dp)) iconBitmap != null -> Image(bitmap = iconBitmap.asImageBitmap(), contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(8.dp)) else -> { 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 5fb8fc0e63..f701360206 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt @@ -12,6 +12,34 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.input.SecondScreenDisplay + +@Composable +fun ChooseAppDisplayDialog( + app: HomeApp.LaunchableApp, + secondaryDisplay: SecondScreenDisplay?, + onPrimary: () -> Unit, + onSecondary: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Launch ${app.label}") }, + text = { + Text( + secondaryDisplay?.let { "Choose a screen. Secondary: ${it.label}." } + ?: "The secondary display is no longer available.", + ) + }, + confirmButton = { TextButton(onClick = onPrimary) { Text("Primary screen") } }, + dismissButton = { + TextButton(onClick = onSecondary, enabled = secondaryDisplay != null) { + Text("Secondary screen") + } + }, + ) +} @Composable fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) { 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 7460914bcc..6eb2cc913d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -46,6 +46,8 @@ class ModeSettings( val suspendPolicy: String, /** Steam only. */ val oscMode: String?, + /** Steam only: whether single and double Back actions are swapped. */ + val backActionsInverted: Boolean = false, val directAudio: Boolean?, val clientDirectAudio: Boolean = false, val mic: Boolean?, @@ -53,6 +55,8 @@ class ModeSettings( val gameStorage: String? = null, val storageOptions: List> = emptyList(), val fexPreset: String? = null, + /** Steam only: games are stretched to fill the screen (null = not a Steam page). */ + val forceFullscreen: Boolean? = null, /** Steam only: the client branch forced on the command line. */ val steamChannel: String? = null, /** Steam only: the user's own games folder and what was found in it. */ @@ -91,6 +95,7 @@ class ModeSettingsActions( val onTouch: (String) -> Unit, val onSuspendPolicy: (String) -> Unit, val onOsc: (String) -> Unit, + val onBackActionsInverted: (Boolean) -> Unit = {}, val onDirectAudio: (Boolean) -> Unit, val onClientDirectAudio: (Boolean) -> Unit = {}, val onMic: (Boolean) -> Unit, @@ -98,6 +103,7 @@ class ModeSettingsActions( val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> }, val onPickGameStorageFolder: () -> Unit = {}, val onFexPreset: (String) -> Unit = {}, + val onForceFullscreen: (Boolean) -> Unit = {}, val onSteamChannel: (String) -> Unit = {}, val onPickAddedGamesDir: () -> Unit = {}, val onForgetAddedGamesDir: (path: String) -> Unit = {}, @@ -177,8 +183,8 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { onPick = { v -> if (v == CUSTOM) editCustom = true else { a.onCustomResolution(null); a.onResolution(v) } }, ) ChoiceRow( - host, "shape", "Shape", - if (custom != null) "Set by the custom resolution." else "The panel's shape stays at 16:9 or wider; pick Exactly this panel for a 4:3 or 3:2 screen.", + host, "shape", "Screen ratio", + 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, ) if (editCustom) CustomResolutionDialog( @@ -226,6 +232,13 @@ 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) ChoiceRow( + host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted), + listOf( + false to SessionPrefs.BACK_MENU_THEN_QAM, + true to SessionPrefs.BACK_QAM_THEN_MENU, + ), s.backActionsInverted, onPick = a.onBackActionsInverted, + ) } SettingsGroup("Session") { ChoiceRow( @@ -280,6 +293,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { FexPreset.all.map { it.id to it.label }, s.fexPreset, note = FexPreset.byId(s.fexPreset).detail, onPick = a.onFexPreset, ) + 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.", + s.forceFullscreen, onChange = a.onForceFullscreen, + ) } if (steam && s.directAudio != null && s.mic != null) SettingsGroup("Audio") { ToggleRow(host, "da", "DirectAudio for games", "Bypasses PulseAudio for lower latency in games.", s.directAudio, onChange = a.onDirectAudio) @@ -309,10 +327,12 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { AnchoredMenu( open, onDismiss = { if (host.open == "storage") host.open = null }, title = "Second library", note = "Games that stream assets from SD or shared storage may stutter. Keep them internal.", - ) { - for ((path, label) in options) MenuItem(label, checked = path == s.gameStorage) { - a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·")) - host.open = null + ) { firstItemFocus -> + options.forEachIndexed { index, (path, label) -> + MenuItem(label, checked = path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) { + a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·")) + host.open = null + } } MenuItem("Choose a folder…", checked = false) { host.open = null; a.onPickGameStorageFolder() } } 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 818d72624d..3a4bdb2ef6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -44,6 +44,7 @@ class SecondScreenPresentation( private val sendWheel: (steps: Int) -> Unit, private val onSteamMenu: () -> Unit, private val onQam: () -> Unit, + private val onClose: () -> Unit, ) : Presentation(sessionActivity, display) { private val root = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL @@ -124,6 +125,12 @@ class SecondScreenPresentation( setPadding(dp(12), dp(8), dp(12), dp(8)) setBackgroundColor(0xE6191E24.toInt()) } + controls.addView(Button(context).apply { + text = "×" + contentDescription = "Close second-screen controls" + minWidth = dp(48) + setOnClickListener { onClose() } + }) controls.addView(TextView(context).apply { text = "Trackpad" textSize = 14f @@ -169,6 +176,12 @@ class SecondScreenPresentation( setPadding(dp(8), dp(4), dp(8), dp(4)) setBackgroundColor(Color.rgb(27, 32, 38)) } + bar.addView(Button(context).apply { + text = "×" + contentDescription = "Close second-screen controls" + minWidth = dp(48) + setOnClickListener { onClose() } + }) bar.addView(TextView(context).apply { text = "Linux terminal" textSize = 14f 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 0aaf1fc7d6..db5d83889a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -1,14 +1,17 @@ package com.droiddeck.launcher.ui +import android.view.Display +import androidx.activity.compose.BackHandler import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusGroup import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.ui.focus.focusRequester import androidx.compose.material3.ButtonDefaults import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -20,16 +23,18 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.ScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Switch +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 +import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap @@ -62,11 +67,18 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Brush 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.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow import com.droiddeck.launcher.core.FexPreset import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.session.SessionPrefs @@ -74,6 +86,29 @@ import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenMode import kotlinx.coroutines.flow.collect +private val drawerPageTitles = listOf("Now", "Controls", "Session") +private val drawerPageEntries = listOf("hud", "touch", "shape") + +private class DrawerFocus { + private val requesters = HashMap() + private val last = arrayOfNulls(3) + var focused by mutableStateOf(null) + private set + + private fun requester(key: String) = requesters.getOrPut(key) { FocusRequester() } + + fun track(page: Int, key: String): Modifier = Modifier.focusRequester(requester(key)).onFocusChanged { + if (it.isFocused) { + last[page] = key + focused = key + } else if (focused == key) focused = null + } + + fun target(page: Int) = last[page] ?: drawerPageEntries[page] + fun request(key: String) = runCatching { requester(key).requestFocus() } + fun forget(page: Int) { last[page] = null } +} + @Composable fun HudText(text: String) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopEnd) { @@ -121,6 +156,11 @@ fun LoadingOverlay(step: String, percent: Int, elapsed: String, hint: String, en @Composable fun SessionPausedOverlay(onResume: () -> Unit) { val interactionSource = remember { MutableInteractionSource() } + val resumeFocus = remember { FocusRequester() } + LaunchedEffect(Unit) { + androidx.compose.runtime.withFrameNanos { } + runCatching { resumeFocus.requestFocus() } + } Box( modifier = Modifier .fillMaxSize() @@ -132,7 +172,10 @@ fun SessionPausedOverlay(onResume: () -> Unit) { horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(32.dp), ) { - OutlinedButton(onClick = onResume) { + OutlinedButton( + onClick = onResume, + modifier = Modifier.focusRequester(resumeFocus).controllerConfirm(onClick = onResume), + ) { Text("Resume session") } } @@ -142,6 +185,8 @@ fun SessionPausedOverlay(onResume: () -> Unit) { /** Everything the drawer shows and does. */ class DrawerActions( val steam: Boolean, + /** The drawer's heading: the emulator for a program from the rail, else Steam or Desktop. */ + val title: String? = null, val isHomeApp: Boolean, val androidApps: List, val hudOn: Boolean, @@ -149,10 +194,13 @@ class DrawerActions( val frameGenMultiplier: Int, val lsfgReady: Boolean, val oscMode: String, + val backActionsInverted: Boolean, val touchMode: String, val touchAuto: String, val shapeMode: String, val fexPreset: String, + /** Steam only: games stretched to the screen's size, changed live (null = not Steam). */ + val fillScreen: Boolean? = null, val secondScreenMode: SecondScreenMode, val secondScreenDisplays: List, val selectedSecondScreenDisplay: Int, @@ -165,32 +213,56 @@ class DrawerActions( val onSteamMenu: (() -> Unit)?, val onQam: (() -> Unit)?, val onOsc: (String) -> Unit, + val onBackActionsInverted: (Boolean) -> Unit, val onTouch: (String) -> Unit, val onShape: (String) -> Unit, val onFexPreset: (String) -> Unit, + val onFillScreen: (Boolean) -> Unit = {}, val onSecondScreenMode: (SecondScreenMode) -> Unit, val onSecondScreenDisplay: (Int) -> Unit, - val onLaunchAndroidApp: (HomeApp.LaunchableApp) -> Unit, + val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit, val onBackground: () -> Unit, val onStop: () -> Unit, val onClose: () -> Unit, ) +@OptIn(ExperimentalComposeUiApi::class) @Composable -fun SessionDrawer(open: Boolean, a: DrawerActions) { +fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageChange: (Int) -> Unit, a: DrawerActions) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val host = rememberMenuHost() var androidAppsExpanded by rememberSaveable { mutableStateOf(false) } + var appToChooseDisplay by remember { mutableStateOf(null) } + var confirmStop by remember { mutableStateOf(false) } + val pageScroll = remember { List(3) { ScrollState(0) } } val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil") - // A controller starts on the drawer's first control, highlighted, as on the app's main screen: - // the STEAM button, or in a desktop session the first setting. - val firstFocus = remember { androidx.compose.ui.focus.FocusRequester() } - val steamButtons = a.onSteamMenu != null && a.onQam != null - LaunchedEffect(open) { - if (open) { - androidx.compose.runtime.withFrameNanos { } - runCatching { firstFocus.requestFocus() } + val focus = remember { DrawerFocus() } + val inputModeManager = LocalInputModeManager.current + val focusManager = LocalFocusManager.current + BackHandler(enabled = open) { + if (host.open != null) host.open = null else a.onClose() + } + BackHandler(enabled = open && confirmStop) { confirmStop = false } + LaunchedEffect(page) { host.open = null; appToChooseDisplay = null } + LaunchedEffect(open, controllerActive) { + if (open && !controllerActive) focusManager.clearFocus(force = true) + } + LaunchedEffect(open, page, controllerActive, host.open, appToChooseDisplay, confirmStop) { + if (!open) { + host.open = null + confirmStop = false + } else if (controllerActive) { + inputModeManager.requestInputMode(InputMode.Keyboard) + if (host.open != null || appToChooseDisplay != null || confirmStop) return@LaunchedEffect + val target = focus.target(page) + repeat(24) { + androidx.compose.runtime.withFrameNanos { } + focus.request(target) + if (focus.focused == target) return@LaunchedEffect + } + focus.forget(page) + focus.request(drawerPageEntries[page]) } } if (open || veil > 0.01f) Box( @@ -209,13 +281,18 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { .width(340.dp) .background(pal.background.copy(alpha = 0.97f)) .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} - .verticalScroll(rememberScrollState()) + .focusGroup() + .controllerBack { + if (host.open != null) host.open = null else a.onClose() + } .padding(horizontal = 14.dp, vertical = 16.dp), ) { - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 4.dp, bottom = 6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 4.dp, bottom = 6.dp)) { Box(modifier = Modifier.size(10.dp).clip(CircleShape).background(Brush.linearGradient(listOf(colors.primary, pal.primary2)))) Spacer(Modifier.width(10.dp)) - Text(if (a.steam) "Steam" else "Desktop", fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) + Text(a.title ?: if (a.steam) "Steam" else "Desktop", fontSize = 17.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 } } if (a.onSteamMenu != null && a.onQam != null) { val qamInteraction = remember { MutableInteractionSource() } @@ -239,7 +316,10 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { OutlinedButton( onClick = { host.open = null; a.onSteamMenu.invoke() }, interactionSource = steamSrc, - modifier = Modifier.weight(1f).height(48.dp).focusRequester(firstFocus), + modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "steam")).controllerConfirm { + host.open = null + a.onSteamMenu.invoke() + }, shape = RoundedCornerShape(12.dp), border = BorderStroke(if (steamHot) 2.dp else 1.dp, if (steamHot) pal.signal else colors.outline), colors = ButtonDefaults.outlinedButtonColors(containerColor = if (steamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent), @@ -253,133 +333,241 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { qamStartedOnPress = false }, interactionSource = qamInteraction, - modifier = Modifier.weight(1f).height(48.dp).semantics { contentDescription = "Open Quick Access Menu" }, + modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "qam")) + .semantics { contentDescription = "Open Quick Access Menu" }.controllerConfirm { + host.open = null + a.onQam.invoke() + }, shape = RoundedCornerShape(12.dp), border = BorderStroke(if (qamHot) 2.dp else 1.dp, if (qamHot) pal.signal else colors.outline), colors = ButtonDefaults.outlinedButtonColors(containerColor = if (qamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent), ) { - Text("…", fontSize = 22.sp, fontWeight = FontWeight.SemiBold) + Text("QAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp) } } } - if (a.isHomeApp) SettingsGroup("Android apps") { - ActionRow("Launch an app", null, if (androidAppsExpanded) "Hide" else "Show") { - androidAppsExpanded = !androidAppsExpanded - } - if (androidAppsExpanded) { - if (a.androidApps.isEmpty()) { - Text("No launchable apps found", fontSize = 12.sp, color = colors.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) - } else { - for (app in a.androidApps) { - MenuItem( - app.label, - checked = false, - leading = { - app.icon?.let { icon -> - Image( - bitmap = icon.asImageBitmap(), - contentDescription = null, - modifier = Modifier.size(26.dp).clip(RoundedCornerShape(6.dp)), - ) - } - }, - ) { a.onLaunchAndroidApp(app) } - } - } - } - } - - SettingsGroup("Now") { - ToggleRow( - host, "hud", "Performance HUD", null, a.hudOn, - chipModifier = if (steamButtons) Modifier else Modifier.focusRequester(firstFocus), onChange = a.onHud, - ) - val fgOpen = host.open == "fg" - val fgLabel = when (a.frameGenEngine) { - FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×" - FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×" - else -> "Off" - } - SettingsRow("Frame generation", null, highlighted = fgOpen) { - Box { - ValueChip(fgLabel, fgOpen) { host.open = if (fgOpen) null else "fg" } - AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { - val need = if (a.lsfgReady) null else "install Lossless Scaling in Steam" - MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null } - for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null } - for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null } - } - } - } - ChoiceRow( - host, "touch", "Touch", null, - listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"), a.touchMode, - onPick = a.onTouch, - ) - if (a.steam) ChoiceRow( - host, "osc", "On-screen controls", null, - listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never"), a.oscMode, - onPick = a.onOsc, - ) - SettingsRow("Keyboard", null) { - Row(verticalAlignment = Alignment.CenterVertically) { - SecondaryButton("Hardware") { host.open = null; a.onHardwareKeyboard() } - Spacer(Modifier.width(8.dp)) - SecondaryButton("Android") { host.open = null; a.onKeyboard() } - } - } - } - - if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") { - ChoiceRow( - host, "second-screen-mode", "Controls", null, - listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) - .map { it to it.label }, a.secondScreenMode, - 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, - onPick = a.onSecondScreenDisplay, - ) - } - - SettingsGroup("Next session") { - ChoiceRow( - host, "shape", "Display shape", null, - SessionPrefs.shapeChoices, a.shapeMode, onPick = a.onShape, - ) - if (a.steam) ChoiceRow( - host, "fex", "FEX preset", null, - FexPreset.all.map { it.id to it.label }, a.fexPreset, note = FexPreset.byId(a.fexPreset).detail, onPick = a.onFexPreset, - ) - } - - Spacer(Modifier.height(18.dp)) Row( - horizontalArrangement = if (a.isHomeApp) Arrangement.End else Arrangement.spacedBy(10.dp), - modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), ) { - if (!a.isHomeApp) SecondaryButton("Send to background") { host.open = null; a.onBackground() } - DangerButton("Stop session") { host.open = null; a.onStop() } + DrawerOutlineButton("LB ‹", modifier = Modifier.height(48.dp).then(focus.track(page, "prev"))) { + host.open = null; onPageChange((page + 2) % 3) + } + Row( + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f), + ) { + drawerPageTitles.forEachIndexed { index, title -> + val dotSource = remember { MutableInteractionSource() } + val dotFocused = dotSource.collectIsFocusedAsState().value + val select = { host.open = null; onPageChange(index) } + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.size(38.dp) + .semantics { contentDescription = "$title page" } + .hoverable(dotSource) + .clickable(interactionSource = dotSource, indication = LocalIndication.current, onClick = select) + .controllerConfirm(onClick = select), + ) { + Box( + Modifier.size(if (index == page) 16.dp else 10.dp) + .clip(CircleShape) + .background(if (index == page) pal.signal else colors.onSurfaceVariant) + .border(if (dotFocused) 2.dp else 0.dp, colors.onBackground, CircleShape), + ) + } + } + } + DrawerOutlineButton("› RB", modifier = Modifier.height(48.dp).then(focus.track(page, "next"))) { + host.open = null; onPageChange((page + 1) % 3) + } + } + + Column( + modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll[page]), + ) { + when (page) { + 0 -> SettingsGroup("Now") { + ToggleRow(host, "hud", "Performance HUD", null, a.hudOn, + chipModifier = focus.track(page, "hud"), onChange = a.onHud) + if (a.fillScreen != null) ToggleRow( + host, "fill", "Stretch games to fill", null, a.fillScreen, + chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen, + ) + val fgOpen = host.open == "fg" + val fgLabel = when (a.frameGenEngine) { + FrameGen.ENGINE_WINFG -> "Win-FG ${a.frameGenMultiplier}×" + FrameGen.ENGINE_LSFG -> "LSFG ${a.frameGenMultiplier}×" + else -> "Off" + } + SettingsRow("Frame generation", null, highlighted = fgOpen) { + Box { + ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" } + AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus -> + val need = if (a.lsfgReady) null else "Requires Lossless Scaling" + MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null } + for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null } + for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null } + } + } + } + } + 1 -> { + SettingsGroup("Controls") { + ChoiceRow(host, "touch", "Touch", null, + listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"), + a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch) + ChoiceRow(host, "osc", "On-screen controls", null, + if (a.steam) listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never") + else listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_NEVER to "Never"), + a.oscMode, chipModifier = focus.track(page, "osc"), onPick = a.onOsc) + if (a.steam) ChoiceRow(host, "back-actions", "Back", null, + listOf(false to SessionPrefs.BACK_MENU_THEN_QAM, true to SessionPrefs.BACK_QAM_THEN_MENU), + a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted) + } + SettingsGroup("Keyboard") { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) { + DrawerOutlineButton("Hardware", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "hardware"))) { + host.open = null; a.onHardwareKeyboard() + } + DrawerOutlineButton("Android", modifier = Modifier.weight(1f).height(42.dp).then(focus.track(page, "android"))) { + host.open = null; a.onKeyboard() + } + } + } + if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") { + ChoiceRow(host, "second-screen-mode", "Controls", null, + listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL).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, + chipModifier = focus.track(page, "second-screen-display"), onPick = a.onSecondScreenDisplay) + } + } + else -> { + if (a.isHomeApp) SettingsGroup("Android apps") { + SettingsRow("Launch an app", null) { + DrawerOutlineButton(if (androidAppsExpanded) "Hide" else "Show", modifier = focus.track(page, "apps")) { + androidAppsExpanded = !androidAppsExpanded + } + } + if (androidAppsExpanded) { + if (a.androidApps.isEmpty()) { + Text("No launchable apps", fontSize = 12.sp, color = colors.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) + } else for (app in a.androidApps) { + MenuItem( + app.label, checked = false, + modifier = focus.track(page, "app:${app.packageName}/${app.className}"), + leading = { + app.icon?.let { icon -> + Image(bitmap = icon.asImageBitmap(), contentDescription = null, + modifier = Modifier.size(26.dp).clip(RoundedCornerShape(6.dp))) + } + }, + ) { + host.open = null + if (a.secondScreenDisplays.isEmpty()) a.onLaunchAndroidApp(app, null) + else appToChooseDisplay = app + } + } + } + } + SettingsGroup("Next session") { + 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, + chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset) + } + Spacer(Modifier.height(18.dp)) + if (!a.isHomeApp) DrawerOutlineButton("Background", modifier = focus.track(page, "background")) { + host.open = null; a.onBackground() + } + } + } } - Spacer(Modifier.height(12.dp)) } } } + + appToChooseDisplay?.let { app -> + val secondaryDisplay = a.secondScreenDisplays.firstOrNull { it.id == a.selectedSecondScreenDisplay } + ?: a.secondScreenDisplays.firstOrNull() + ChooseAppDisplayDialog( + app = app, + secondaryDisplay = secondaryDisplay, + onPrimary = { + appToChooseDisplay = null + a.onLaunchAndroidApp(app, Display.DEFAULT_DISPLAY) + }, + onSecondary = { + appToChooseDisplay = null + secondaryDisplay?.let { a.onLaunchAndroidApp(app, it.id) } + }, + 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 -private fun DangerButton(text: String, onClick: () -> Unit) { +private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val source = remember { MutableInteractionSource() } + val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value + OutlinedButton( + onClick = onClick, + interactionSource = source, + modifier = modifier.controllerConfirm(onClick = onClick), + shape = RoundedCornerShape(12.dp), + contentPadding = PaddingValues(horizontal = 12.dp), + border = BorderStroke(if (hot) 2.dp else 1.dp, if (hot) pal.signal else colors.outline), + colors = ButtonDefaults.outlinedButtonColors(containerColor = if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent), + ) { Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1) } +} + +@Composable +private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill") Box( - modifier = Modifier.clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp)) + contentAlignment = Alignment.Center, + modifier = modifier.size(42.dp).semantics { contentDescription = "Stop session" } + .clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp)) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) - .padding(horizontal = 16.dp, vertical = 11.dp), - ) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.error, maxLines = 1) } + .controllerConfirm(onClick = onClick), + ) { Text("×", fontSize = 25.sp, fontWeight = FontWeight.Medium, color = colors.error) } } 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 da7fd678db..981440b836 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import android.view.KeyEvent import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState @@ -39,6 +40,7 @@ import androidx.compose.foundation.verticalScroll 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.mutableStateOf import androidx.compose.runtime.remember @@ -49,10 +51,15 @@ import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.draw.shadow +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.InputMode import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset @@ -69,6 +76,26 @@ import androidx.compose.ui.window.PopupProperties private val RowShape = RoundedCornerShape(12.dp) private val GroupShape = RoundedCornerShape(14.dp) +internal fun Modifier.controllerConfirm(enabled: Boolean = true, onClick: () -> Unit): Modifier = onPreviewKeyEvent { event -> + val keyEvent = event.nativeKeyEvent + if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_A) { + false + } else { + if (enabled && keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) onClick() + true + } +} + +internal fun Modifier.controllerBack(onBack: () -> Unit): Modifier = onPreviewKeyEvent { event -> + val keyEvent = event.nativeKeyEvent + if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_B && keyEvent.keyCode != KeyEvent.KEYCODE_BACK) { + false + } else { + if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) onBack() + true + } +} + class MenuHost { var open by mutableStateOf(null) } @@ -88,10 +115,19 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider { } @Composable -fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.() -> Unit) { +fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.(FocusRequester) -> Unit) { val state = remember { MutableTransitionState(false) } state.targetState = open if (!state.currentState && !state.targetState && state.isIdle) return + val firstItemFocus = remember { FocusRequester() } + val inputMode = LocalInputModeManager.current.inputMode + LaunchedEffect(open, inputMode) { + if (open && inputMode == InputMode.Keyboard) { + repeat(2) { androidx.compose.runtime.withFrameNanos { } } + runCatching { firstItemFocus.requestFocus() } + android.util.Log.i("AnchoredMenu", "requested first option focus") + } + } val gap = with(LocalDensity.current) { 6.dp.roundToPx() } val provider = remember(gap) { BelowEndProvider(gap) } val colors = MaterialTheme.colorScheme @@ -114,13 +150,14 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no .clip(RowShape) .background(pal.surfaceVariant.copy(alpha = 0.95f)) .border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape) + .controllerBack(onDismiss) .padding(6.dp), ) { if (title != null) Text( title.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 6.dp), ) - Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content() } + Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content(firstItemFocus) } if (note != null) { Spacer(Modifier.height(4.dp)) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) @@ -134,7 +171,8 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no @Composable fun MenuItem( label: String, checked: Boolean, enabled: Boolean = true, detail: String? = null, - trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit, + trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null, + focusRequester: FocusRequester? = null, modifier: Modifier = Modifier, onClick: () -> Unit, ) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -143,12 +181,14 @@ fun MenuItem( val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift") Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth() + modifier = modifier.fillMaxWidth() .graphicsLayer { translationX = shift.dp.toPx() } + .then(focusRequester?.let { Modifier.focusRequester(it) } ?: Modifier) .clip(RoundedCornerShape(8.dp)) .background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent) .alpha(if (enabled) 1f else 0.4f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 10.dp, vertical = 9.dp), ) { Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f)) @@ -181,6 +221,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo .border(1.dp, edge, RoundedCornerShape(10.dp)) .alpha(if (enabled) 1f else 0.5f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) { AnimatedContent( @@ -234,8 +275,13 @@ fun ChoiceRow( SettingsRow(label, hint, highlighted = open) { Box { ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier) { host.open = if (open) null else key } - AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { - for ((value, text) in options) MenuItem(text, checked = value == selected) { onPick(value); host.open = null } + AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus -> + options.forEachIndexed { index, (value, text) -> + MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) { + onPick(value) + host.open = null + } + } } } } @@ -260,10 +306,10 @@ fun MultiRow( SettingsRow(label, hint, highlighted = open) { Box { ValueChip(summary, open, enabled) { host.open = if (open) null else key } - AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { - for ((value, text) in items) { + AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus -> + items.forEachIndexed { index, (value, text) -> val on = value in selected - MenuItem(text, checked = on) { onToggle(value, !on) } + MenuItem(text, checked = on, focusRequester = if (index == 0) firstItemFocus else null) { onToggle(value, !on) } } } } 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 52afd790f0..b9b2eb5d15 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -169,6 +169,8 @@ public final class WaylandCompositor { * action: 0=down, 1=move, 2=up. x/y in compositor output space (0..1919, 0..1079). */ public static native void nativeSendPointer(int action, int x, int y); + public static native void nativeSendTouch(int action, int pointerId, int x, int y); + /** Inject a key event. evdev = Linux input keycode (KEY_A=30…); state: 1=down, 0=up. */ public static native void nativeSendKey(int evdev, int state); diff --git a/app/src/main/res/drawable-nodpi/logo.png b/app/src/main/res/drawable-nodpi/logo.png index 936dba3bd4..a9c737a397 100644 Binary files a/app/src/main/res/drawable-nodpi/logo.png and b/app/src/main/res/drawable-nodpi/logo.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_background.png b/app/src/main/res/mipmap-hdpi/ic_launcher_background.png index 4d43523810..8538bed392 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-hdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png index 70d64c0ed6..6998da4247 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_background.png b/app/src/main/res/mipmap-mdpi/ic_launcher_background.png index adcd0243a0..a92ccfafbb 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-mdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png index 29b8eaef83..a9a5f33dc0 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png index 1ef58344be..3ba37c9e97 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png index 9eb6b35a8c..98c616ee8c 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png index abac9697ec..07f6de5a9b 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png index 8fdd7a8b24..35a8ddbbcb 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png index 8ab6e6ea4c..5ae3008fea 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png index 7e9120421c..91ae0e397b 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/artwork/README.md b/artwork/README.md new file mode 100644 index 0000000000..9379fc54f6 --- /dev/null +++ b/artwork/README.md @@ -0,0 +1,5 @@ +# DroidDeck mark + +`droiddeck-mark.svg` is the editable source for the split-D mark. The blue orb is `#1A9FFF`; its halo and the two separator bars are transparent cutouts. The bars are centered on x=63.97, the endpoint of the curved half in the original Steam Deck symbol, and use the halo's 15.83-unit thickness. The mark is optically centered in its view box with a small rightward offset to balance its asymmetric silhouette. + +Android currently consumes raster resources for the launcher layers and the Compose logo. The `mipmap-*/ic_launcher_foreground.png` files are density-sized exports of the SVG, with the mark kept inside the adaptive icon safe area. The matching backgrounds are white. `drawable-nodpi/logo.png` composes the same mark on a white circular badge for use on the app's dark surfaces. diff --git a/artwork/droiddeck-mark.svg b/artwork/droiddeck-mark.svg new file mode 100644 index 0000000000..6b071bde25 --- /dev/null +++ b/artwork/droiddeck-mark.svg @@ -0,0 +1,13 @@ + + DroidDeck split D with a circular orb halo and solid blue orb + + + + + + + + + + + diff --git a/docs/progress-log.md b/docs/progress-log.md index 751ecfb86d..9109c676b6 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -7,6 +7,77 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d --- +## 2026-09-24 (afternoon) - main `94f9935`: PS1, controller focus, own signing key, CI hardening + +State: **main = `94f9935`** (PR #41 merge), main build run 36036219740 - the first one signed with +DroidDeck's own key (`droiddeck-signed-standard`). No tag, no release since 0.1.6. Device-tested on +the AYANEO Pocket FIT unless marked. **main is now protected** (below). + +- **PR #34 → `63d7051`, PR #38 → `c7998a8`** (`feat/duckstation`, `feat/duckstation-play`) - PS1 and the front end: + - **DuckStation like ARMSX2**: Player 1 on the controller, BIOS from `ROMs/psx/bios`, `psx` as the game + list, Vulkan, guide → pause menu, `-batch -bigpicture -fullscreen` from the rail. Crash Bandicoot and + Tekken 3 at 60 fps from the desktop and from the front end. + - **One tap to play**: DuckStation's and ARMSX2's first-time setup is answered for the user + (`SetupWizardIncomplete = false`); ARMSX2 names its BIOS dump itself (`[Filenames] BIOS`, a US dump + first, re-checked before every launch) - PCSX2 needs a named file, DuckStation finds one in its folder. + DuckStation no longer warns it cannot inhibit a screensaver (no `org.freedesktop.ScreenSaver` here). + - **One tile per disc**: a `.cue`/`.gdi`/`.m3u` hides the files it names (Tekken 3 showed 4×, one per + `(Track N).bin`); `bios`/`firmware` folders are skipped (the BIOS showed as a game). + - **Controller focus**: the rail item is outlined on open (an app starts in touch mode, where clickables + refuse focus - the app now asks for keyboard mode first); Right enters a page on its main button, + Left from the page's edge returns to the rail, Right again returns to the tile or button last used + (explicit tracking - `FocusRequester.saveFocusedChild` restored into the grid, not the tile); a page + opened from a tile takes focus on its main button (focus used to vanish with the tile and the next + press landed on Steam); Down from a page's buttons goes to the first tile. +- **PR #41 → `94f9935`** (`feat/release-signing`) - signing, file access, hardening before going public: + - **Own signing key** (RSA 4096, made on device by `tools/release/make-release-key.sh`, digest + `b241ea7d…5d3f0` in `keystore/release-signer.sha256`). Every build before it - 0.1.6 included - was + signed with the public AOSP testkey, so anyone could sign an "update" that installs over DroidDeck. + - **Hand-over** (APK Signature Scheme v3 rotation): v1/v2 by the testkey, v3 by our key with a lineage + testkey → ours, testkey rollback off, `--rotation-min-sdk-version 28`. Proven on the FIT with a throwaway + key and package: a 0.1.6-style install updates and keeps its data; an apk signed with the testkey alone + is refused; so is one with an attacker's own lineage from the testkey; an apk signed with our key alone + (what MT Manager / APK Tool M make) installs over a hand-over install and fresh, not over a testkey one. + - **CI**: `sign.yml` (reusable, a matrix job per package) runs after every non-pull-request build + (environment `signing-main` on main, `signing-branch` elsewhere; the key is an environment secret). + `release.yml` (dispatch, version) signs the exact Build APK artifact of a main commit as four packages: + `com.droiddeck.launcher`, `com.tencent.ig`, `com.antutu.benchmark.full`, `com.ludashi.benchmark` + (`tools/release/variants.txt`; the manifest rename also covers `.documents` and the `.home` task affinity). + - **Documents provider** (`files/AppFilesProvider.kt`): the app's data folder in Android's file picker + ("Open from" → DroidDeck, per-package title), confined to the data folder (a `../` id is refused, links + out of it are hidden), and deleting never follows a link. + - **Hardening**: pull requests build with `pull_request`, not `pull_request_target` (a pull request could + write the caches main's signed builds restore); a build fails if a private key file is committed; + `.gitignore` covers key files; **main is protected** - pull request + passing `build` + one approval, + no force-push or deletion, the owner can override for his own pull requests. History scanned before + going public: no secrets. + - Max and Kurt get the key (jks, p12, pk8 + x509.pem, lineage) with a password and three plain guides + (MT Manager / APK Tool M signing, the hand-over, how pull requests / test builds / releases work). +- **Also merged today** (Kurt): #20 Back shortcuts (session menu, Steam QAM), #24 build identity on the + launcher, #33 per-launch Android display choice, #35 CI build-cleanliness snapshot, #37 the split-D logo, + #40 faster held-stick navigation in the session drawer; (The412Banner) #32 stretch games to fill the + screen, Quake-engine titles windowed at the session's size. + +## 2026-09-24 - main `08a6769`: GPU desktop, emulators like PS3, ARMSX2, game art + +State: **main = `08a6769`** (PR #29 merge), main build run 35983098806, staged as `Download/DroidDeck-main-08a6769(-Genshin).apk`. No tag, no release since 0.1.6. **Device-tested on the AYANEO Pocket FIT** (Adreno 750) unless marked. + +- **PR #25 → `f6f7470`** (`feat/desktop-gpu`) - the desktop on the GPU: + - **Patched wlroots** (`tools/wlroots`, release `wlroots-0.20.2-p1`, staged at `/usr/local/lib/droiddeck-wlroots`): a Vulkan DMA-BUF allocator for the KGSL stand-in node, which is not a DRM device - stock wlroots failed at `drmModeCreateLease` → "unable to create allocator"; linux-dmabuf skips its GEM import check on such a node. labwc's **vulkan** and **gles2** renderers start; **vulkan is the default**. + - Compositor: a toplevel's **initial commit is answered with a configure** (labwc on vulkan waited for ever - wlroots moves its toplevel to a private queue after that commit); **`xdg_positioner` / `xdg_popup` / `wl_output` requests no longer abort** the app (NULL implementations; a gamescope beside labwc took the app down); without a Wine desktop a new window takes the keys. + - Fallback: labwc that exits or does not answer its socket within 20 s → pixman, remembered per renderer + wlroots md5 + driver (`~/.droiddeck-renderer-failed`, cleared by choosing a renderer). On pixman, Game/Emulator menu entries run through `droiddeck-gpu` (their own gamescope on wayland-0). + - Emulators: the pad is a plain Xbox 360 controller outside Steam (SDL ignores Steam's virtual gamepad outside Steam); `bannerlator-pad-defaults` seeds Player 1 per emulator (source-verified formats) and never overwrites a user's profile; big-core pinning (`program_cores`, game cores when chosen); rail programs use the desktop's Linux driver (one shader cache); RPCS3 moved once to `Async Recompiler (multi-threaded)` (no 6650-variant interpreter precompile each boot). + - **PC keyboard** (drawer: Keyboard [Hardware] [Android]): Esc, F1-F12, editing block, modifiers (sticky), arrows; real evdev key presses; 47% of the screen. + - Proven: Vulkan and gles2 desktops, Firefox on Vulkan, RPCS3 God of War II HD in a window and from the rail (pad bound, no precompile, cores 2-7), pixman fallback path, Steam session. +- **PR #26 → `6980428`** (`feat/armsx2`) - **PS2 is ARMSX2** (PCSX2 fork with ARM64 recompilers, GPL-3.0). Upstream PCSX2 only has `pcsx2/arm64/RecStubs.cpp`: NFS Underground 2 ran at 17 fps with one core at 100%; ARMSX2 runs it at **59.9 fps / 100%**, all recompilers + fastmem on under proot. PCSX2 left the front end and the catalog. +- **PR #29 → `08a6769`** (`feat/armsx2-polish`): + - ARMSX2 from the rail: `-batch -bigpicture -fullscreen`; guide → pause menu → Close Game returns to the app. First run: PCSX2 settings + memory cards copied once; a new player gets ARMSX2's setup with the BIOS folder in `ROMs/ps2/bios` (or `ps2/firmware`), `ps2` as game list, Vulkan, controller on Player 1. Users bring their own BIOS and games. + - Catalog `pages` - a file per memory page size; ARMSX2 4K + 16K. + - On-screen controls: Auto for rail games and Steam when no controller, off on the desktop; setting in the drawer everywhere; drawer headed by the emulator for rail games. + - Front end: Back/B steps back a level (emulator → Desktop, game → emulator) instead of leaving the app; games found up to 3 folders deep (`ps2/games//`); **box art** (libretro-thumbnails by name exact/loose, xlenore/ps2-covers by PS2 serial, GameTDB by GC/Wii ID, PS3 discs' own `ICON0.PNG`), kept in `files/covers`; wide art shown whole over a blurred copy; titles without dump tags. +- **winlator-contents** (the catalog): ARMSX2 `nightly-20260923-92aa2174da` mirrored (`armsx2.AppImage` 4K, `armsx2-16k.AppImage`), PCSX2 dropped from `desktop.json` (PRs #12, #13); the mirror workflow lists only the file being added (a re-run re-fetches and clobbers every listed file, and DuckStation's upstream link moves). +- **Not yet device-played**: DuckStation, Dolphin, Cemu, melonDS, PPSSPP, RetroArch (profiles + covers written from their sources). Known gap: a keyboard's Esc does not open ARMSX2's pause menu in a rail game (guide does). + ## 2026-09-23 (evening) - renamed SteamDeck → DroidDeck - **App name, app ID and code package**: DroidDeck, `com.droiddeck.launcher` (was `com.steamdeck.launcher`), sources under `app/src/main/java/com/droiddeck/launcher`, the 68 JNI functions renamed with them. A new app ID means DroidDeck installs **beside** SteamDeck, not over it: the runtime, the Steam sign-in and the settings start fresh. @@ -191,13 +262,43 @@ State: **main = `90c7574`** (PR #14 merge), main build run 35895701784. No tag, - Bannerlator's File Manager ports mechanically (`port_fm.py` anchors) once the container hooks are cut; do not hand-edit 2,500 lines. - Deleting a release asset on GitHub can drop a sibling asset - re-list and restore. +- A resource without an implementation makes libwayland abort on its first request - every + interface the compositor hands out needs one, even as no-ops (positioner, popup, output). +- The KGSL stand-in answers no DRM ioctl: `drmIsMaster()` reads that as "master"; check + `drmGetVersion()` before treating a GPU fd as DRM. +- Verify an emulator's config values from its source: RPCS3's GUI says "Async Shader Recompiler", + the config value is "Async Recompiler (multi-threaded)". +- Upstream PCSX2 has no ARM64 recompiler; a correct ARM64 build of it is still interpreter-slow. +- An Android app starts in touch mode, where Compose clickables refuse focus: `requestFocus()` on open + does nothing until the app asks for keyboard input mode. +- `grep -q` (or `head`) at the end of a pipe exits early; under `pipefail` that fails the whole line at + random. Capture the output first, then search it. +- A reusable workflow gets no more permission than its caller gives, and sees environment secrets only + with `secrets: inherit`. A workflow naming an environment that does not exist creates it unprotected. +- `pull_request_target` shares main's caches with the pull request's code - never with signed builds. +- apksigner prints signers as "Signer #1", "Signer (minSdkVersion=…)" or "V3.0 Signer:" by version. ## Backlog / next +- Play-test the other emulators one by one on the FIT: Dolphin, Cemu, melonDS, PPSSPP, RetroArch + (pad profiles and covers exist; nothing played yet). DuckStation done 2026-09-24. +- **Kurt's PR #39 (Non-Launcher flavor) breaks signing as written**: it replaces the `droiddeck-apk` + artifact with `droiddeck-home-apk` / `droiddeck-non-launcher-apk`, which `sign.yml` and `release.yml` + read, and it conflicts with today's `build.yml`. Adapt before merging: sign both editions (a release + would then be editions × packages). +- After the repo is public: add a required reviewer to the `release` environment (not allowed on a + private repo on the Pro plan). +- First release with the new key (0.1.7): run `release.yml`, publish; 0.1.6 users move over by the + hand-over. +- Keyboard Esc in a rail game does not reach ARMSX2's pause menu (guide does). +- 0.1.7 pre-release when ready (everything above is on main only). +- Pin a newer ARMSX2 nightly only after testing it (it changes daily). - Device-prove 0.1.4 on the FIT (list above). - Thor Pro: trackpad tap; the 1–2 min in-game crash once a `crash.log` arrives. - Xfce as a second desktop shell (Max's branch runs XFCE 4.20 on labwc) - a catalog package + a shell choice in the Desktop cog; comfort, not performance. -- Quick Access Menu for non-Deck pads - no confirmed chord; needs research, not a guess. +- Quick Access Menu for non-Deck pads - Back double-press (500 ms) now routes to the existing Guide+A + chord; the in-session menu, Steam settings, and Setup › Session can swap the single- and double-Back + actions. Device confirmation is still needed. - FlatOut shrink: try `vk_wsi_force_swapchain_to_current_extent=false` via `steamdeck-env`. - Max's stricter `winnative-directaudio` guards; `winnative-epic-launch` (a feature). -- Rename before anything truly public: "SteamDeck" is Valve's mark. +- Rename before anything truly public: "SteamDeck" is Valve's mark. (Done 2026-09-23: DroidDeck.) diff --git a/keystore/release-signer.sha256 b/keystore/release-signer.sha256 new file mode 100644 index 0000000000..21b2147916 --- /dev/null +++ b/keystore/release-signer.sha256 @@ -0,0 +1 @@ +b241ea7d77822d39b89d3227e06f3ecf62adec6cbfd38ad06196787991b5d3f0 diff --git a/tools/build_local.sh b/tools/build_local.sh index c849a35051..3df403703e 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -2,6 +2,15 @@ set -euo pipefail repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +if tree_status=$(git -C "${repo_root}" status --porcelain 2>/dev/null); then + if [[ -n "${tree_status}" ]]; then + export DROIDDECK_BUILD_TREE_STATE=dirty + else + export DROIDDECK_BUILD_TREE_STATE=clean + fi +else + export DROIDDECK_BUILD_TREE_STATE=unknown +fi sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}} java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"} image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v2} diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-pad-defaults b/tools/linuxfs/overlay/usr/local/bin/bannerlator-pad-defaults index 01b9f593f4..88e56d76de 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-pad-defaults +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-pad-defaults @@ -116,7 +116,7 @@ def ini_section(lines, name): return (start, len(lines)) if start is not None else None -def patch_ini_section(path, section, body, what, needle="SDL-", require=None): +def patch_ini_section(path, section, body, what, needle="SDL-", require=None, done="Player 1 on the controller"): """Add body's lines to [section] of an ini the emulator wrote itself, unless the section already binds a controller (needle). Missing file: nothing - the emulator writes its own defaults on first run and this runs again.""" @@ -144,7 +144,7 @@ def patch_ini_section(path, section, body, what, needle="SDL-", require=None): with open(path + ".tmp", "w", encoding="utf-8") as f: f.write("\n".join(lines) + "\n") os.replace(path + ".tmp", path) - print(f"bannerlator-pad-defaults: {what}: Player 1 on the controller ({path})") + print(f"bannerlator-pad-defaults: {what}: {done} ({path})") # DuckStation: SDL-/, axes signed (src/util/sdl_input_source.cpp); Pad1 keys from @@ -180,9 +180,131 @@ SmallMotor = SDL-0/SmallMotor """ +def ini_get(path, section, key): + try: + with open(path, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + except OSError: + return None + span = ini_section(lines, section) + if not span: + return None + for l in lines[span[0]:span[1]]: + if "=" in l and l.split("=", 1)[0].strip() == key: + return l.split("=", 1)[1].strip() + return None + + +def ini_set(path, section, key, value): + """Sets one key (the first of that name) in [section], adding either as needed.""" + with open(path, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + span = ini_section(lines, section) + if span is None: + lines += ["", f"[{section}]", f"{key} = {value}"] + else: + for i in range(span[0], span[1]): + if "=" in lines[i] and lines[i].split("=", 1)[0].strip() == key: + lines[i] = f"{key} = {value}" + break + else: + end = span[1] + while end > span[0] and not lines[end - 1].strip(): + end -= 1 + lines.insert(end, f"{key} = {value}") + with open(path + ".tmp", "w", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + os.replace(path + ".tmp", path) + + +def drop_line(path, line): + with open(path, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + kept = [l for l in lines if l.replace(" ", "") != line.replace(" ", "")] + if len(kept) != len(lines): + with open(path + ".tmp", "w", encoding="utf-8") as f: + f.write("\n".join(kept) + "\n") + os.replace(path + ".tmp", path) + + +def system_folder(names, default): + for name in names: + for cand in (name, name.upper()): + d = os.path.join(ROMS, cand) + if os.path.isdir(d): + return d + return os.path.join(ROMS, default) + + +def bios_folder(base): + for name in ("bios", "BIOS", "firmware"): + d = os.path.join(base, name) + if os.path.isdir(d): + return d + d = os.path.join(base, "bios") + if os.path.isdir(ROMS): + try: + os.makedirs(d, exist_ok=True) # where the user is told to put their BIOS + except OSError: + pass + return d + + +# DuckStation (PS1) - set up like ARMSX2: users bring their own BIOS and games, in the ROMs folder. +# Front-end runs use -batch -bigpicture -fullscreen, so the guide button is the pause menu +# (Hotkeys OpenPauseMenu, src/core/hotkeys.cpp), not the analog toggle. Keys from +# src/core/settings.cpp: [BIOS] SearchDirectory, [GPU] Renderer ("Vulkan"), [Main] +# SetupWizardIncomplete (src/duckstation-qt/qthost.cpp). +DUCKSTATION_PAD1_GUIDE_FREE = "\n".join(l for l in DUCKSTATION_PAD1.splitlines() if not l.startswith("Analog ")) + "\n" + + def duckstation(): - for d in (os.path.join(CONFIG, "duckstation"), os.path.join(HOME, ".local/share/duckstation")): - patch_ini_section(os.path.join(d, "settings.ini"), "Pad1", DUCKSTATION_PAD1, "DuckStation") + ps1 = system_folder(("psx", "ps1"), "psx") + d = os.path.join(CONFIG, "duckstation") + ini = os.path.join(d, "settings.ini") + legacy = os.path.join(HOME, ".local/share/duckstation/settings.ini") + if not os.path.isfile(ini) and os.path.isfile(legacy): + ini = legacy + if not os.path.isfile(ini): + # A new player: everything DuckStation's first-time setup asks is answered here (it finds + # the BIOS in its folder by itself), so a game from the front end boots straight away. + bios = bios_folder(ps1) + seed(ini, "[Main]\nSetupWizardIncomplete = false\nInhibitScreensaver = false\n\n" + f"[BIOS]\nSearchDirectory = {bios}\n\n" + f"[GameList]\nRecursivePaths = {ps1}\n\n" + "[GPU]\nRenderer = Vulkan\n\n" + "[Hotkeys]\nOpenPauseMenu = Keyboard/Escape\nOpenPauseMenu = SDL-0/Guide\n\n" + "[Pad1]\n" + DUCKSTATION_PAD1_GUIDE_FREE, "DuckStation", "first-time setup, BIOS from " + bios) + return + patch_ini_section(ini, "Pad1", DUCKSTATION_PAD1_GUIDE_FREE, "DuckStation") + drop_line(ini, "Analog = SDL-0/Guide") + patch_ini_section(ini, "Hotkeys", "OpenPauseMenu = SDL-0/Guide\n", "DuckStation", needle="SDL-0/Guide", + done="the guide button opens the pause menu") + patch_ini_section(ini, "GameList", f"RecursivePaths = {ps1}\n", "DuckStation", needle=ROMS, + done="games listed from the ROMs folder") + # One set up by an earlier build still has its first-time setup pending, in the way of a game. + if ini_get(ini, "Main", "SetupWizardIncomplete") == "true": + ini_set(ini, "Main", "SetupWizardIncomplete", "false") + print("bannerlator-pad-defaults: DuckStation: first-time setup already done here") + # Keeping the screen awake goes through org.freedesktop.ScreenSaver, which nothing in the session + # provides (Android decides when the screen sleeps): DuckStation only warns it failed, every game. + if (ini_get(ini, "Main", "InhibitScreensaver") or "true") == "true": + ini_set(ini, "Main", "InhibitScreensaver", "false") + print("bannerlator-pad-defaults: DuckStation: no screensaver inhibit (no such service here)") + # Once, for a DuckStation set up before this: its own empty BIOS folder moves to the ROMs folder, + # and Automatic becomes Vulkan. A later choice in DuckStation's settings is kept. + marker = os.path.join(os.path.dirname(ini), ".droiddeck-setup") + if os.path.exists(marker): + return + current = ini_get(ini, "BIOS", "SearchDirectory") or "bios" + own = current if os.path.isabs(current) else os.path.join(os.path.dirname(ini), current) + if not (os.path.isdir(own) and os.listdir(own)): + ini_set(ini, "BIOS", "SearchDirectory", bios_folder(ps1)) + print(f"bannerlator-pad-defaults: DuckStation: BIOS from {bios_folder(ps1)}") + if (ini_get(ini, "GPU", "Renderer") or "Automatic") == "Automatic": + ini_set(ini, "GPU", "Renderer", "Vulkan") + print("bannerlator-pad-defaults: DuckStation: renderer Vulkan") + open(marker, "w").close() # PCSX2: FaceSouth/... names (pcsx2/Input/SDLInputSource.cpp), keys from SIO/Pad/PadDualshock2.cpp. @@ -221,10 +343,7 @@ SmallMotor = SDL-0/SmallMotor def pcsx2(): patch_ini_section(os.path.join(CONFIG, "PCSX2/inis/PCSX2.ini"), "Pad1", PCSX2_PAD1, "PCSX2", require="SettingsVersion") - # ARMSX2 (PCSX2 with ARM64 recompilers): the same ini and binding names under its own folder - # (pcsx2/Pcsx2Config.cpp: $XDG_CONFIG_HOME/ARMSX2/inis/PCSX2.ini). - patch_ini_section(os.path.join(CONFIG, "ARMSX2/inis/PCSX2.ini"), "Pad1", PCSX2_PAD1, "ARMSX2", - require="SettingsVersion") + # Dolphin: SDL//; control names from InputCommon/.../SDL/SDLGamepad.h (Left Y+ @@ -287,6 +406,110 @@ Nunchuk/Stick/Right = `Left X+` """ +# ARMSX2 - the PS2 emulator (PCSX2 with ARM64 recompilers; upstream PCSX2 interprets on ARM64). Its +# files are PCSX2's under $XDG_CONFIG_HOME/ARMSX2 (pcsx2/Pcsx2Config.cpp). The user supplies the BIOS +# and the games; they live in the ROMs folder (/root/ROMs). The guide button opens the pause menu +# (Hotkeys OpenPauseMenu) - the way out of a game started from the front end, which runs ARMSX2 +# without its window (-batch -bigpicture) - so it is not also the analog toggle here. +ARMSX2_PAD1 = "\n".join(l for l in PCSX2_PAD1.splitlines() if not l.startswith("Analog ")) + "\n" +ROMS = "/root/ROMs" + + +def ps2_folder(): + for name in ("ps2", "PS2"): + d = os.path.join(ROMS, name) + if os.path.isdir(d): + return d + return os.path.join(ROMS, "ps2") + + +def ps2_bios_folder(): + base = ps2_folder() + for name in ("bios", "BIOS", "firmware"): + d = os.path.join(base, name) + if os.path.isdir(d): + return d + d = os.path.join(base, "bios") + if os.path.isdir(ROMS): + try: + os.makedirs(d, exist_ok=True) # where the user is told to put their BIOS + except OSError: + pass + return d + + +def armsx2(): + root = os.path.join(CONFIG, "ARMSX2") + ini = os.path.join(root, "inis/PCSX2.ini") + old = os.path.join(CONFIG, "PCSX2") + if not os.path.isfile(ini) and os.path.isfile(os.path.join(old, "inis/PCSX2.ini")): + # Someone who played on PCSX2 here: the same settings, BIOS choice and memory cards (the + # saves), copied once. PCSX2's own folder is left as it was. + import shutil + for sub in ("inis", "memcards", "bios", "gamesettings", "cheats", "patches", "covers", + "inputprofiles", "textures"): + src = os.path.join(old, sub) + if os.path.isdir(src): + shutil.copytree(src, os.path.join(root, sub), dirs_exist_ok=True) + print(f"bannerlator-pad-defaults: ARMSX2: settings and memory cards copied from PCSX2 ({root})") + elif not os.path.isfile(ini): + # A new player: everything ARMSX2's first-time setup asks is answered here - the BIOS + # folder in the ROMs folder, the ps2 folder as its game list, the controller on Player 1 - + # and the BIOS file itself is picked below once one is there. + bios, games = ps2_bios_folder(), ps2_folder() + seed(ini, "[UI]\nSettingsVersion = 1\nSetupWizardIncomplete = false\n\n" + f"[Folders]\nBios = {bios}\n\n" + f"[GameList]\nRecursivePaths = {games}\n\n" + # Vulkan outright rather than Auto's pick: the renderer every other path here uses. + "[EmuCore/GS]\nRenderer = 14\n\n" + "[Hotkeys]\nOpenPauseMenu = Keyboard/Escape\nOpenPauseMenu = SDL-0/Guide\n\n" + "[Pad1]\n" + ARMSX2_PAD1, "ARMSX2", "first-time setup, BIOS from " + bios) + armsx2_bios(ini) + return + patch_ini_section(ini, "Pad1", ARMSX2_PAD1, "ARMSX2", require="SettingsVersion") + # The guide button is the pause menu here; PCSX2's profile (ours, copied over) had it as the + # analog toggle as well. + with open(ini, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + kept = [l for l in lines if l.replace(" ", "") != "Analog=SDL-0/Guide"] + if len(kept) != len(lines): + with open(ini + ".tmp", "w", encoding="utf-8") as f: + f.write("\n".join(kept) + "\n") + os.replace(ini + ".tmp", ini) + patch_ini_section(ini, "Hotkeys", "OpenPauseMenu = SDL-0/Guide\n", "ARMSX2", needle="SDL-0/Guide", + require="SettingsVersion", done="the guide button opens the pause menu") + patch_ini_section(ini, "GameList", f"RecursivePaths = {ps2_folder()}\n", "ARMSX2", needle=ROMS, + require="SettingsVersion", done="games listed from the ROMs folder") + if ini_get(ini, "UI", "SetupWizardIncomplete") == "true": + ini_set(ini, "UI", "SetupWizardIncomplete", "false") + print("bannerlator-pad-defaults: ARMSX2: first-time setup already done here") + armsx2_bios(ini) + + +def armsx2_bios(ini): + """PCSX2 boots the one BIOS file named in [Filenames] BIOS (inside [Folders] Bios); its first-time + setup is what names it. With that skipped, the first dump in the folder is named here - a US one + first - while none is named or the named one is gone. A choice made in ARMSX2 is kept.""" + folder = ini_get(ini, "Folders", "Bios") or ps2_bios_folder() + if not os.path.isabs(folder): + folder = os.path.join(os.path.dirname(os.path.dirname(ini)), folder) + current = ini_get(ini, "Filenames", "BIOS") + if current and os.path.isfile(os.path.join(folder, current)): + return + try: + # A PS2 BIOS dump is 4 MiB (a few are 8); the .nvm/.mec files beside it are not dumps. + dumps = sorted(f for f in os.listdir(folder) + if os.path.isfile(os.path.join(folder, f)) and 4 << 20 <= os.path.getsize(os.path.join(folder, f)) <= 8 << 20) + except OSError: + return + if not dumps: + return + us = [f for f in dumps if any(t in f.lower() for t in ("usa", "(us)", "(us,", "ntsc-u"))] + pick = (us or dumps)[0] + ini_set(ini, "Filenames", "BIOS", pick) + print(f"bannerlator-pad-defaults: ARMSX2: BIOS {pick}") + + def dolphin(): d = os.path.join(CONFIG, "dolphin-emu") seed(os.path.join(d, "GCPadNew.ini"), DOLPHIN_GC, "Dolphin (GameCube)") @@ -454,7 +677,7 @@ def retroarch(): print(f"bannerlator-pad-defaults: RetroArch: joypad driver udev -> sdl2 ({cfg})") -for step in (rpcs3, duckstation, pcsx2, dolphin, cemu, melonds, ppsspp, retroarch): +for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch): try: step() except Exception as e: diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session index 0bc8477cd4..bdcc653c9e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session @@ -347,6 +347,22 @@ case $mode in # moments later, so the seeder has only that gap to mark the redistributables as already run. # It stamps each prefix it has covered and skips it thereafter, so the extra passes cost # almost nothing. + # The drawer's "Stretch games to fill the screen" works live: the app writes its choice to + # ~/.droiddeck-fill, and each change goes to gamescope as GAMESCOPE_FORCE_WINDOWS_FULLSCREEN on + # the root window, which it watches. What gamescope was started with is where this begins. + ( + last=${BL_GAMESCOPE_FORCE_FULLSCREEN:-1} + while :; do + sleep 1 + want=$(cat "$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 + echo "== stretch games to fill the screen: $want (live)" + last=$want + fi + done + ) & ( beat=0 for _ in $(seq 1 720); do diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat index b7c0659ad1..4156846a5b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat @@ -87,6 +87,31 @@ bl_game_cpus() { } """ +# Quake III engine games (id Tech 3) set their own resolution and switch the display to it. Under +# gamescope with the ARM64 Proton that switch is refused ("calling CDS: failed, bad mode") and the +# 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. +BL_IDTECH3_SETUP = """ +bl_idtech3() { + BL_EXTRA_ARGS=() + case "${SteamAppId:-${STEAM_COMPAT_APP_ID:-}}" in + # Quake III Arena, Quake III: Team Arena, Return to Castle Wolfenstein, Jedi Academy. + 2200|2350|9010|6020) ;; + *) return 0 ;; + esac + case " $* " in + *r_fullscreen*|*r_mode*|*r_customwidth*|*r_customheight*) + echo "bannerlator-proton: Quake-engine title; its launch options set the video mode, left as they are" >&2 + return 0 ;; + esac + w=${BL_WIDTH:-1280} + h=${BL_HEIGHT:-720} + BL_EXTRA_ARGS=(+set r_fullscreen 0 +set r_mode -1 +set r_customwidth "$w" +set r_customheight "$h") + echo "bannerlator-proton: Quake-engine title: windowed at ${w}x${h}" >&2 +} +""" + BL_DIRECTAUDIO_SETUP = """ bl_directaudio() { base=$1 @@ -152,7 +177,8 @@ for name in %s; do if [ -d "$depot/files/bin-arm64" ] && [ -x "$depot/proton" ]; then bl_directaudio "$depot" bl_game_cpus - exec ${BL_TASKSET:-} "$depot/proton" "$verb" "$@" + bl_idtech3 "$@" + exec ${BL_TASKSET:-} "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" fi done echo "bannerlator-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2 @@ -162,7 +188,7 @@ exit 1 # and a % format would eat that into a single %, leaving a shell expansion that silently does # something else. LAUNCHER_SH = LAUNCHER_SH.replace( - "verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP, 1) + "verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_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 @@ -196,9 +222,10 @@ if [ -f "$fake" ]; then fi bl_directaudio "$here" bl_game_cpus +bl_idtech3 "$@" # 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" "$@" +exec ${BL_TASKSET:-} "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" """ EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools" { @@ -357,7 +384,7 @@ def adopt_extras(tools): # ${major%%.*} of its own, and putting it through the format would eat both. body = (EXTRA_WRAPPER_SH % entry_point).replace( 'here=$(dirname "$0")', - 'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP, 1) + 'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP, 1) with open(wrapper, "w", encoding="utf-8") as f: f.write(body) os.chmod(wrapper, 0o755) diff --git a/tools/release/axml_rename.py b/tools/release/axml_rename.py new file mode 100644 index 0000000000..ec553a12c7 --- /dev/null +++ b/tools/release/axml_rename.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +# axml_rename.py in.apk out.apk old=new ... : rewrite whole strings in AndroidManifest.xml's string +# pool (binary XML), leaving every other entry of the apk byte-identical. Unsigned output. +import struct, sys, zipfile + +def dec_len8(b, o): + n = b[o]; o += 1 + if n & 0x80: n = ((n & 0x7f) << 8) | b[o]; o += 1 + return n, o + +def dec_len16(b, o): + n = struct.unpack_from('> 8), n & 0xff]) + +def enc_len16(n): + return struct.pack('> 16), n & 0xffff) + +def rewrite(axml, repl): + ftype, fhs, fsize = struct.unpack_from('&2; exit 1; } +command -v keytool >/dev/null || die "keytool not found (Termux: pkg install openjdk-17)" +command -v gh >/dev/null || die "gh not found" +gh auth status >/dev/null 2>&1 || die "gh is not logged in (gh auth login)" +[ -e "$OUT/droiddeck-release.p12" ] && die "a key already exists in $OUT - there must only ever be one" +case "$OUT" in "$repo"|"$repo"/*) die "the key must not be made inside the repo" ;; esac +for env in "${ENVIRONMENTS[@]}"; do + gh api "repos/$REPO/environments/$env" >/dev/null 2>&1 || die "GitHub environment '$env' does not exist yet" +done + +umask 077 +mkdir -p "$OUT" +KS="$OUT/droiddeck-release.p12" +KS_PW=$(head -c 60 /dev/urandom | base64 -w0 | tr -d '/+=') +KS_PW=${KS_PW:0:48} +[ ${#KS_PW} -ge 40 ] || die "could not make a password" +export KS_PW +printf '%s\n' "$KS_PW" > "$OUT/password.txt" + +keytool -genkeypair -keystore "$KS" -storetype PKCS12 -alias "$ALIAS" \ + -keyalg RSA -keysize 4096 -validity 10950 -dname "CN=DroidDeck, O=The412Banner" \ + -storepass:env KS_PW -keypass:env KS_PW >/dev/null 2>&1 || die "keytool could not make the key" +listing=$(keytool -list -v -keystore "$KS" -storepass:env KS_PW -alias "$ALIAS") +SHA=$(awk '/SHA256:/ { print $2 }' <<<"$listing" | head -n1 | tr -d ':' | tr 'A-F' 'a-f') +[[ $SHA =~ ^[0-9a-f]{64}$ ]] || die "could not read the key's certificate digest" + +for env in "${ENVIRONMENTS[@]}"; do + base64 -w0 < "$KS" | gh secret set RELEASE_KEYSTORE_B64 --env "$env" -R "$REPO" >/dev/null + printf '%s' "$KS_PW" | gh secret set RELEASE_STORE_PASSWORD --env "$env" -R "$REPO" >/dev/null + echo "secrets set for environment: $env" +done +unset KS_PW + +printf '%s\n' "$SHA" > "$repo/keystore/release-signer.sha256" +cat < +# +# Turns a CI build (signed with the public AOSP testkey) into one package of tools/release/variants.txt +# signed with DroidDeck's own key, carrying the hand-over from the testkey: +# - v1 + v2 are signed by the testkey, v3 by our key, with a signed lineage testkey -> our key; +# - an install from before (testkey) updates to it and keeps its data; +# - the testkey loses its rollback right, so an apk signed with the testkey alone - which anyone +# can make - is refused as an update to it (device-proven on the Pocket FIT, 2026-09-24); +# - --rotation-min-sdk-version 28: the lineage applies from Android 9, not only from 13. +# +# The key comes from the environment and is never written anywhere but the path given: +# RELEASE_KEYSTORE path to the PKCS12 keystore +# RELEASE_STORE_PASSWORD its password (the key has the same one: PKCS12) +# RELEASE_KEY_ALIAS the key's alias +# BUILD_TOOLS Android build-tools dir (zipalign, apksigner, aapt) +# RELEASE_SIGNER_SHA256 optional: the expected certificate digest, else keystore/release-signer.sha256 +set -euo pipefail + +die() { echo "::error::$*" >&2; exit 1; } +[ $# -eq 3 ] || die "usage: sign-apk.sh " +in=$1 variant=$2 out=$3 +here=$(cd "$(dirname "$0")" && pwd) +repo=$(cd "$here/../.." && pwd) + +pkg=$(awk -v v="$variant" '!/^#/ && $1 == v { print $2 }' "$here/variants.txt") +[ -n "$pkg" ] || die "no variant '$variant' in tools/release/variants.txt" +expected=${RELEASE_SIGNER_SHA256:-$(tr -d ' \n' < "$repo/keystore/release-signer.sha256" 2>/dev/null || true)} +[[ $expected =~ ^[0-9a-f]{64}$ ]] \ + || die "keystore/release-signer.sha256 is missing: make the key first (tools/release/make-release-key.sh)" +: "${RELEASE_KEYSTORE:?}" "${RELEASE_STORE_PASSWORD:?}" "${RELEASE_KEY_ALIAS:?}" "${BUILD_TOOLS:?}" +[ -s "$RELEASE_KEYSTORE" ] || die "the release keystore is empty - is the secret set for this environment?" + +TESTKEY="$repo/keystore/testkey.p12" +TESTKEY_SHA256=a40da80a59d170caa950cf15c18c454d47a39b26989d8b640ecd745ba71bf5dc +export TESTKEY_PASSWORD=android +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +# The package name and everything the manifest derives from it; component class names stay. +P=com.droiddeck.launcher +if [ "$pkg" = "$P" ]; then + python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" +else + python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \ + "$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \ + "$P.documents=$pkg.documents" "$P.home=$pkg.home" \ + "$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" +fi +got=$("$BUILD_TOOLS/aapt" dump badging "$work/renamed.apk" | sed -n "s/^package: name='\([^']*\)'.*/\1/p") +[ "$got" = "$pkg" ] || die "$variant: the apk says package '$got', not '$pkg'" +if [ "$pkg" != "$P" ]; then + # A provider left on the old authority would clash with the standard app installed beside it. + tree=$("$BUILD_TOOLS/aapt" dump xmltree "$work/renamed.apk" AndroidManifest.xml) + grep -E 'android:(authorities|taskAffinity)' <<<"$tree" | grep -F "\"$P." \ + && die "$variant: the manifest still names $P in an authority or task" +fi + +"$BUILD_TOOLS/zipalign" -p -f 4 "$work/renamed.apk" "$work/aligned.apk" + +# The lineage: the testkey vouches for our key. Made fresh each time (it is two certificates and +# a signature, nothing secret beyond the key that signs it). +"$BUILD_TOOLS/apksigner" rotate --out "$work/lineage" \ + --old-signer --ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \ + --ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD --set-rollback false \ + --new-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \ + --ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD + +"$BUILD_TOOLS/apksigner" sign \ + --ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \ + --ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD \ + --next-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \ + --ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD \ + --lineage "$work/lineage" --rotation-min-sdk-version 28 \ + --v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true --v4-signing-enabled false \ + --out "$out" "$work/aligned.apk" +rm -f "$out.idsig" + +# What the apk must carry, checked rather than assumed. +"$BUILD_TOOLS/apksigner" verify --min-sdk-version 26 "$out" >/dev/null || die "$variant: does not verify" +# (Listed first, then searched: grep -q stops reading early, which fails a pipe under pipefail.) +listing=$(unzip -l "$out") +grep -qE 'META-INF/.*\.(SF|RSA)$' <<<"$listing" || die "$variant: no JAR signature (old installers)" +# Android 9+ must see our key and only our key. apksigner labels signers "Signer #1", "Signer +# (minSdkVersion=28, ...)" or "V3.0 Signer:" depending on its version; the digests are what count. +certs=$("$BUILD_TOOLS/apksigner" verify --min-sdk-version 28 --print-certs "$out") +v3=$(sed -n 's/^.*Signer.* certificate SHA-256 digest: //p' <<<"$certs" | sort -u) +if [ "$v3" != "$expected" ]; then + echo "$certs" >&2 + die "$variant: Android 9+ sees signer(s) [$(tr '\n' ' ' <<<"$v3")], not only DroidDeck's key $expected" +fi +lineage=$("$BUILD_TOOLS/apksigner" lineage --in "$out" --print-certs) +grep -q "Signer #1 in lineage certificate SHA-256 digest: $TESTKEY_SHA256" <<<"$lineage" \ + || die "$variant: the lineage does not start at the testkey - old installs could not update" +grep -q "Signer #2 in lineage certificate SHA-256 digest: $expected" <<<"$lineage" \ + || die "$variant: the lineage does not hand over to DroidDeck's key" +rollback=$(awk '/Signer #1 in lineage/{s=1} /Signer #2 in lineage/{s=0} s && /rollback capability/' <<<"$lineage") +grep -q false <<<"$rollback" \ + || die "$variant: the testkey kept its rollback right - a testkey-signed apk could replace this one" +echo "$variant ($pkg): signed, hand-over from the testkey, v3 signer $expected" diff --git a/tools/release/variants.txt b/tools/release/variants.txt new file mode 100644 index 0000000000..6071068008 --- /dev/null +++ b/tools/release/variants.txt @@ -0,0 +1,9 @@ +# The packages a signed build ships as. The same apk, with only the manifest's package name (and +# the names derived from it) changed: some phones give their performance modes only to apps with +# certain names. Each is its own app to Android - installs beside the others, with its own data. +# +# name package file suffix +standard com.droiddeck.launcher - +pubg com.tencent.ig -pubg +antutu com.antutu.benchmark.full -antutu +ludashi com.ludashi.benchmark -ludashi