diff --git a/.github/workflows/authorship.yml b/.github/workflows/authorship.yml index 615267b6c0..857fb68023 100644 --- a/.github/workflows/authorship.yml +++ b/.github/workflows/authorship.yml @@ -7,7 +7,7 @@ on: push: branches: [main] workflow_run: - workflows: [Build APK] + workflows: [Build APK, Unit tests] types: [completed] workflow_dispatch: inputs: @@ -21,6 +21,12 @@ permissions: pull-requests: read statuses: write +# Build APK and Unit tests each trigger a validation, and the last one to post sets the status. Queued runs for a +# commit wait, so the newest one reads both results and posts last. +concurrency: + group: build-validation-${{ github.event.pull_request.head.sha || github.event.workflow_run.head_sha || inputs.pr_number || github.sha }} + cancel-in-progress: false + jobs: validate: name: Validate source and build result diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c96d808872..b142ab7604 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,5 @@ name: Build APK -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) }} +run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('building {0} on {1}', github.ref_name, github.sha) }} on: push: @@ -57,15 +57,18 @@ jobs: - name: Pin and merge the APK source id: merge if: github.event_name == 'pull_request' + env: + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} run: | set -euo pipefail - git fetch --no-tags origin main - echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT" + # Unit tests uses the same event snapshot, including when either workflow is rerun. + git fetch --no-tags origin "$PR_BASE_SHA" + echo "base-sha=$PR_BASE_SHA" >> "$GITHUB_OUTPUT" git config user.name "ci" git config user.email "ci@users.noreply.github.com" # Partial clone: a merged blob that only exists in a fork's history can't be lazily fetched (GitHub: "not our ref"); merge-tree writes it locally first. - git merge-tree --write-tree HEAD origin/main >/dev/null || true - git merge --no-ff --no-edit origin/main + git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true + git merge --no-ff --no-edit FETCH_HEAD - name: Resolve trusted manifest base id: trusted if: github.event_name != 'pull_request' @@ -352,7 +355,7 @@ jobs: build: needs: [source, components, xbox, build-runner] - name: Compile APK and Android tests + name: Compile APK if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ${{ fromJSON(needs.build-runner.outputs.labels) }} timeout-minutes: 45 @@ -510,23 +513,7 @@ jobs: 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 "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV" - echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV" - echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV" - echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" + run: bash tools/ci/build-label.sh - name: Rust toolchain for the store engines (aarch64-linux-android) id: rust @@ -737,101 +724,6 @@ jobs: if-no-files-found: ignore overwrite: true - - name: Resolve the Robolectric version - id: robolectric - run: | - echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT" - # Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes. - # The cache path sits beside the workspace because runner homes are at different depths from it, and - # actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects - # "..". Runners that keep their own ~/.m2 skip the cache. - - name: Place Robolectric's Android jars beside the workspace - id: robolectric-jars - run: | - set -euo pipefail - jars="$GITHUB_WORKSPACE/../robolectric-jars" - m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented" - if [ -d "$m2" ] && [ ! -L "$m2" ]; then - echo "cache=false" >> "$GITHUB_OUTPUT" - else - mkdir -p "$jars" "$(dirname "$m2")" - jars=$(cd "$jars" && pwd) - ln -sfn "$jars" "$m2" - echo "path=$jars" >> "$GITHUB_OUTPUT" - echo "cache=true" >> "$GITHUB_OUTPUT" - fi - - name: Restore Robolectric's Android jars - id: robolectric-cache - if: steps.robolectric-jars.outputs.cache == 'true' - uses: actions/cache/restore@v4 - with: - path: ${{ steps.robolectric-jars.outputs.path }} - key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} - restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}- - - name: Count the restored Robolectric jars - if: steps.robolectric-jars.outputs.cache == 'true' - run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV" - - name: Unit tests - id: unit-tests - env: - DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} - SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }} - run: | - set -o pipefail - mkdir -p app/build - # A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next. - for wait in 60 180 0; do - status=0 - ./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$? - if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://repo\.maven\.apache\.org/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://repo\.maven\.apache\.org/)' app/build/unit-tests.log; then - exit "$status" - fi - echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" - sleep "$wait" - done - - # actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache. - # Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first. - - name: Save Robolectric's Android jars - id: robolectric-jars-final - if: always() && steps.robolectric-jars.outputs.cache == 'true' - run: | - python3 - <<'PY' - import glob, os, zipfile - root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars') - for f in glob.glob(os.path.join(root, '**', '*'), recursive=True): - if not os.path.isfile(f): - continue - try: - ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None - except Exception: - ok = False - if not ok: - os.remove(f) - PY - after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l) - [ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true - - name: Store Robolectric's Android jars - if: always() && steps.robolectric-jars-final.outputs.save == 'true' - uses: actions/cache/save@v4 - with: - path: ${{ steps.robolectric-jars.outputs.path }} - key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} - - - name: Upload unit test diagnostics - id: unit-test-diagnostics - if: always() && steps.unit-tests.outcome != 'skipped' - uses: actions/upload-artifact@v4 - with: - name: unit-test-results - path: | - app/build/unit-tests.log - app/build/test-results/testReleaseUnitTest/ - app/build/reports/tests/testReleaseUnitTest/ - if-no-files-found: ignore - retention-days: 14 - overwrite: true - - name: Sign with the testkey (v1 + v2 + v3) run: | set -euo pipefail @@ -887,8 +779,6 @@ jobs: PR: ${{ github.event.pull_request.number }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} BUILD_OUTCOME: ${{ steps.build.outcome }} - UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }} - TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }} APK_OUTCOME: ${{ steps.apk-upload.outcome }} run: bash tools/release/report-build.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eabc77a358..24fd2ffa9a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -47,6 +47,13 @@ jobs: echo "::error::main ${GITHUB_SHA::7} has no successful Build APK run yet: wait for it, then release" exit 1 fi + tests=$(gh run list -R "$GITHUB_REPOSITORY" --workflow unit-tests.yml --branch main --commit "$GITHUB_SHA" \ + --json conclusion,event,headSha -L 20 | + jq -r --arg sha "$GITHUB_SHA" '[.[] | select(.headSha == $sha and (.event == "push" or .event == "workflow_dispatch"))][0].conclusion // empty') + if [ "$tests" != success ]; then + echo "::error::main ${GITHUB_SHA::7} has no passing Unit tests run (${tests:-none yet}): fix or 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" diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml new file mode 100644 index 0000000000..a2ef6cfe8e --- /dev/null +++ b/.github/workflows/unit-tests.yml @@ -0,0 +1,200 @@ +name: Unit tests +run-name: ${{ github.event_name == 'pull_request' && format('unit tests for pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('unit tests for {0} on {1}', github.ref_name, github.sha) }} + +# Runs beside Build APK rather than inside it, so a test build is published as soon as the APK compiles. +# Build validation folds this workflow's result into the "Build APK" commit status, and Release APKs requires it. +on: + push: + branches: [ main ] + paths-ignore: + - '**/*.md' + - 'LICENSE' + - '.gitignore' + - 'docs/**' + - '.github/ISSUE_TEMPLATE/**' + pull_request: + branches: [ main ] + types: [ opened, synchronize, reopened, ready_for_review ] + paths-ignore: + - '**/*.md' + - 'LICENSE' + - '.gitignore' + - 'docs/**' + - '.github/ISSUE_TEMPLATE/**' + workflow_dispatch: + +permissions: + contents: read + actions: read + +concurrency: + group: unit-tests-${{ github.event.pull_request.number || (github.event_name == 'push' && 'main') || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }} + +jobs: + unit-tests: + name: Unit tests + if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + sparse-checkout: | + /* + !/docs/releases/media/ + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Merge the pinned APK base + if: github.event_name == 'pull_request' + env: + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + set -euo pipefail + git config user.name "ci" + git config user.email "ci@users.noreply.github.com" + git fetch --no-tags origin "$PR_BASE_SHA" + git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true + git merge --no-ff --no-edit FETCH_HEAD || { echo "::error::the pull request conflicts with main; Build APK lists the files"; exit 1; } + + - name: Check out MaliBridge + run: git submodule update --init external/MaliBridge + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - uses: gradle/actions/setup-gradle@v4 + with: + cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }} + cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }} + + - name: Resolve the pinned Android NDK + run: bash tools/ci/resolve-ndk.sh + + - name: Set the APK build label + id: build-label + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_TITLE: ${{ github.event.pull_request.title }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + BUILD_REF: ${{ github.ref_name }} + BUILD_SHA: ${{ github.sha }} + run: bash tools/ci/build-label.sh + + - name: Resolve the Robolectric version + id: robolectric + run: | + echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT" + # Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes. + # The cache path sits beside the workspace because runner homes are at different depths from it, and + # actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects + # "..". Runners that keep their own ~/.m2 skip the cache. + - name: Place Robolectric's Android jars beside the workspace + id: robolectric-jars + run: | + set -euo pipefail + jars="$GITHUB_WORKSPACE/../robolectric-jars" + m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented" + if [ -d "$m2" ] && [ ! -L "$m2" ]; then + echo "cache=false" >> "$GITHUB_OUTPUT" + else + mkdir -p "$jars" "$(dirname "$m2")" + jars=$(cd "$jars" && pwd) + ln -sfn "$jars" "$m2" + echo "path=$jars" >> "$GITHUB_OUTPUT" + echo "cache=true" >> "$GITHUB_OUTPUT" + fi + - name: Restore Robolectric's Android jars + id: robolectric-cache + if: steps.robolectric-jars.outputs.cache == 'true' + uses: actions/cache/restore@v4 + with: + path: ${{ steps.robolectric-jars.outputs.path }} + key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} + restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}- + - name: Count the restored Robolectric jars + if: steps.robolectric-jars.outputs.cache == 'true' + run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV" + - name: Unit tests + id: unit-tests + env: + DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} + SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }} + run: | + set -o pipefail + mkdir -p app/build + log=app/build/unit-tests.log + attempt_log=app/build/unit-tests-attempt.log + : > "$log" + mirror=() + central='https://(repo1\.maven\.org|repo\.maven\.apache\.org)/maven2/org/robolectric/' + gradle_error='((Caused by: )?org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: |>[[:space:]]+)?' + java_error='((Caused by: )?java\.io\.IOException: )?' + # A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next. + for wait in 60 180 0; do + status=0 + ./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" "${mirror[@]}" 2>&1 | tee "$attempt_log" || status=$? + cat "$attempt_log" >> "$log" + if [ "$status" = 0 ] || [ "$wait" = 0 ]; then + exit "$status" + fi + if [ "${#mirror[@]}" = 0 ] && grep -qE \ + -e "^[[:space:]]*${gradle_error}Could not (GET|HEAD) '?${central}[^'[:space:]]+'?\. Received status code 429([[:space:]]|$)" \ + -e "^[[:space:]]*${java_error}Server returned HTTP response code: 429 for URL: ${central}[^[:space:]]+" "$attempt_log"; then + mirror=(-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2) + echo "::notice::Maven Central rate limited Robolectric. Retrying unit tests with the Google Cloud mirror." | tee -a "$log" + continue + fi + if ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' "$attempt_log"; then + exit "$status" + fi + echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" | tee -a "$log" + sleep "$wait" + done + + # actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache. + # Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first. + - name: Save Robolectric's Android jars + id: robolectric-jars-final + if: always() && steps.robolectric-jars.outputs.cache == 'true' + run: | + python3 - <<'PY' + import glob, os, zipfile + root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars') + for f in glob.glob(os.path.join(root, '**', '*'), recursive=True): + if not os.path.isfile(f): + continue + try: + ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None + except Exception: + ok = False + if not ok: + os.remove(f) + PY + after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l) + [ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true + - name: Store Robolectric's Android jars + if: always() && steps.robolectric-jars-final.outputs.save == 'true' + uses: actions/cache/save@v4 + with: + path: ${{ steps.robolectric-jars.outputs.path }} + key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} + + - name: Upload unit test diagnostics + id: unit-test-diagnostics + if: always() && steps.unit-tests.outcome != 'skipped' + uses: actions/upload-artifact@v4 + with: + name: unit-test-results + path: | + app/build/unit-tests.log + app/build/test-results/testReleaseUnitTest/ + app/build/reports/tests/testReleaseUnitTest/ + if-no-files-found: ignore + retention-days: 14 + overwrite: true diff --git a/AGENTS.md b/AGENTS.md index 97930d6563..d89bdf632c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ - For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step. - `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`. - Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout. -- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally. +- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest` in the `Unit tests` workflow, beside Build APK; when a test fails only in CI, run the release variant locally. - Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests ''` and `python3 -m unittest discover -s tools/tests -p 'test_*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI. - For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape. - After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`. @@ -31,7 +31,7 @@ - CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge. - Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors. - Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them. -- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs//logs`, or `gh run download -n unit-test-results`. Don't call a failure a runner problem until you have read it. +- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs//logs`, or `gh run download -n unit-test-results` from the `Unit tests` workflow run. Don't call a failure a runner problem until you have read it. - Only these are known flakes worth a `gh run rerun --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real. - A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`. diff --git a/README.md b/README.md index 576cf61c59..4a15571419 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Steam audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink`. - The DroidDeck HUD is [@The412Banner](https://github.com/The412Banner)'s [FusionHUD](https://github.com/The412Banner/FusionHUD) (GPL-3.0 with an attribution term). Its readings match Valve's [MangoHud](https://github.com/flightlessmango/MangoHud) build (MIT), with frame times from gamescope patch 0125. - The HUD's CPU, GPU load, thermal and battery readers come from [@xXJSONDeruloXx](https://github.com/xXJSONDeruloXx)'s work. -- LSFG frame generation comes from Camille LaVey and the [Eden](https://eden-emu.dev) project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported by [@maxjivi05](https://github.com/maxjivi05). It needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. +- LSFG frame generation comes from Camille LaVey and the [Eden](https://eden-emu.dev) project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported by [@maxjivi05](https://github.com/maxjivi05). It requires [Lossless Scaling](https://store.steampowered.com/app/993090/) installed through Steam and ships none of its shaders. - Black frame insertion follows the design of [@artzox](https://github.com/artzox)'s [BFI Presenter](https://github.com/artzox/BFI-Presenter) (GPL-3.0): the strobe runs on the display's refresh clock and the game is paced to the lit refresh. Both build on [Blur Busters](https://blurbusters.com)' research on MPRT and motion blur. No BFI Presenter code is used. - Remote Play decodes through Android's MediaCodec or the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) in Steam's runtime. Qualcomm low latency settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0). - [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) sockets use the settings in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions. diff --git a/app/build.gradle b/app/build.gradle index 25052d96bd..addaac3735 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -82,6 +82,8 @@ def buildBranch = providers.environmentVariable('GITHUB_HEAD_REF').getOrNull()?. ?: gitValue(['branch', '--show-current']) ?: '' def escapeJava = { String value -> value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', ' ').replace('\r', ' ') } def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true' +// The Unit tests workflow compiles no APK, so it has no add-on packs to pin. +def unitTestsOnly = project.findProperty('unitTestsOnly')?.toString()?.toBoolean() ?: false def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim() def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' } def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines() @@ -96,10 +98,12 @@ def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines() def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic', 'upscale'].collectEntries { name -> def pack = file("build/packs/${name}.tar.zst") if (!pack.isFile()) { - if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") + if (ciBuild && !unitTestsOnly) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) { return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]] } + // A CI APK pins every pack, and CI_BUILD code assumes that, so the tests see a placeholder pin. + if (unitTestsOnly) return [(name): [sha256: '0' * 64, size: 0L]] return [(name): [sha256: '', size: 0L]] } def digest = java.security.MessageDigest.getInstance('SHA-256') @@ -238,6 +242,9 @@ android { doFirst { jvmTemp.mkdirs() } def logTarget = providers.systemProperty('robolectric.logging').orNull if (logTarget != null) systemProperty 'robolectric.logging', logTarget + // Robolectric resolves Android SDK jars inside the test JVM independently of Gradle. + def robolectricMirror = providers.gradleProperty('robolectricMavenMirror').orNull + if (robolectricMirror) systemProperty 'robolectric.dependency.repo.url', robolectricMirror } } diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt index 0ab0ab8216..05d9559271 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -1,13 +1,17 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.material.icons.filled.Settings import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import com.droiddeck.launcher.R import com.droiddeck.launcher.input.SecondScreenMode @@ -26,6 +30,50 @@ private fun Launcher(tab: String, games: List Unit) = + DroidDeckTheme(frost = FrostChoice(transparency, cards, cardTransparency)) { + val wallpaper = Brush.linearGradient(listOf(Color(0xFFE2725B), Color(0xFF7A4BC2), Color(0xFF2A9D8F))) + Box(Modifier.fillMaxSize().background(wallpaper).background(LocalFrost.current ?: Color.Transparent)) { content() } + } + +@Composable +private fun FrostedLauncher(tab: String, transparency: Int = FROST_WALLPAPER_DEFAULT, cards: Boolean = false, cardTransparency: Int = FROST_DEFAULT) = + Frosted(transparency, cards, cardTransparency) { FrontEndScreen(sampleState(navigate = tab), sampleActions) } + +/** A settings step opened over frosted page text with see-through cards: the step is solid, so none of the text shows through it. */ +@Composable +private fun FrostedStepOut() = Frosted(cards = true) { + val text: @Composable (Int) -> String = { androidx.compose.ui.res.stringResource(it) } + Column(Modifier.padding(24.dp)) { + val line = List(8) { text(R.string.stores_shelf_new) }.joinToString(" ") + repeat(14) { androidx.compose.material3.Text(line, fontSize = 24.sp, color = LocalPalette.current.onBackground, maxLines = 1, softWrap = false) } + } + androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) { + val pill = with(androidx.compose.ui.platform.LocalDensity.current) { + androidx.compose.ui.geometry.Rect(androidx.compose.ui.geometry.Offset((maxWidth - 68.dp).toPx(), 16.dp.toPx()), androidx.compose.ui.geometry.Size(44.dp.toPx(), 44.dp.toPx())) + } + val accent = LocalPalette.current.signal + StepOut( + open = true, pill = pill, preferredSide = StepSide.Left, accent = accent, onDismiss = {}, onClosed = {}, items = 2, maxWidth = 440.dp, + handle = { androidx.compose.material3.Icon(androidx.compose.material.icons.Icons.Filled.Settings, null, tint = accent, modifier = Modifier.size(20.dp)) }, + ) { + StepTitle(text(R.string.stores_settings_eyebrow)) + Column(Modifier.stepItem(1)) { + SettingsRow(text(R.string.stores_show_mature), null) { ToggleSwitch(true, label = text(R.string.stores_show_mature)) {} } + SettingsRow(text(R.string.gog_achievements), text(R.string.gog_achievements_hint)) { ToggleSwitch(false, label = text(R.string.gog_achievements)) {} } + } + } + } +} + +@DroidDeckPreviews @Composable private fun FrostedSteamTabPreview() = FrostedLauncher("steam") +@DroidDeckPreviews @Composable private fun FrostedLibraryPreview() = FrostedLauncher("games") +@DroidDeckPreviews @Composable private fun FrostedSettingsCardsPreview() = FrostedLauncher("setup", cards = true) +@DroidDeckPreviews @Composable private fun FrostedSettingsClearestPreview() = FrostedLauncher("setup", transparency = FROST_MAX, cards = true, cardTransparency = FROST_MAX) +@DroidDeckPreviews @Composable private fun FrostedStepOutPreview() = FrostedStepOut() + /** The in-game menu on one page, as a session shows it. */ @Composable private fun SessionMenu(page: SessionDrawerPage, steam: Boolean = true, desktop: Boolean = false) = PreviewHost { @@ -72,6 +120,11 @@ internal val previewCases: List = listOf( PreviewCase("downloads") { Launcher("downloads") }, PreviewCase("settings") { Launcher("setup") }, PreviewCase("runtime-missing") { Launcher("setup", ready = false) }, + PreviewCase("frosted-steam-tab") { FrostedLauncher("steam") }, + PreviewCase("frosted-library", storesLoaded) { FrostedLauncher("games") }, + PreviewCase("frosted-settings-cards") { FrostedLauncher("setup", cards = true) }, + PreviewCase("frosted-settings-clearest") { FrostedLauncher("setup", transparency = FROST_MAX, cards = true, cardTransparency = FROST_MAX) }, + PreviewCase("frosted-step-out") { FrostedStepOut() }, PreviewCase("session-menu-controller") { SessionMenu(SessionDrawerPage.CONTROLLER) }, PreviewCase("session-menu-display") { SessionMenu(SessionDrawerPage.DISPLAY) }, PreviewCase("session-menu-hud") { SessionMenu(SessionDrawerPage.HUD) }, diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt index 96a958e719..8a7da4c5d0 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt @@ -59,7 +59,7 @@ internal fun sampleState( internal val sampleActions: FrontEndActions = FrontEndActions( onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, - onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, + onFrameGenPick = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, ) @@ -82,7 +82,7 @@ internal fun sampleDrawerActions( secondScreenDisplays = listOfNotNull(secondScreen?.let { SecondScreenDisplay(2, "Built-in · 1240×1080") }), selectedSecondScreenDisplay = if (secondScreen != null) 2 else -1, onSecondScreenDisplay = {}, gameSwapAvailable = secondScreen != null, dashboardAvailable = secondScreen != null, - onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, + onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null, onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {}, ) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 55b75d36df..5db5b11509 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -33,6 +33,9 @@ + + @@ -274,6 +277,17 @@ android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" android:theme="@style/AppTheme" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/assets/agent/dd-gh-login b/app/src/main/assets/agent/dd-gh-login index f9b0b7734a..e02054ffc1 100644 --- a/app/src/main/assets/agent/dd-gh-login +++ b/app/src/main/assets/agent/dd-gh-login @@ -28,6 +28,19 @@ float_code() { [ "$result" = ok ] } +# git pushes through gh's sign-in and commits as the signed-in account, with its no-reply address. +configure_git() { + gh auth setup-git || return 1 + [ -n "$(git config --global user.name)" ] && [ -n "$(git config --global user.email)" ] && return 0 + local user id login name + user=$(gh api user -q '"\(.id) \(.login) \(.name // .login)"') || return 1 + read -r id login name <<<"$user" + [ -n "$id" ] && [ -n "$login" ] || return 1 + [ -n "$(git config --global user.name)" ] || git config --global user.name "${name:-$login}" + [ -n "$(git config --global user.email)" ] || git config --global user.email "$id+$login@users.noreply.github.com" +} +if [ "${1:-}" = --git ]; then configure_git; exit; fi + coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; } gh_pid=$GH_PID exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}" @@ -48,5 +61,9 @@ while IFS= read -r line <&"$ghout"; do done wait "$gh_pid" status=$? +if [ $status = 0 ] && ! configure_git; then + echo "Signed in, but git could not be set up: run dd-gh-login --git" + status=1 +fi [ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code" exit $status diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index d81f46c880..2aa4089a17 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -10,6 +10,17 @@ add_subdirectory(adrenotools) add_subdirectory(thirdparty/dxbc) +# Pin ZeroFG to a fixed revision instead of vendoring thousands of generated shader lines. +include(FetchContent) +set(ZEROFG_VULKAN_HEADERS_DIR "${CMAKE_SYSROOT}/usr/include" CACHE PATH "" FORCE) +set(ZEROFG_PREBUILT_SHADERS ON CACHE STRING "" FORCE) +FetchContent_Declare(zerofg + GIT_REPOSITORY https://github.com/hy300leosquizz-ctrl/ZeroFG.git + GIT_TAG e6ca7ef9f9765db89847b6d8eed352e458f1a8bb + GIT_PROGRESS TRUE +) +FetchContent_MakeAvailable(zerofg) + set(DDFG_UPSTREAM "v0.3.0") set(DDFG_CHAIN_SRC framegen/ddfg/framegen.cpp diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp index 2e0aaa927d..856501cb3c 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -4130,6 +4130,24 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { return read_input(fd, buf, count); } +// glibc's fortify failure; bionic (DroidDeck-Bionic preloads this library into its Wine processes) has no +// __chk_fail, and a library naming it there cannot be loaded, which stops every Wine program from starting. +#if defined(__BIONIC__) +[[noreturn]] static void fakeinput_chk_fail(void) { abort(); } +#else +extern "C" [[noreturn]] void __chk_fail(void); +[[noreturn]] static void fakeinput_chk_fail(void) { __chk_fail(); } +#endif + +/* Programs built with _FORTIFY_SOURCE (Flatpak runtimes among them) call these instead of read, poll + * and ppoll, and glibc's versions go straight to the kernel. */ +EXPORT ssize_t __read_chk(int fd, void *buf, size_t count, size_t buflen) { + static auto next_read_chk = reinterpret_cast(dlsym(RTLD_NEXT, "__read_chk")); + if (count > buflen) fakeinput_chk_fail(); + if (next_read_chk && !is_fake_input_fd(fd)) return next_read_chk(fd, buf, count, buflen); + return read_input(fd, buf, count); +} + EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) { if (!is_fake_input_fd(fd)) return syscall(SYS_readv, fd, iov, iovcnt); if (iovcnt < 0 || iovcnt > IOV_MAX) { @@ -4378,6 +4396,17 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds, return my_ppoll(fds, nfds, timeout, sigmask); } +EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) { + if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail(); + return poll(fds, nfds, timeout); +} + +EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, + const sigset_t *sigmask, size_t fdslen) { + if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail(); + return ppoll(fds, nfds, timeout, sigmask); +} + EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) { const auto my_select = next_symbol(Next::select); diff --git a/app/src/main/cpp/framegen/ddfg/ddfg_engine.cpp b/app/src/main/cpp/framegen/ddfg/ddfg_engine.cpp index 6e87890b3f..034f2c4d55 100644 --- a/app/src/main/cpp/framegen/ddfg/ddfg_engine.cpp +++ b/app/src/main/cpp/framegen/ddfg/ddfg_engine.cpp @@ -27,7 +27,31 @@ VkImageMemoryBarrier bar(VkImage img, VkImageLayout from, VkImageLayout to, } Engine::Engine() = default; -Engine::~Engine() { destroyRing(); fg_.destroy(); } +Engine::~Engine() { (void)destroy(); } + +bool Engine::destroy() { + if (!fg_.destroy()) { + DDFG_LOGE("native: retaining the input ring because GPU completion is unknown"); + return false; + } + if (!destroyRing(true)) { + DDFG_LOGE("native: could not release the input ring during teardown"); + return false; + } + dev_ = VK_NULL_HANDLE; + unavailable_ = true; + return true; +} + +void Engine::abandon() { + fg_.abandon(); + ring_[0] = Slot{}; + ring_[1] = Slot{}; + dev_ = VK_NULL_HANDLE; + queue_ = VK_NULL_HANDLE; + phys_ = VK_NULL_HANDLE; + unavailable_ = true; +} bool Engine::init(const VkTable& table, VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue) { @@ -59,15 +83,29 @@ bool Engine::prepare(uint32_t w, uint32_t h, VkFormat fmt) { if (unavailable_ || w == 0 || h == 0 || fmt == VK_FORMAT_UNDEFINED) return false; if (builtW_ == w && builtH_ == h && builtFmt_ == fmt && fg_.valid()) return true; - - if (!fg_.onResize(VkExtent2D{w, h}, fmt, false)) { + const bool formatChanged = fmt != builtFmt_; + if (!fg_.onResize(VkExtent2D{w, h}, fmt, formatChanged)) { DDFG_LOGE("native: onResize %ux%u failed; frame generation unavailable", w, h); unavailable_ = true; return false; } - destroyRing(); + bool deviceLost = false; + if (!destroyRing(false, &deviceLost)) { + DDFG_LOGE("native: could not safely release the previous input ring"); + unavailable_ = true; + return false; + } + if (deviceLost) { + DDFG_LOGE("native: device lost while releasing the input ring"); + unavailable_ = true; + return false; + } for (Slot& s : ring_) { - if (!makeSlot(s, w, h, fmt)) { destroyRing(); unavailable_ = true; return false; } + if (!makeSlot(s, w, h, fmt)) { + destroyRing(true); + unavailable_ = true; + return false; + } } builtW_ = w; builtH_ = h; builtFmt_ = fmt; history_ = 0; curr_ = 0; frames_ = 0; @@ -178,11 +216,37 @@ void Engine::destroySlot(Slot& s) { s = Slot{}; } -void Engine::destroyRing() { - if (dev_ == VK_NULL_HANDLE || !dd_.DeviceWaitIdle) return; - if (ring_[0].img || ring_[1].img) dd_.DeviceWaitIdle(dev_); - destroySlot(ring_[0]); destroySlot(ring_[1]); +bool Engine::destroyRing(bool deviceIdleConfirmed, bool* deviceLost) { + if (deviceLost) *deviceLost = false; + const bool hasResources = ring_[0].img || ring_[0].mem || ring_[0].view || + ring_[1].img || ring_[1].mem || ring_[1].view; + if (!hasResources) { + history_ = 0; + return true; + } + if (dev_ == VK_NULL_HANDLE) { + DDFG_LOGE("native: cannot release the input ring without a valid device"); + return false; + } + if (!deviceIdleConfirmed) { + if (!dd_.DeviceWaitIdle) { + DDFG_LOGE("native: cannot release the input ring without vkDeviceWaitIdle"); + return false; + } + const VkResult result = dd_.DeviceWaitIdle(dev_); + if (result == VK_ERROR_DEVICE_LOST) { + if (deviceLost) *deviceLost = true; + unavailable_ = true; + } else if (result != VK_SUCCESS) { + DDFG_LOGE("native: DeviceWaitIdle failed (%d); retaining the input ring", (int)result); + unavailable_ = true; + return false; + } + } + destroySlot(ring_[0]); + destroySlot(ring_[1]); history_ = 0; + return true; } } diff --git a/app/src/main/cpp/framegen/ddfg/ddfg_engine.h b/app/src/main/cpp/framegen/ddfg/ddfg_engine.h index 55c1ef8fa0..aff10a9033 100644 --- a/app/src/main/cpp/framegen/ddfg/ddfg_engine.h +++ b/app/src/main/cpp/framegen/ddfg/ddfg_engine.h @@ -36,13 +36,15 @@ public: uint32_t width, uint32_t height); void reset(); + bool destroy(); + void abandon(); private: struct Slot { VkImage img = VK_NULL_HANDLE; VkDeviceMemory mem = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; bool valid = false; }; bool makeSlot(Slot& s, uint32_t w, uint32_t h, VkFormat fmt); void destroySlot(Slot& s); - void destroyRing(); + bool destroyRing(bool deviceIdleConfirmed = false, bool* deviceLost = nullptr); uint32_t memType(uint32_t bits, VkMemoryPropertyFlags props) const; DeviceDispatch dd_{}; diff --git a/app/src/main/cpp/framegen/ddfg/framegen.cpp b/app/src/main/cpp/framegen/ddfg/framegen.cpp index 330f83a7cf..20cc5e2d4a 100644 --- a/app/src/main/cpp/framegen/ddfg/framegen.cpp +++ b/app/src/main/cpp/framegen/ddfg/framegen.cpp @@ -7,6 +7,31 @@ namespace ddfg { +struct ScratchState { + VkDevice ownerDevice = VK_NULL_HANDLE; + VkBuffer synthUbo[ddfg::FrameGen::kSynthSlots]{}; + VkDeviceMemory synthUboMem[ddfg::FrameGen::kSynthSlots]{}; + void* synthUboPtr[ddfg::FrameGen::kSynthSlots]{}; + std::vector flowUbo; std::vector flowUboMem; std::vector flowUboPtr; + VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr; + VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr; + VkBuffer gmUbo[ddfg::FrameGen::kGmSlots]{}; + VkDeviceMemory gmUboMem[ddfg::FrameGen::kGmSlots]{}; + void* gmUboPtr[ddfg::FrameGen::kGmSlots]{}; + VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE; + std::vector sDownA, sDownB, sFlow; + VkDescriptorSet sExpand[ddfg::FrameGen::kGmSlots]{}; + VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE; + VkDescriptorSet sSynth[ddfg::FrameGen::kSynthSlots]{}; + VkDescriptorSet sGmReduce[ddfg::FrameGen::kGmSlots]{}; + std::vector sGmPrewarp[ddfg::FrameGen::kGmSlots]; + VkExtent2D builtFor{0,0}; + uint64_t builtGeneration = 0; + bool built = false; + bool flowInited = false; + bool flowReady = false; +}; + #define VKOK(x) do { if ((x) != VK_SUCCESS) { DDFG_LOGE("vk fail: %s", #x); return false; } } while (0) uint32_t FrameGen::findMemType(uint32_t bits, VkMemoryPropertyFlags props) const { @@ -108,6 +133,10 @@ static bool buildSetLayout(const DeviceDispatch* dd, VkDevice dev, bool FrameGen::init(const DeviceDispatch* dd, const InstanceDispatch* id, VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue) { + if (device_ || completionUnknown_ || deviceLost_) { + DDFG_LOGE("framegen: refusing to initialize an instance that still owns device resources"); + return false; + } dd_ = dd; id_ = id; phys_ = phys; device_ = dev; queueFamily_ = queueFamily; queue_ = queue; id_->GetPhysicalDeviceMemoryProperties(phys_, &memProps_); @@ -166,16 +195,19 @@ static VkExtent2D levelExtent(VkExtent2D e, int l) { } bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) { - - - if (!force && ready_ && extent.width == extent_.width && extent.height == extent_.height) return true; - if (ready_) { - const VkResult idleResult = dd_->DeviceWaitIdle(device_); - if (idleResult != VK_SUCCESS) { - DDFG_LOGE("framegen resize: DeviceWaitIdle failed (%d); keeping existing images", (int)idleResult); - return false; - } + if (completionUnknown_ || deviceLost_) return false; + if (!device_) { + DDFG_LOGE("framegen: cannot resize before device initialization"); + return false; } + if (!force && ready_ && extent.width == extent_.width && extent.height == extent_.height) return true; + if (ready_ && !waitIdle("resize")) return false; + if (scratch_ && scratch_->ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) { + DDFG_LOGE("framegen resize: scratch cleanup failed; retaining the previous image set"); + return false; + } + + ready_ = false; ++imageGeneration_; for (auto& i : pyrA_) destroyImage(i); pyrA_.clear(); for (auto& i : pyrB_) destroyImage(i); pyrB_.clear(); @@ -183,7 +215,17 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) { for (auto& i : flowLvl_) destroyImage(i); flowLvl_.clear(); destroyImage(flowExpA_); destroyImage(flowExpB_); destroyImage(flowRegA_); destroyImage(flowRegB_); - extent_ = extent; ready_ = false; + extent_ = extent; + + for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0; + for (int s = 0; s < kGmSlots; ++s) { + gmSlotValid_[s] = false; + for (int i = 0; i < 6; ++i) gmLinAt_[s][i] = 0.0; + } + gmHaveEst_ = false; + gmEngaged_ = false; + gmStableCount_ = 0; + gmLastTransPx_ = 0.0f; const VkImageUsageFlags lumaUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT; const VkImageUsageFlags flowUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; @@ -234,21 +276,37 @@ void FrameGen::initializeImage(VkCommandBuffer cmd, VkImage img, VkImageLayout t } -void FrameGen::destroy() { - if (!device_) return; - const VkResult idleResult = dd_->DeviceWaitIdle(device_); - if (idleResult != VK_SUCCESS && idleResult != VK_ERROR_DEVICE_LOST) { - DDFG_LOGE("framegen destroy: DeviceWaitIdle failed (%d); preserving resources for safe retry", (int)idleResult); - return; - } - if (idleResult == VK_ERROR_DEVICE_LOST) { - // A lost device cannot become idle again. Still explicitly destroy its - // child objects; skip descriptor-pool reset and release scratch ownership. - DDFG_LOGE("framegen destroy: device lost; releasing owned resources without waiting"); - destroyScratchResources(false); - } else { - destroyScratchResources(); +bool FrameGen::destroy() { + if (!device_) return true; + if (!deviceLost_) { + // A previous wait failure leaves completion unknown, but a later + // teardown attempt may safely retry the wait before releasing resources. + if (!dd_ || !dd_->DeviceWaitIdle) { + ready_ = false; + completionUnknown_ = true; + DDFG_LOGE("framegen destroy: vkDeviceWaitIdle is unavailable; preserving GPU resources"); + return false; + } + const VkResult idleResult = dd_->DeviceWaitIdle(device_); + if (idleResult == VK_SUCCESS) completionUnknown_ = false; + if (idleResult != VK_SUCCESS) { + ready_ = false; + if (idleResult == VK_ERROR_DEVICE_LOST) { + deviceLost_ = true; + DDFG_LOGE("framegen destroy: device lost; releasing owned resources without waiting"); + } else { + completionUnknown_ = true; + DDFG_LOGE("framegen destroy: DeviceWaitIdle failed (%d); preserving resources because GPU completion is unknown", + (int)idleResult); + return false; + } + } } + + ready_ = false; + if (descPool_) dd_->DestroyDescriptorPool(device_, descPool_, nullptr); + descPool_ = VK_NULL_HANDLE; + releaseScratch(); for (auto& i : pyrA_) destroyImage(i); pyrA_.clear(); for (auto& i : pyrB_) destroyImage(i); pyrB_.clear(); for (auto& i : pyrAs_) destroyImage(i); pyrAs_.clear(); @@ -260,15 +318,45 @@ void FrameGen::destroy() { destroyPipe(pGmReduce_); destroyPipe(pGmPrewarp_); destroyPipe(pFlowReg_); for (int s = 0; s < kGmSlots; ++s) { - if (gmSsboMem_[s]) dd_->UnmapMemory(device_, gmSsboMem_[s]); + if (gmSsboPtr_[s] && gmSsboMem_[s]) dd_->UnmapMemory(device_, gmSsboMem_[s]); if (gmSsbo_[s]) dd_->DestroyBuffer(device_, gmSsbo_[s], nullptr); if (gmSsboMem_[s]) dd_->FreeMemory(device_, gmSsboMem_[s], nullptr); gmSsbo_[s] = VK_NULL_HANDLE; gmSsboMem_[s] = VK_NULL_HANDLE; gmSsboPtr_[s] = nullptr; } gmBuffersReady_ = false; - if (descPool_) dd_->DestroyDescriptorPool(device_, descPool_, nullptr); if (linear_) dd_->DestroySampler(device_, linear_, nullptr); - descPool_ = VK_NULL_HANDLE; linear_ = VK_NULL_HANDLE; device_ = VK_NULL_HANDLE; ready_ = false; + linear_ = VK_NULL_HANDLE; + device_ = VK_NULL_HANDLE; + ready_ = false; + deviceLost_ = false; + return true; +} + +void FrameGen::abandon() { + device_ = VK_NULL_HANDLE; + dd_ = nullptr; + id_ = nullptr; + phys_ = VK_NULL_HANDLE; + queue_ = VK_NULL_HANDLE; + linear_ = VK_NULL_HANDLE; + descPool_ = VK_NULL_HANDLE; + scratch_.reset(); + pyrA_.clear(); pyrB_.clear(); pyrAs_.clear(); flowLvl_.clear(); + flowExpA_ = Img{}; flowExpB_ = Img{}; + flowRegA_ = Img{}; flowRegB_ = Img{}; + pLuma_ = Pipe{}; pDown_ = Pipe{}; pFlow_ = Pipe{}; pFlowM4_ = Pipe{}; + pExpand_ = Pipe{}; pExpandM4_ = Pipe{}; pSynth_ = Pipe{}; + pGmReduce_ = Pipe{}; pGmPrewarp_ = Pipe{}; pFlowReg_ = Pipe{}; + for (int s = 0; s < kGmSlots; ++s) { + gmSsbo_[s] = VK_NULL_HANDLE; + gmSsboMem_[s] = VK_NULL_HANDLE; + gmSsboPtr_[s] = nullptr; + gmSlotValid_[s] = false; + } + gmBuffersReady_ = false; + ready_ = false; + completionUnknown_ = false; + deviceLost_ = false; } } diff --git a/app/src/main/cpp/framegen/ddfg/framegen.hpp b/app/src/main/cpp/framegen/ddfg/framegen.hpp index d40518dd1d..bba77480c7 100644 --- a/app/src/main/cpp/framegen/ddfg/framegen.hpp +++ b/app/src/main/cpp/framegen/ddfg/framegen.hpp @@ -1,12 +1,20 @@ #pragma once #include "vk_dispatch.hpp" #include "config.hpp" +#include #include namespace ddfg { +struct ScratchState; + class FrameGen { public: + FrameGen(); + ~FrameGen(); + FrameGen(const FrameGen&) = delete; + FrameGen& operator=(const FrameGen&) = delete; + bool init(const DeviceDispatch* dd, const InstanceDispatch* id, VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue); void configure(const Config& c); @@ -14,7 +22,8 @@ public: void record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView, VkImageView outView, float alpha, uint32_t gmSlot = 0, uint32_t synthSlot = 0, bool reuseFlow = false); - void destroy(); + bool destroy(); + void abandon(); bool valid() const { return device_ != VK_NULL_HANDLE && ready_; } const Config& config() const { return cfg_; } @@ -64,7 +73,9 @@ private: void destroyPipe(Pipe& p); void barrier(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to); void initializeImage(VkCommandBuffer cmd, VkImage img, VkImageLayout to); - void destroyScratchResources(bool resetPool = true); + bool waitIdle(const char* operation); + bool destroyScratchResources(bool resetPool = true); + void releaseScratch(); const DeviceDispatch* dd_ = nullptr; const InstanceDispatch* id_ = nullptr; @@ -80,7 +91,10 @@ private: VkExtent2D extent_{}; uint64_t imageGeneration_ = 0; bool ready_ = false; + bool completionUnknown_ = false; + bool deviceLost_ = false; int flowFinest_ = kFlowFinestDefault; + std::unique_ptr scratch_; Pipe pLuma_, pDown_, pFlow_, pFlowM4_, pExpand_, pExpandM4_, pSynth_; Pipe pGmReduce_, pGmPrewarp_; diff --git a/app/src/main/cpp/framegen/ddfg/record_impl.inc b/app/src/main/cpp/framegen/ddfg/record_impl.inc index 1d9e71df8c..3922db391b 100644 --- a/app/src/main/cpp/framegen/ddfg/record_impl.inc +++ b/app/src/main/cpp/framegen/ddfg/record_impl.inc @@ -1,33 +1,7 @@ -namespace { -struct ScratchState { - VkDevice ownerDevice = VK_NULL_HANDLE; - VkBuffer synthUbo[ddfg::FrameGen::kSynthSlots]{}; - VkDeviceMemory synthUboMem[ddfg::FrameGen::kSynthSlots]{}; - void* synthUboPtr[ddfg::FrameGen::kSynthSlots]{}; - std::vector flowUbo; std::vector flowUboMem; std::vector flowUboPtr; - VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr; - VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr; - VkBuffer gmUbo[ddfg::FrameGen::kGmSlots]{}; - VkDeviceMemory gmUboMem[ddfg::FrameGen::kGmSlots]{}; - void* gmUboPtr[ddfg::FrameGen::kGmSlots]{}; - VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE; - std::vector sDownA, sDownB, sFlow; - VkDescriptorSet sExpand[ddfg::FrameGen::kGmSlots]{}; - - - - VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE; - VkDescriptorSet sSynth[ddfg::FrameGen::kSynthSlots]{}; - VkDescriptorSet sGmReduce[ddfg::FrameGen::kGmSlots]{}; - std::vector sGmPrewarp[ddfg::FrameGen::kGmSlots]; - VkExtent2D builtFor{0,0}; - uint64_t builtGeneration = 0; - bool built = false; - bool flowInited = false; - bool flowReady = false; -}; -ScratchState g_scratch; +namespace ddfg { +FrameGen::FrameGen() : scratch_(std::make_unique()) {} +FrameGen::~FrameGen() { (void)destroy(); } } static bool makeUbo(const ddfg::DeviceDispatch* dd, VkDevice dev, @@ -144,7 +118,7 @@ static void mulAff(const double A[3][3], const double B[3][3], double out[3][3]) namespace ddfg { -static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, +static bool ensureScratch(ScratchState& S, FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool, VkSampler samp, VkExtent2D ext, std::vector& pyrA, std::vector& pyrB, @@ -157,30 +131,72 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, FrameGen::Img& flowRegA, FrameGen::Img& flowRegB, VkBuffer* gmSsbo, int kLevels, const Config& cfg, uint64_t imageGeneration); -static void destroyScratch(const DeviceDispatch* dd, VkDevice dev, VkDescriptorPool pool, - bool resetPool = true) { - if (g_scratch.ownerDevice != VK_NULL_HANDLE && g_scratch.ownerDevice != dev) return; +bool FrameGen::waitIdle(const char* operation) { + if (completionUnknown_ || deviceLost_ || !device_) return false; + if (!dd_ || !dd_->DeviceWaitIdle) { + completionUnknown_ = true; + ready_ = false; + DDFG_LOGE("framegen: %s cannot confirm GPU completion; this instance is stopped and its resources are retained", + operation); + return false; + } + const VkResult result = dd_->DeviceWaitIdle(device_); + if (result == VK_SUCCESS) return true; + ready_ = false; + if (result == VK_ERROR_DEVICE_LOST) { + deviceLost_ = true; + DDFG_LOGE("framegen: %s reported device loss; cleanup will skip further waits", operation); + } else { + completionUnknown_ = true; + DDFG_LOGE("framegen: %s vkDeviceWaitIdle failed (%d); this instance is stopped and its GPU resources retained", + operation, (int)result); + } + return false; +} + +bool FrameGen::destroyScratchResources(bool resetPool) { + if (!scratch_) return true; + if (resetPool && descPool_ && !deviceLost_) { + if (!dd_ || !dd_->ResetDescriptorPool) { + ready_ = false; + DDFG_LOGE("framegen: descriptor-pool reset is unavailable; retaining scratch resources"); + return false; + } + const VkResult result = dd_->ResetDescriptorPool(device_, descPool_, 0); + if (result != VK_SUCCESS) { + ready_ = false; + if (result == VK_ERROR_DEVICE_LOST) deviceLost_ = true; + DDFG_LOGE("framegen: descriptor-pool reset failed (%d); retaining scratch resources", + (int)result); + return false; + } + } + releaseScratch(); + return true; +} + +void FrameGen::releaseScratch() { + if (!scratch_) return; + auto& S = *scratch_; auto freeUbo = [&](VkBuffer& b, VkDeviceMemory& m, void*& p) { - if (m) dd->UnmapMemory(dev, m); - if (b) dd->DestroyBuffer(dev, b, nullptr); - if (m) dd->FreeMemory(dev, m, nullptr); - b = VK_NULL_HANDLE; m = VK_NULL_HANDLE; p = nullptr; + if (p && m) dd_->UnmapMemory(device_, m); + if (b) dd_->DestroyBuffer(device_, b, nullptr); + if (m) dd_->FreeMemory(device_, m, nullptr); + b = VK_NULL_HANDLE; + m = VK_NULL_HANDLE; + p = nullptr; }; - auto& S = g_scratch; for (int s = 0; s < FrameGen::kSynthSlots; ++s) freeUbo(S.synthUbo[s], S.synthUboMem[s], S.synthUboPtr[s]); - freeUbo(S.expandUbo, S.expandUboMem, S.expandUboPtr); + freeUbo(S.expandUbo, S.expandUboMem, S.expandUboPtr); freeUbo(S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr); for (size_t i = 0; i < S.flowUbo.size(); ++i) freeUbo(S.flowUbo[i], S.flowUboMem[i], S.flowUboPtr[i]); for (int s = 0; s < FrameGen::kGmSlots; ++s) freeUbo(S.gmUbo[s], S.gmUboMem[s], S.gmUboPtr[s]); - if (resetPool && pool && dd->ResetDescriptorPool) dd->ResetDescriptorPool(dev, pool, 0); S = ScratchState{}; } -void FrameGen::destroyScratchResources(bool resetPool) { - destroyScratch(dd_, device_, descPool_, resetPool); -} void FrameGen::configure(const Config& c) { + if (completionUnknown_ || deviceLost_) return; Config nextCfg = c; nextCfg.sanitize(); int want = flowFinestForPreset(nextCfg.perfPreset); @@ -203,16 +219,12 @@ void FrameGen::configure(const Config& c) { return; } - // Keep the previous configuration and image set if the device cannot idle. - const VkResult idleResult = dd_->DeviceWaitIdle(device_); - if (idleResult != VK_SUCCESS) { - DDFG_LOGE("framegen configure: DeviceWaitIdle failed (%d); keeping previous configuration and images", - (int)idleResult); + if (!waitIdle("live preset rebuild")) return; + if (scratch_ && scratch_->ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) { + DDFG_LOGE("perf-preset live rebuild: scratch cleanup failed; keeping the previous configuration"); return; } - // The device is idle, so reset motion history before rebuilding. This - // also leaves the predictor reset if onResize fails. for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0; for (int s = 0; s < kGmSlots; ++s) { gmSlotValid_[s] = false; @@ -223,20 +235,17 @@ void FrameGen::configure(const Config& c) { gmStableCount_ = 0; gmLastTransPx_ = 0.0f; - // Prevent onResize from issuing a second wait. - destroyScratch(dd_, device_, descPool_); cfg_ = nextCfg; flowFinest_ = want; ready_ = false; if (!onResize(extent_, VK_FORMAT_UNDEFINED, true)) { ready_ = false; - DDFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - FG disabled until next resize", + DDFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - frame generation unavailable", extent_.width, extent_.height); return; } DDFG_LOGI("perf-preset live rebuild DONE (kFlowFinest=%d, flow predictor reset)", flowFinest_); } - bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) { ++gmFrames_; if (!gmBuffersReady_ || cfg_.gmMode == 2 ) { @@ -306,35 +315,33 @@ bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) { void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView, VkImageView outView, float alpha, uint32_t gmSlot, uint32_t synthSlot, bool reuseFlow) { if (!valid()) return; + auto& S = *scratch_; if (gmSlot >= (uint32_t)kGmSlots) gmSlot = 0; if (synthSlot >= (uint32_t)kSynthSlots) synthSlot = 0; const bool m4 = (cfg_.model == 4); const Pipe& flowP = m4 ? pFlowM4_ : pFlow_; const Pipe& expandP = m4 ? pExpandM4_ : pExpand_; - if (!g_scratch.built || g_scratch.builtFor.width != extent_.width || - g_scratch.builtFor.height != extent_.height || - g_scratch.builtGeneration != imageGeneration_) { - if (g_scratch.built) { - const VkResult idleResult = dd_->DeviceWaitIdle(device_); - if (idleResult != VK_SUCCESS) { - DDFG_LOGE("framegen record: DeviceWaitIdle failed (%d); skipping scratch rebuild", (int)idleResult); - return; - } - destroyScratch(dd_, device_, descPool_); + if (!S.built || S.builtFor.width != extent_.width || + S.builtFor.height != extent_.height || + S.builtGeneration != imageGeneration_) { + if (S.built && !waitIdle("scratch rebuild")) return; + if (S.ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) { + DDFG_LOGE("framegen record: scratch cleanup failed; skipping this frame"); + return; } - if (!ensureScratch(this, dd_, device_, memProps_, descPool_, linear_, extent_, + if (!ensureScratch(S, this, dd_, device_, memProps_, descPool_, linear_, extent_, pyrA_, pyrB_, pyrAs_, flowLvl_, flowExpA_, flowExpB_, pLuma_, pDown_, flowP, expandP, pSynth_, pGmReduce_, pGmPrewarp_, pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_, imageGeneration_)) return; } - if (g_scratch.ownerDevice != device_) return; - if (reuseFlow && !g_scratch.flowReady) return; + if (S.ownerDevice != device_) return; + if (reuseFlow && !S.flowReady) return; if (!reuseFlow) { bool gmEngaged = updateGlobalMotion(gmSlot, extent_); - if (g_scratch.gmUboPtr[gmSlot]) { + if (S.gmUboPtr[gmSlot]) { GMUBO g{}; g.lin[0]=(float)gmRun_[0]; g.lin[1]=(float)gmRun_[1]; g.lin[2]=(float)gmRun_[2]; g.lin[3]=(float)gmRun_[3]; g.linT[0]=(float)gmRun_[4]; g.linT[1]=(float)gmRun_[5]; g.linT[2]=gmEngaged?1.0f:0.0f; g.linT[3]=0.0f; @@ -342,7 +349,7 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur g.app[0]=(float)gmRun_[0]; g.app[1]=(float)gmRun_[1]; g.app[2]=(float)gmRun_[2]; g.app[3]=(float)gmRun_[3]; g.appT[0]=(float)gmRun_[4]; g.appT[1]=(float)gmRun_[5]; } - std::memcpy(g_scratch.gmUboPtr[gmSlot], &g, sizeof(g)); + std::memcpy(S.gmUboPtr[gmSlot], &g, sizeof(g)); } { static int lastEng = -1; @@ -353,7 +360,7 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur } } - const VkDescriptorSet lumaSets[] = {g_scratch.sLumaCurr, g_scratch.sLumaPrev}; + const VkDescriptorSet lumaSets[] = {S.sLumaCurr, S.sLumaPrev}; const uint32_t lumaBindings[] = {32, 32}; const VkDescriptorType lumaTypes[] = { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER}; @@ -367,9 +374,9 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur SynthUBO su{cfg_.flowScale, alpha, cfg_.beta, cfg_.lambda, cfg_.epsilon, cfg_.photoScale, 0, 0, cfg_.hudX0, cfg_.hudY0, cfg_.hudX1, cfg_.hudY1}; - if (g_scratch.synthUboPtr[synthSlot]) std::memcpy(g_scratch.synthUboPtr[synthSlot], &su, sizeof(su)); + if (S.synthUboPtr[synthSlot]) std::memcpy(S.synthUboPtr[synthSlot], &su, sizeof(su)); - const VkDescriptorSet synthSet = g_scratch.sSynth[synthSlot]; + const VkDescriptorSet synthSet = S.sSynth[synthSlot]; const VkDescriptorSet synthSets[] = {synthSet, synthSet, synthSet}; const uint32_t synthBindings[] = {32, 33, 48}; const VkDescriptorType synthTypes[] = { @@ -468,17 +475,17 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &b); } - disp(pLuma_, g_scratch.sLumaCurr, levelExtent(extent_, 0)); - disp(pLuma_, g_scratch.sLumaPrev, levelExtent(extent_, 0)); + disp(pLuma_, S.sLumaCurr, levelExtent(extent_, 0)); + disp(pLuma_, S.sLumaPrev, levelExtent(extent_, 0)); barPair(pyrA_[0], pyrB_[0]); for (int l = 1; l < kLevels; ++l) { - disp(pDown_, g_scratch.sDownA[l - 1], levelExtent(extent_, l)); - disp(pDown_, g_scratch.sDownB[l - 1], levelExtent(extent_, l)); + disp(pDown_, S.sDownA[l - 1], levelExtent(extent_, l)); + disp(pDown_, S.sDownB[l - 1], levelExtent(extent_, l)); barPair(pyrA_[l], pyrB_[l]); } - if (gmBuffersReady_ && g_scratch.sGmReduce[gmSlot]) { + if (gmBuffersReady_ && S.sGmReduce[gmSlot]) { dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.pipeline); - dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &g_scratch.sGmReduce[gmSlot], 0, nullptr); + dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &S.sGmReduce[gmSlot], 0, nullptr); dd_->CmdDispatch(cmd, (uint32_t)(kGmThreads / 64), 1, 1); VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; mb.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; mb.dstAccessMask = VK_ACCESS_HOST_READ_BIT; @@ -486,27 +493,27 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur 0, 1, &mb, 0, nullptr, 0, nullptr); } for (int l = flowFinest_; l < kLevels; ++l) { - disp(pGmPrewarp_, g_scratch.sGmPrewarp[gmSlot][l], levelExtent(extent_, l)); + disp(pGmPrewarp_, S.sGmPrewarp[gmSlot][l], levelExtent(extent_, l)); bar(pyrAs_[l]); } for (int l = kLevels - 1; l >= flowFinest_; --l) { - disp(flowP, g_scratch.sFlow[l], levelExtent(extent_, l)); + disp(flowP, S.sFlow[l], levelExtent(extent_, l)); bar(flowLvl_[l]); } if (frEngaged) { const int F = flowFinest_; const VkExtent2D fe = levelExtent(extent_, F); - if (g_scratch.flowRegUboPtr) { + if (S.flowRegUboPtr) { FlowRegUBO fu{cfg_.frDt, cfg_.frLambda, cfg_.frEdge, cfg_.frEps}; - std::memcpy(g_scratch.flowRegUboPtr, &fu, sizeof(fu)); + std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); } FrameGen::Img* last = nullptr; for (int it = 0; it < cfg_.frIters; ++it) { VkDescriptorSet set; FrameGen::Img* outImg; - if (it == 0) { set = g_scratch.sFlowReg0; outImg = &flowRegA_; } - else if (it % 2 == 1) { set = g_scratch.sFlowRegAB; outImg = &flowRegB_; } - else { set = g_scratch.sFlowRegBA; outImg = &flowRegA_; } + if (it == 0) { set = S.sFlowReg0; outImg = &flowRegA_; } + else if (it % 2 == 1) { set = S.sFlowRegAB; outImg = &flowRegB_; } + else { set = S.sFlowRegBA; outImg = &flowRegA_; } dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.pipeline); dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.layout, 0, 1, &set, 0, nullptr); dd_->CmdDispatch(cmd, (fe.width + 15) / 16, (fe.height + 15) / 16, 1); @@ -540,14 +547,14 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur } } - disp(expandP, g_scratch.sExpand[gmSlot], levelExtent(extent_, 0)); + disp(expandP, S.sExpand[gmSlot], levelExtent(extent_, 0)); barPair(flowExpA_, flowExpB_); - g_scratch.flowReady = true; + S.flowReady = true; } disp(pSynth_, synthSet, levelExtent(extent_, 0)); } -static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, +static bool ensureScratch(ScratchState& S, FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool, VkSampler samp, VkExtent2D ext, std::vector& pyrA, std::vector& pyrB, @@ -559,7 +566,6 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, const FrameGen::Pipe& pGmPrewarp, const FrameGen::Pipe& pFlowReg, FrameGen::Img& flowRegA, FrameGen::Img& flowRegB, VkBuffer* gmSsbo, int kLevels, const Config& cfg, uint64_t imageGeneration) { - auto& S = g_scratch; if (S.ownerDevice != VK_NULL_HANDLE && S.ownerDevice != dev) return false; S = ScratchState{}; S.ownerDevice = dev; diff --git a/app/src/main/cpp/questxr/CMakeLists.txt b/app/src/main/cpp/questxr/CMakeLists.txt index c23558bb0b..dd7ccc3599 100644 --- a/app/src/main/cpp/questxr/CMakeLists.txt +++ b/app/src/main/cpp/questxr/CMakeLists.txt @@ -8,6 +8,6 @@ target_compile_features(droiddeckxr PRIVATE cxx_std_17) target_compile_definitions(droiddeckxr PRIVATE XR_USE_PLATFORM_ANDROID XR_USE_GRAPHICS_API_OPENGL_ES XR_USE_TIMESPEC) target_compile_options(droiddeckxr PRIVATE -Wall -Wextra -Wno-missing-field-initializers -Werror=return-type) target_link_options(droiddeckxr PRIVATE -Wl,-z,max-page-size=16384 -uANativeActivity_onCreate) -target_link_libraries(droiddeckxr PRIVATE droiddeckxr_glue OpenXR::openxr_loader EGL GLESv3 android log) +target_link_libraries(droiddeckxr PRIVATE droiddeckxr_glue OpenXR::openxr_loader EGL GLESv3 android jnigraphics log) target_include_directories(droiddeckxr PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../tools/vr/src) diff --git a/app/src/main/cpp/questxr/quest_xr.cpp b/app/src/main/cpp/questxr/quest_xr.cpp index 8646bd501c..7f0237b097 100644 --- a/app/src/main/cpp/questxr/quest_xr.cpp +++ b/app/src/main/cpp/questxr/quest_xr.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -22,10 +23,14 @@ #include #include #include +#include +#include #include "xr_tracking.h" #include "xr_frame_channel.h" #include "xr_frame_math.h" #include "gpu_frames.h" +#include "xr_host.h" +#include "xr_overlay.h" static void check(XrResult result, const char *operation) { if (XR_FAILED(result)) throw std::runtime_error(std::string(operation) + ": " + std::to_string(result)); @@ -37,6 +42,15 @@ struct Eye { std::vector images; }; +struct SurfaceLayer { + XrSwapchain swapchain = XR_NULL_HANDLE; + jobject surface = nullptr; + int width = 0, height = 0; +}; + +class QuestXR; +static QuestXR *g_runtime = nullptr; + class QuestXR { public: explicit QuestXR(android_app *app) : app_(app) {} @@ -76,21 +90,74 @@ public: "\"headPosition\":[%.6f,%.6f,%.6f],\"controllersActive\":[%s,%s]," "\"periodNs\":%lld,\"surfaceSwapchain\":%s,\"source\":\"%s\",\"guestFrames\":%lld,\"steamvrState\":%d," "\"receivedFrames\":%llu,\"rejectedFrames\":%llu,\"uploadedFrames\":%llu,\"sourceFrameId\":%llu," - "\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u,\"error\":\"%s\"}\n", + "\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u," + "\"hostVersion\":%u,\"visibleLayers\":%d,\"overlay\":%s,\"error\":\"%s\"}\n", (unsigned long long)frames_, (unsigned long long)rendered_, state_, (unsigned long long)head_.locationFlags, head_.pose.position.x, head_.pose.position.y, head_.pose.position.z, handActive_[0] ? "true" : "false", handActive_[1] ? "true" : "false", - (long long)period_, "false", "frames", + (long long)period_, surfaceSupported_ ? "true" : "false", "frames", 0LL, steamvrState, (unsigned long long)(receiver_.Received() + gpuFrames_.Received()), (unsigned long long)(receiver_.Rejected() + gpuFrames_.Rejected()), (unsigned long long)uploadedFrames_, (unsigned long long)sourceHeader_.frame_id, (unsigned long long)gpuFrames_.Received(), (unsigned long long)gpuFrames_.Dropped(), - (unsigned long long)verifiedFrame_, gpuChecksum_, error); + (unsigned long long)verifiedFrame_, gpuChecksum_, + hostBuffers_ ? DROIDDECK_XR_HOST_VERSION : 0u, visibleLayers_, + XrOverlay::active(hostControl_) ? "true" : "false", error); std::fclose(file); std::rename(temp.c_str(), path.c_str()); } + bool onXrThread() const { return pthread_equal(pthread_self(), xrThread_); } + + int createLayer(JNIEnv *env, int width, int height) { + if (!onXrThread() || !createSurfaceSwapchain_ || session_ == XR_NULL_HANDLE || width <= 0 || height <= 0) return -1; + for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) { + SurfaceLayer &layer = layers_[index]; + if (layer.swapchain) continue; + XrSwapchainCreateInfo create{XR_TYPE_SWAPCHAIN_CREATE_INFO}; + create.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT; + create.width = width; create.height = height; + jobject surface = nullptr; + XrResult result = createSurfaceSwapchain_(session_, &create, &layer.swapchain, &surface); + if (XR_FAILED(result) || !surface) { + __android_log_print(ANDROID_LOG_ERROR, "DroidDeckXR", "surface layer %dx%d failed: %d", width, height, result); + if (layer.swapchain) xrDestroySwapchain(layer.swapchain); + layer = {}; + return -1; + } + layer.surface = env->NewGlobalRef(surface); + layer.width = width; layer.height = height; + __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface layer %d created %dx%d", index, width, height); + return index; + } + return -1; + } + + jobject layerSurface(JNIEnv *env, int index) { + if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS || !layers_[index].surface) return nullptr; + return env->NewLocalRef(layers_[index].surface); + } + + void setOrbImage(JNIEnv *env, jobject bitmap) { + if (!onXrThread() || !bitmap) return; + AndroidBitmapInfo info{}; + void *pixels = nullptr; + if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS + || info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) return; + if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) return; + overlay_.setLogo(pixels, (int)info.width, (int)info.height, (int)info.stride); + AndroidBitmap_unlockPixels(env, bitmap); + } + + void destroyLayer(JNIEnv *env, int index) { + if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS) return; + SurfaceLayer &layer = layers_[index]; + if (layer.swapchain) xrDestroySwapchain(layer.swapchain); + if (layer.surface) env->DeleteGlobalRef(layer.surface); + layer = {}; + } + private: android_app *app_; JNIEnv *env_ = nullptr; @@ -104,6 +171,20 @@ private: XrAction primary_ = XR_NULL_HANDLE, secondary_ = XR_NULL_HANDLE, menu_ = XR_NULL_HANDLE; XrAction triggerTouch_ = XR_NULL_HANDLE, stickTouch_ = XR_NULL_HANDLE, primaryTouch_ = XR_NULL_HANDLE; XrAction secondaryTouch_ = XR_NULL_HANDLE, thumbrestTouch_ = XR_NULL_HANDLE; + PFN_xrCreateSwapchainAndroidSurfaceKHR createSurfaceSwapchain_ = nullptr; + bool surfaceSupported_ = false; + bool imageLayoutSupported_ = false; + pthread_t xrThread_{}; + SurfaceLayer layers_[DROIDDECK_XR_HOST_LAYERS]; + DroidDeckXrHostState hostState_{}; + DroidDeckXrHostControl hostControl_{}; + bool hostBuffers_ = false; + jmethodID hostFrameCallback_ = nullptr; + uint64_t hostPulse_[2]{}; + int visibleLayers_ = 0; + XrOverlay overlay_; + Eye overlayEyes_[2]; + GLuint overlayDepth_[2]{}; DroidDeckXrHand inputs_[2]{}; PFN_xrConvertTimeToTimespecTimeKHR convertTime_ = nullptr; bool timespecSupported_ = false; @@ -220,6 +301,8 @@ private: void initialize() { app_->userData = this; + xrThread_ = pthread_self(); + g_runtime = this; app_->onInputEvent = [](android_app *app, AInputEvent *event) -> int32_t { if (AInputEvent_getType(event) != AINPUT_EVENT_TYPE_KEY || AKeyEvent_getKeyCode(event) != AKEYCODE_BACK || AKeyEvent_getAction(event) != AKEY_EVENT_ACTION_UP) return 0; @@ -244,6 +327,10 @@ private: frameCallback_ = env_->GetMethodID(activityClass, "onXrFrame", "(J)V"); statusCallback_ = env_->GetMethodID(activityClass, "onXrStatus", "()I"); if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("XR activity bridge methods unavailable"); } + hostFrameCallback_ = env_->GetMethodID(activityClass, "onXrHostFrame", "()V"); + jmethodID hostBuffersCallback = hostFrameCallback_ ? + env_->GetMethodID(activityClass, "onXrHostBuffers", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V") : nullptr; + if (env_->ExceptionCheck()) { env_->ExceptionClear(); hostFrameCallback_ = nullptr; hostBuffersCallback = nullptr; } env_->DeleteLocalRef(intentClass); env_->DeleteLocalRef(intent); env_->DeleteLocalRef(activityClass); PFN_xrInitializeLoaderKHR initializeLoader = nullptr; check(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", @@ -261,10 +348,21 @@ private: timespecSupported_ = true; if (!std::strcmp(extension.extensionName, XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME)) performanceSupported_ = true; + if (!std::strcmp(extension.extensionName, XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME)) + surfaceSupported_ = true; + if (!std::strcmp(extension.extensionName, XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME)) + imageLayoutSupported_ = true; } + __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface swapchain available=%d image layout=%d", + surfaceSupported_, imageLayoutSupported_); + // A surface swapchain's image arrives upside down, and a quad's back face is not drawn, so + // panels need the layout flag to flip it. + surfaceSupported_ = surfaceSupported_ && imageLayoutSupported_; std::vector enabled{XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME, XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME}; if (timespecSupported_) enabled.push_back(XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME); if (performanceSupported_) enabled.push_back(XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME); + if (surfaceSupported_) enabled.push_back(XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME); + if (surfaceSupported_) enabled.push_back(XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME); XrInstanceCreateInfoAndroidKHR androidInfo{XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR}; androidInfo.applicationVM = app_->activity->vm; androidInfo.applicationActivity = app_->activity->clazz; @@ -281,6 +379,11 @@ private: reinterpret_cast(&setPerformance_)); if (XR_FAILED(result)) setPerformance_ = nullptr; } + if (surfaceSupported_ && XR_FAILED(xrGetInstanceProcAddr(instance_, "xrCreateSwapchainAndroidSurfaceKHR", + reinterpret_cast(&createSurfaceSwapchain_)))) { + createSurfaceSwapchain_ = nullptr; + surfaceSupported_ = false; + } if (timespecSupported_) check(xrGetInstanceProcAddr(instance_, "xrConvertTimeToTimespecTimeKHR", reinterpret_cast(&convertTime_)), "time conversion entrypoint"); XrSystemGetInfo systemInfo{XR_TYPE_SYSTEM_GET_INFO}; @@ -334,6 +437,16 @@ private: bool gpu = !verifyPixels_ && gpuFrames_.Start(std::string(app_->activity->internalDataPath) + "/.wayland-rt/" DROIDDECK_XR_GPU_SOCKET, display_); __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "GPU frame channel available=%d", gpu); } + overlay_.initialize(); + hostState_.version = DROIDDECK_XR_HOST_VERSION; + if (hostBuffersCallback) { + jobject state = env_->NewDirectByteBuffer(&hostState_, sizeof(hostState_)); + jobject control = env_->NewDirectByteBuffer(&hostControl_, sizeof(hostControl_)); + env_->CallVoidMethod(app_->activity->clazz, hostBuffersCallback, state, control); + if (env_->ExceptionCheck()) { env_->ExceptionDescribe(); env_->ExceptionClear(); hostFrameCallback_ = nullptr; } + else hostBuffers_ = true; + env_->DeleteLocalRef(state); env_->DeleteLocalRef(control); + } health(); } @@ -422,6 +535,13 @@ private: target.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR}); check(xrEnumerateSwapchainImages(target.swapchain, count, &count, reinterpret_cast(target.images.data())), "images"); + Eye &overlay = overlayEyes_[eye]; + overlay.width = target.width; overlay.height = target.height; + check(xrCreateSwapchain(session_, &create, &overlay.swapchain), "overlay swapchain"); + check(xrEnumerateSwapchainImages(overlay.swapchain, 0, &count, nullptr), "overlay image count"); + overlay.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR}); + check(xrEnumerateSwapchainImages(overlay.swapchain, count, &count, + reinterpret_cast(overlay.images.data())), "overlay images"); } } @@ -530,6 +650,12 @@ private: void initializeGraphics() { glGenFramebuffers(1, &framebuffer_); + glGenRenderbuffers(2, overlayDepth_); + for (int eye = 0; eye < 2; eye++) { + glBindRenderbuffer(GL_RENDERBUFFER, overlayDepth_[eye]); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, overlayEyes_[eye].width, overlayEyes_[eye].height); + } + glBindRenderbuffer(GL_RENDERBUFFER, 0); glGenVertexArrays(1, &vertexArray_); GLuint vertex = shader(GL_VERTEX_SHADER, "#version 300 es\nout vec2 uv; uniform float eye; void main(){vec2 coordinate=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));uv=vec2(coordinate.x*0.5+eye*0.5,1.0-coordinate.y);gl_Position=vec4(coordinate*2.0-1.0,0.0,1.0);}"); @@ -584,24 +710,46 @@ private: if (verifyPixels_ || uploadedFrames_ % 72 == 1) health(); } - void render(Eye &eye, uint32_t image) { + void render(Eye &eye, uint32_t image, bool source, const XrPosef &pose, const XrFovf &fov, float seconds) { glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw std::runtime_error("Incomplete eye framebuffer"); - { - glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST); + glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST); + if (source) { glUseProgram(sourceProgram_); glBindVertexArray(vertexArray_); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sourceTexture_); glUniform1i(glGetUniformLocation(sourceProgram_, "source"), 0); glUniform1f(glGetUniformLocation(sourceProgram_, "eye"), &eye == &eyes_[1] ? 1.f : 0.f); glDrawArrays(GL_TRIANGLES, 0, 3); + } else { + glClearColor(0.f, 0.f, 0.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT); } glBindFramebuffer(GL_FRAMEBUFFER, 0); if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL render error"); glFlush(); } + // Lasers and the orb go in their own layer above the panels, which only the panels' depth hides. + void renderOverlay(int index, uint32_t image, const XrPosef &pose, const XrFovf &fov, float seconds) { + Eye &eye = overlayEyes_[index]; + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, overlayDepth_[index]); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) + throw std::runtime_error("Incomplete overlay framebuffer"); + glViewport(0, 0, eye.width, eye.height); + glClearColor(0.f, 0.f, 0.f, 0.f); glClearDepthf(1.f); + glDepthMask(GL_TRUE); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + overlay_.draw(pose, fov, hostControl_, hostState_, seconds); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL overlay error"); + glFlush(); + } + void pollEvents() { XrEventDataBuffer event{XR_TYPE_EVENT_DATA_BUFFER}; XrResult result; @@ -685,6 +833,7 @@ private: XrViewState viewState{XR_TYPE_VIEW_STATE}; uint32_t count = 0; XrView views[2]{{XR_TYPE_VIEW}, {XR_TYPE_VIEW}}; check(xrLocateViews(session_, &locate, &viewState, 2, &count, views), "xrLocateViews"); + hostFrame(frameState.predictedDisplayTime); publishTracking(views, frameState.predictedDisplayTime); if (guestAttached_) { timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now); @@ -692,29 +841,34 @@ private: if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("Guest frame callback failed"); } } XrCompositionLayerProjectionView projection[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}}; - bool valid = frameState.shouldRender && count == 2 && + const bool viewsValid = frameState.shouldRender && count == 2 && (viewState.viewStateFlags & (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT)) == (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT); - { - valid = valid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL; - if (valid) for (int eye = 0; eye < 2; eye++) { - auto source = xr_frame_view(sourceHeader_, eye); - views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]}; - views[eye].pose.position = {source.position[0], source.position[1], source.position[2]}; - views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]}; - } + bool valid = viewsValid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL; + if (valid) for (int eye = 0; eye < 2; eye++) { + auto source = xr_frame_view(sourceHeader_, eye); + views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]}; + views[eye].pose.position = {source.position[0], source.position[1], source.position[2]}; + views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]}; } + std::vector quads; + std::vector layouts; + if (viewsValid) collectQuads(quads, layouts); + const bool uiOnly = !valid && viewsValid && !quads.empty(); + const bool draw = valid || uiOnly; const std::string capture = captureRequest(); bool captured = valid; if (!capture.empty() && valid) captured = captureTexture(sourceTexture_, sourceHeader_.width, sourceHeader_.height, "source"); - if (valid) for (int eye = 0; eye < 2; eye++) { + timespec clock{}; clock_gettime(CLOCK_MONOTONIC, &clock); + const float seconds = (float)(clock.tv_sec % 3600) + clock.tv_nsec * 1e-9f; + if (draw) for (int eye = 0; eye < 2; eye++) { uint32_t image = 0; XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO}; check(xrAcquireSwapchainImage(eyes_[eye].swapchain, &acquire, &image), "acquire image"); XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION; check(xrWaitSwapchainImage(eyes_[eye].swapchain, &imageWait), "wait image"); - render(eyes_[eye], image); + render(eyes_[eye], image, valid, views[eye].pose, views[eye].fov, seconds); if (!capture.empty()) captured = captureTexture(eyes_[eye].images[image].image, eyes_[eye].width, eyes_[eye].height, eye ? "right" : "left") && captured; XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO}; check(xrReleaseSwapchainImage(eyes_[eye].swapchain, &release), "release image"); @@ -722,19 +876,143 @@ private: projection[eye].subImage.swapchain = eyes_[eye].swapchain; projection[eye].subImage.imageRect.extent = {eyes_[eye].width, eyes_[eye].height}; } + const bool overlay = viewsValid && hostBuffers_ && XrOverlay::active(hostControl_); + XrCompositionLayerProjectionView overlayViews[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}}; + if (overlay) for (int eye = 0; eye < 2; eye++) { + uint32_t image = 0; + XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO}; + check(xrAcquireSwapchainImage(overlayEyes_[eye].swapchain, &acquire, &image), "acquire overlay image"); + XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION; + check(xrWaitSwapchainImage(overlayEyes_[eye].swapchain, &imageWait), "wait overlay image"); + renderOverlay(eye, image, views[eye].pose, views[eye].fov, seconds); + XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO}; + check(xrReleaseSwapchainImage(overlayEyes_[eye].swapchain, &release), "release overlay image"); + overlayViews[eye].pose = views[eye].pose; overlayViews[eye].fov = views[eye].fov; + overlayViews[eye].subImage.swapchain = overlayEyes_[eye].swapchain; + overlayViews[eye].subImage.imageRect.extent = {overlayEyes_[eye].width, overlayEyes_[eye].height}; + } XrCompositionLayerProjection layer{XR_TYPE_COMPOSITION_LAYER_PROJECTION}; layer.space = world_; layer.viewCount = 2; layer.views = projection; - const XrCompositionLayerBaseHeader *layers[] = {reinterpret_cast(&layer)}; + XrCompositionLayerProjection overlayLayer{XR_TYPE_COMPOSITION_LAYER_PROJECTION}; + overlayLayer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT; + overlayLayer.space = world_; overlayLayer.viewCount = 2; overlayLayer.views = overlayViews; + std::vector layers; + if (draw) layers.push_back(reinterpret_cast(&layer)); + for (auto &quad : quads) layers.push_back(reinterpret_cast(&quad)); + if (overlay) layers.push_back(reinterpret_cast(&overlayLayer)); + visibleLayers_ = (int)quads.size(); XrFrameEndInfo end{XR_TYPE_FRAME_END_INFO}; end.displayTime = frameState.predictedDisplayTime; - end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; end.layerCount = valid ? 1 : 0; end.layers = layers; + end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; + end.layerCount = (uint32_t)layers.size(); end.layers = layers.data(); check(xrEndFrame(session_, &end), "xrEndFrame"); if (!capture.empty()) captureResult(capture, captured, valid, projection, frameState.predictedDisplayTime); frames_++; if (valid) rendered_++; if (frames_ % 72 == 0) { health(); - __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld", + __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld layers=%d", (unsigned long long)frames_, (unsigned long long)rendered_, (unsigned long long)head_.locationFlags, - handActive_[0], handActive_[1], (long long)period_); + handActive_[0], handActive_[1], (long long)period_, visibleLayers_); + } + } + + // Android surfaces are stored top row first, while OpenXR samples images bottom row first. + void collectQuads(std::vector &quads, std::vector &layouts) { + if (!hostBuffers_) return; + quads.reserve(DROIDDECK_XR_HOST_LAYERS); + layouts.reserve(DROIDDECK_XR_HOST_LAYERS); + const DroidDeckXrHostLayer *ordered[DROIDDECK_XR_HOST_LAYERS]; + int visible = 0; + for (const auto &layer : hostControl_.layers) { + if (!layer.visible || layer.id < 0 || layer.id >= DROIDDECK_XR_HOST_LAYERS || !layers_[layer.id].swapchain) continue; + if (!(layer.width > 0.f) || !(layer.height > 0.f)) continue; + ordered[visible++] = &layer; + } + std::sort(ordered, ordered + visible, [](const DroidDeckXrHostLayer *a, const DroidDeckXrHostLayer *b) { return a->order < b->order; }); + for (int index = 0; index < visible; index++) { + const auto &layer = *ordered[index]; + const SurfaceLayer &surface = layers_[layer.id]; + XrCompositionLayerQuad quad{XR_TYPE_COMPOSITION_LAYER_QUAD}; + quad.layerFlags = (layer.flags & DROIDDECK_XR_HOST_LAYER_ALPHA) ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT : 0; + quad.space = (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) ? view_ : world_; + quad.eyeVisibility = XR_EYE_VISIBILITY_BOTH; + quad.subImage.swapchain = surface.swapchain; + quad.subImage.imageRect.extent = {surface.width, surface.height}; + quad.pose.orientation = {layer.pose.orientation[0], layer.pose.orientation[1], layer.pose.orientation[2], layer.pose.orientation[3]}; + quad.pose.position = {layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]}; + quad.size = {layer.width, layer.height}; + layouts.push_back({XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB, nullptr, XR_COMPOSITION_LAYER_IMAGE_LAYOUT_VERTICAL_FLIP_BIT_FB}); + quad.next = &layouts.back(); + quads.push_back(quad); + } + } + + // SteamVR draws its laser from the "tip" of the Quest Touch render model the driver names + // (resources/rendermodels/oculus_quest_plus_controller_*), placed on the raw grip pose; panels + // use the same ray so there is one laser per controller. + static DroidDeckXrPose steamVrPointer(const XrSpaceLocation &grip, int hand) { + const float q[4] = {grip.pose.orientation.x, grip.pose.orientation.y, grip.pose.orientation.z, grip.pose.orientation.w}; + const XrVec3 tip{hand == 0 ? 0.016694f : -0.016694f, -0.02522f, 0.024687f}; + const XrVec3 at = XrVec3{grip.pose.position.x, grip.pose.position.y, grip.pose.position.z} + rotate(q, tip); + const float tx = -0.320613f, tw = 0.947210f; + DroidDeckXrPose pose{}; + pose.orientation[0] = q[3] * tx + q[0] * tw; + pose.orientation[1] = q[1] * tw + q[2] * tx; + pose.orientation[2] = q[2] * tw - q[1] * tx; + pose.orientation[3] = q[3] * tw - q[0] * tx; + pose.position[0] = at.x; pose.position[1] = at.y; pose.position[2] = at.z; + pose.flags = (uint32_t)grip.locationFlags; + return pose; + } + + void hostFrame(XrTime predicted) { + if (!hostBuffers_ || !hostFrameCallback_) return; + hostState_.version = DROIDDECK_XR_HOST_VERSION; + hostState_.session_state = state_; + hostState_.flags = (surfaceSupported_ ? DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN : 0u) | + (state_ == XR_SESSION_STATE_FOCUSED ? DROIDDECK_XR_HOST_FOCUSED : 0u); + hostState_.frame = (int64_t)frames_; + hostState_.display_time_ns = 0; + if (convertTime_) { + timespec displayTime{}; + if (XR_SUCCEEDED(convertTime_(instance_, predicted, &displayTime))) + hostState_.display_time_ns = (int64_t)displayTime.tv_sec * 1000000000LL + displayTime.tv_nsec; + } + hostState_.head = posePacket(head_.pose, head_.locationFlags); + const XrSpaceLocationFlags tracked = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT; + for (int hand = 0; hand < 2; hand++) { + auto &out = hostState_.hands[hand]; + out.grip = posePacket(handLocations_[hand].pose, handLocations_[hand].locationFlags); + out.aim = steamVrPointer(handLocations_[hand], hand); + out.trigger = inputs_[hand].trigger; out.squeeze = inputs_[hand].squeeze; + out.stick[0] = inputs_[hand].stick[0]; out.stick[1] = inputs_[hand].stick[1]; + out.buttons = inputs_[hand].buttons; + out.active = handActive_[hand] && (handLocations_[hand].locationFlags & tracked) == tracked; + } + env_->CallVoidMethod(app_->activity->clazz, hostFrameCallback_); + if (env_->ExceptionCheck()) { + env_->ExceptionDescribe(); env_->ExceptionClear(); + hostControl_ = {}; + return; + } + if (hostControl_.version != DROIDDECK_XR_HOST_VERSION) { hostControl_ = {}; return; } + for (int hand = 0; hand < 2; hand++) { + const auto &control = hostControl_.hands[hand]; + if (control.mask & DROIDDECK_XR_HOST_MASK_INPUT) { + inputs_[hand].trigger = 0; inputs_[hand].squeeze = 0; + inputs_[hand].stick[0] = inputs_[hand].stick[1] = 0; + inputs_[hand].buttons = 0; + } + const auto &pulse = control.haptic; + if (pulse.id == hostPulse_[hand]) continue; + hostPulse_[hand] = pulse.id; + if (state_ != XR_SESSION_STATE_FOCUSED || !handActive_[hand] + || pulse.duration_ns < 1000000 || pulse.duration_ns > 1000000000 + || !std::isfinite(pulse.amplitude) || pulse.amplitude < 0 || pulse.amplitude > 1 + || !std::isfinite(pulse.frequency) || pulse.frequency < 0) continue; + XrHapticActionInfo info{XR_TYPE_HAPTIC_ACTION_INFO}; info.action = vibration_; info.subactionPath = hands_[hand]; + XrHapticVibration vibration{XR_TYPE_HAPTIC_VIBRATION}; + vibration.duration = pulse.duration_ns; vibration.amplitude = pulse.amplitude; vibration.frequency = pulse.frequency; + check(xrApplyHapticFeedback(session_, &info, reinterpret_cast(&vibration)), "host haptics"); } } @@ -749,11 +1027,17 @@ private: munmap(tracking_, sizeof(DroidDeckXrTracking)); } if (haptics_) munmap(haptics_, sizeof(DroidDeckXrHaptics)); + g_runtime = nullptr; + hostBuffers_ = false; if (display_ != EGL_NO_DISPLAY && context_ != EGL_NO_CONTEXT) { glDeleteFramebuffers(1, &framebuffer_); glDeleteVertexArrays(1, &vertexArray_); glDeleteTextures(1, &cpuTexture_); glDeleteProgram(sourceProgram_); + glDeleteRenderbuffers(2, overlayDepth_); + overlay_.destroy(); } + if (env_) for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) destroyLayer(env_, index); for (auto &eye : eyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain); + for (auto &eye : overlayEyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain); for (auto space : handSpaces_) if (space) xrDestroySpace(space); if (view_) xrDestroySpace(view_); if (world_) xrDestroySpace(world_); if (session_) xrDestroySession(session_); @@ -769,6 +1053,26 @@ private: } }; +extern "C" JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_QuestXrActivity_nativeCreateLayer(JNIEnv *env, jobject, jint width, jint height) { + return g_runtime ? g_runtime->createLayer(env, width, height) : -1; +} + +extern "C" JNIEXPORT jobject JNICALL +Java_com_droiddeck_launcher_QuestXrActivity_nativeLayerSurface(JNIEnv *env, jobject, jint index) { + return g_runtime ? g_runtime->layerSurface(env, index) : nullptr; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_QuestXrActivity_nativeDestroyLayer(JNIEnv *env, jobject, jint index) { + if (g_runtime) g_runtime->destroyLayer(env, index); +} + +extern "C" JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_QuestXrActivity_nativeSetOrbImage(JNIEnv *env, jobject, jobject bitmap) { + if (g_runtime) g_runtime->setOrbImage(env, bitmap); +} + void android_main(android_app *app) { QuestXR runtime(app); try { runtime.run(); } diff --git a/app/src/main/cpp/questxr/xr_host.h b/app/src/main/cpp/questxr/xr_host.h new file mode 100644 index 0000000000..9f08c32537 --- /dev/null +++ b/app/src/main/cpp/questxr/xr_host.h @@ -0,0 +1,91 @@ +#pragma once +#include +#include +#include "xr_tracking.h" + +// Shared with com.droiddeck.launcher.session.xr.XrHost, which reads and writes these through direct +// ByteBuffers by fixed offset: any layout change must bump the version and update both sides. +#define DROIDDECK_XR_HOST_VERSION 1u +#define DROIDDECK_XR_HOST_LAYERS 6 + +#define DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN (1u << 0) +#define DROIDDECK_XR_HOST_FOCUSED (1u << 1) + +#define DROIDDECK_XR_HOST_MASK_INPUT (1u << 0) + +#define DROIDDECK_XR_HOST_LAYER_ALPHA (1u << 0) +#define DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED (1u << 1) + +struct DroidDeckXrHostHand { + DroidDeckXrPose grip; + DroidDeckXrPose aim; + float trigger, squeeze, stick[2]; + uint32_t buttons, active; + uint32_t reserved[2]; +}; + +struct DroidDeckXrHostState { + uint32_t version, session_state, flags, reserved0; + int64_t frame, display_time_ns; + DroidDeckXrPose head; + DroidDeckXrHostHand hands[2]; + uint32_t reserved[8]; +}; + +struct DroidDeckXrHostHaptic { + uint64_t id; + int64_t duration_ns; + float amplitude, frequency; +}; + +struct DroidDeckXrHostHandControl { + uint32_t mask; + float laser; + DroidDeckXrHostHaptic haptic; + uint32_t reserved[2]; +}; + +struct DroidDeckXrHostOrb { + uint32_t visible; + float progress, burst, radius; + DroidDeckXrPose pose; +}; + +struct DroidDeckXrHostLayer { + int32_t id; + uint32_t visible, flags; + int32_t order; + DroidDeckXrPose pose; + float width, height; + uint32_t reserved[2]; +}; + +struct DroidDeckXrHostControl { + uint32_t version, reserved0; + DroidDeckXrHostHandControl hands[2]; + DroidDeckXrHostOrb orb; + DroidDeckXrHostLayer layers[DROIDDECK_XR_HOST_LAYERS]; + uint32_t reserved[8]; +}; + +static_assert(sizeof(DroidDeckXrHostHand) == 96, "XR host hand layout"); +static_assert(offsetof(DroidDeckXrHostHand, aim) == 32 && offsetof(DroidDeckXrHostHand, trigger) == 64 && + offsetof(DroidDeckXrHostHand, stick) == 72 && offsetof(DroidDeckXrHostHand, buttons) == 80 && + offsetof(DroidDeckXrHostHand, active) == 84, "XR host hand layout"); +static_assert(offsetof(DroidDeckXrHostState, flags) == 8 && offsetof(DroidDeckXrHostState, frame) == 16 && + offsetof(DroidDeckXrHostState, head) == 32, "XR host state layout"); +static_assert(offsetof(DroidDeckXrHostHandControl, laser) == 4 && offsetof(DroidDeckXrHostHandControl, haptic) == 8, + "XR host hand control layout"); +static_assert(offsetof(DroidDeckXrHostHaptic, duration_ns) == 8 && offsetof(DroidDeckXrHostHaptic, amplitude) == 16, + "XR host haptic layout"); +static_assert(offsetof(DroidDeckXrHostOrb, progress) == 4 && offsetof(DroidDeckXrHostOrb, pose) == 16, "XR host orb layout"); +static_assert(offsetof(DroidDeckXrHostLayer, order) == 12 && offsetof(DroidDeckXrHostLayer, pose) == 16 && + offsetof(DroidDeckXrHostLayer, width) == 48, "XR host layer layout"); +static_assert(sizeof(DroidDeckXrHostState) == 288, "XR host state layout"); +static_assert(offsetof(DroidDeckXrHostState, hands) == 64, "XR host state layout"); +static_assert(sizeof(DroidDeckXrHostHandControl) == 40, "XR host hand control layout"); +static_assert(sizeof(DroidDeckXrHostOrb) == 48, "XR host orb layout"); +static_assert(sizeof(DroidDeckXrHostLayer) == 64, "XR host layer layout"); +static_assert(offsetof(DroidDeckXrHostControl, orb) == 88, "XR host control layout"); +static_assert(offsetof(DroidDeckXrHostControl, layers) == 136, "XR host control layout"); +static_assert(sizeof(DroidDeckXrHostControl) == 552, "XR host control layout"); diff --git a/app/src/main/cpp/questxr/xr_overlay.h b/app/src/main/cpp/questxr/xr_overlay.h new file mode 100644 index 0000000000..5078e27b16 --- /dev/null +++ b/app/src/main/cpp/questxr/xr_overlay.h @@ -0,0 +1,229 @@ +#pragma once +#include +#include +#include +#include +#include +#include "xr_host.h" + +struct XrVec3 { float x, y, z; }; + +static inline XrVec3 xrv(float x, float y, float z) { return {x, y, z}; } +static inline XrVec3 operator+(XrVec3 a, XrVec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; } +static inline XrVec3 operator-(XrVec3 a, XrVec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; } +static inline XrVec3 operator*(XrVec3 a, float s) { return {a.x * s, a.y * s, a.z * s}; } +static inline float dot(XrVec3 a, XrVec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } +static inline XrVec3 cross(XrVec3 a, XrVec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; } +static inline XrVec3 normalized(XrVec3 a) { + float length = std::sqrt(dot(a, a)); + return length > 1e-6f ? a * (1.f / length) : xrv(0, 0, 0); +} + +static inline XrVec3 rotate(const float q[4], XrVec3 v) { + XrVec3 u{q[0], q[1], q[2]}; + float s = q[3]; + return u * (2.f * dot(u, v)) + v * (s * s - dot(u, u)) + cross(u, v) * (2.f * s); +} + +class XrOverlay { +public: + void initialize() { + GLuint vertex = compile(GL_VERTEX_SHADER, + "#version 300 es\nlayout(location=0) in vec3 position; layout(location=1) in vec2 coordinate;" + "uniform mat4 viewProjection; out vec2 uv;" + "void main(){uv=coordinate;gl_Position=viewProjection*vec4(position,1.0);}"); + GLuint fragment = compile(GL_FRAGMENT_SHADER, + "#version 300 es\nprecision highp float; in vec2 uv; uniform int mode; uniform float progress, burst, time;" + "uniform vec3 color; uniform sampler2D logo; uniform int hasLogo; out vec4 outputColor;" + "void main(){" + " if(mode==0){float across=1.0-abs(uv.y); float a=smoothstep(0.0,0.7,across)*mix(0.95,0.35,uv.x);" + " outputColor=vec4(color*a,a);return;}" + " if(mode==1){float r=length(uv); float a=1.0-smoothstep(0.55,1.0,r); outputColor=vec4(vec3(1.0)*a,a);return;}" + " float r=length(uv); vec3 c=vec3(0.0); float a=0.0;" + " float pulse=0.5+0.5*sin(time*6.0);" + " float glow=exp(-pow(max(r-0.45,0.0)*6.0,2.0))*(0.25+0.2*pulse)*step(0.5,r); c+=color*glow; a=max(a,glow*0.7);" + " if(hasLogo==1&&r<0.52){vec4 l=texture(logo,vec2(0.5+uv.x/1.04,0.5-uv.y/1.04)); c=c*(1.0-l.a)+l.rgb; a=a*(1.0-l.a)+l.a;}" + " else if(r<0.5){float core=1.0-smoothstep(0.46,0.5,r); c+=color*core; a=max(a,core);}" + " float angle=atan(uv.x,uv.y); float sweep=(angle<0.0?angle+6.2831853:angle)/6.2831853;" + " float band=1.0-smoothstep(0.0,0.03,abs(r-0.64));" + " float track=band*0.25; float fill=band*step(sweep,progress);" + " c+=vec3(1.0)*track+color*fill*1.4; a=max(a,max(track,fill));" + " if(burst>0.0){float ring=(1.0-smoothstep(0.0,0.06,abs(r-(0.64+burst*0.3))))*(1.0-burst); c+=color*ring*2.0; a=max(a,ring);}" + " a=clamp(a,0.0,1.0); outputColor=vec4(c*a,a);" + "}"); + program_ = glCreateProgram(); + glAttachShader(program_, vertex); glAttachShader(program_, fragment); + glLinkProgram(program_); glDeleteShader(vertex); glDeleteShader(fragment); + GLint linked = 0; glGetProgramiv(program_, GL_LINK_STATUS, &linked); + if (!linked) throw std::runtime_error("Overlay shader link failed"); + viewProjection_ = glGetUniformLocation(program_, "viewProjection"); + mode_ = glGetUniformLocation(program_, "mode"); + progress_ = glGetUniformLocation(program_, "progress"); + burst_ = glGetUniformLocation(program_, "burst"); + time_ = glGetUniformLocation(program_, "time"); + color_ = glGetUniformLocation(program_, "color"); + logoSampler_ = glGetUniformLocation(program_, "logo"); + hasLogo_ = glGetUniformLocation(program_, "hasLogo"); + glGenVertexArrays(1, &vertexArray_); + glGenBuffers(1, &buffer_); + glBindVertexArray(vertexArray_); + glBindBuffer(GL_ARRAY_BUFFER, buffer_); + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 5 * 6, nullptr, GL_DYNAMIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, nullptr); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast(sizeof(float) * 3)); + glBindVertexArray(0); + } + + /** [pixels] are premultiplied RGBA rows, top row first, as an Android ARGB_8888 bitmap holds them. */ + void setLogo(const void *pixels, int width, int height, int stride) { + if (!logo_) glGenTextures(1, &logo_); + glBindTexture(GL_TEXTURE_2D, logo_); + glPixelStorei(GL_UNPACK_ROW_LENGTH, stride / 4); + glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + + void destroy() { + if (logo_) glDeleteTextures(1, &logo_); + logo_ = 0; + if (program_) glDeleteProgram(program_); + if (buffer_) glDeleteBuffers(1, &buffer_); + if (vertexArray_) glDeleteVertexArrays(1, &vertexArray_); + program_ = buffer_ = vertexArray_ = 0; + } + + static bool active(const DroidDeckXrHostControl &control) { + return control.orb.visible || control.hands[0].laser > 0.f || control.hands[1].laser > 0.f; + } + + void draw(const XrPosef &eye, const XrFovf &fov, const DroidDeckXrHostControl &control, + const DroidDeckXrHostState &state, float seconds) { + if (!active(control)) return; + float matrix[16]; + viewProjectionOf(eye, fov, matrix); + const float eyeOrientation[4] = {eye.orientation.x, eye.orientation.y, eye.orientation.z, eye.orientation.w}; + const XrVec3 eyePosition{eye.position.x, eye.position.y, eye.position.z}; + glUseProgram(program_); + glUniformMatrix4fv(viewProjection_, 1, GL_FALSE, matrix); + glUniform3f(color_, 0.12f, 0.62f, 1.0f); + glUniform1f(time_, seconds); + glBindVertexArray(vertexArray_); + glBindBuffer(GL_ARRAY_BUFFER, buffer_); + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); + glDepthMask(GL_TRUE); + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + glDisable(GL_BLEND); + glUniform1i(mode_, 0); + for (const auto &layer : control.layers) { + if (!layer.visible || !(layer.width > 0.f) || !(layer.height > 0.f)) continue; + if (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) continue; + XrVec3 center{layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]}; + XrVec3 right = rotate(layer.pose.orientation, xrv(layer.width / 2.f, 0, 0)); + XrVec3 up = rotate(layer.pose.orientation, xrv(0, layer.height / 2.f, 0)); + quad(center - right - up, center + right - up, center - right + up, center + right + up, 0.f, 1.f); + } + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + for (int hand = 0; hand < 2; hand++) { + float length = control.hands[hand].laser; + if (!(length > 0.f) || !state.hands[hand].active) continue; + const auto &aim = state.hands[hand].aim; + XrVec3 start{aim.position[0], aim.position[1], aim.position[2]}; + XrVec3 direction = normalized(rotate(aim.orientation, xrv(0, 0, -1))); + XrVec3 end = start + direction * std::max(length - 0.004f, 0.f); + XrVec3 side = normalized(cross(direction, eyePosition - start)) * 0.0022f; + glUniform1i(mode_, 0); + quad(start - side, start + side, end - side, end + side, 0.f, 1.f); + XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * 0.007f; + XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * 0.007f; + glUniform1i(mode_, 1); + billboard(end + normalized(eyePosition - end) * 0.008f, right, up); + } + if (control.orb.visible) { + const auto &pose = control.orb.pose; + XrVec3 center{pose.position[0], pose.position[1], pose.position[2]}; + float size = control.orb.radius * 1.25f; + XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * size; + XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * size; + glUniform1i(mode_, 2); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, logo_); + glUniform1i(logoSampler_, 0); + glUniform1i(hasLogo_, logo_ ? 1 : 0); + glUniform1f(progress_, control.orb.progress); + glUniform1f(burst_, control.orb.burst); + billboard(center, right, up); + } + glBindVertexArray(0); + glDisable(GL_BLEND); + glDisable(GL_DEPTH_TEST); + glDepthMask(GL_TRUE); + } + +private: + GLuint program_ = 0, buffer_ = 0, vertexArray_ = 0, logo_ = 0; + GLint viewProjection_ = -1, mode_ = -1, progress_ = -1, burst_ = -1, time_ = -1, color_ = -1; + GLint logoSampler_ = -1, hasLogo_ = -1; + + static GLuint compile(GLenum type, const char *text) { + GLuint handle = glCreateShader(type); + glShaderSource(handle, 1, &text, nullptr); glCompileShader(handle); + GLint success = 0; glGetShaderiv(handle, GL_COMPILE_STATUS, &success); + if (!success) { glDeleteShader(handle); throw std::runtime_error("Overlay shader compile failed"); } + return handle; + } + + void billboard(XrVec3 center, XrVec3 right, XrVec3 up) { + quadUv(center - right - up, center + right - up, center - right + up, center + right + up); + } + + void quad(XrVec3 a0, XrVec3 a1, XrVec3 b0, XrVec3 b1, float from, float to) { + const float vertices[] = { + a0.x, a0.y, a0.z, from, -1, a1.x, a1.y, a1.z, from, 1, b0.x, b0.y, b0.z, to, -1, + b0.x, b0.y, b0.z, to, -1, a1.x, a1.y, a1.z, from, 1, b1.x, b1.y, b1.z, to, 1}; + glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); + glDrawArrays(GL_TRIANGLES, 0, 6); + } + + void quadUv(XrVec3 bottomLeft, XrVec3 bottomRight, XrVec3 topLeft, XrVec3 topRight) { + const float vertices[] = { + bottomLeft.x, bottomLeft.y, bottomLeft.z, -1, -1, bottomRight.x, bottomRight.y, bottomRight.z, 1, -1, + topLeft.x, topLeft.y, topLeft.z, -1, 1, topLeft.x, topLeft.y, topLeft.z, -1, 1, + bottomRight.x, bottomRight.y, bottomRight.z, 1, -1, topRight.x, topRight.y, topRight.z, 1, 1}; + glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); + glDrawArrays(GL_TRIANGLES, 0, 6); + } + + static void viewProjectionOf(const XrPosef &pose, const XrFovf &fov, float out[16]) { + const float q[4] = {pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w}; + XrVec3 xAxis = rotate(q, xrv(1, 0, 0)), yAxis = rotate(q, xrv(0, 1, 0)), zAxis = rotate(q, xrv(0, 0, 1)); + XrVec3 position{pose.position.x, pose.position.y, pose.position.z}; + float view[16] = { + xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, + -dot(xAxis, position), -dot(yAxis, position), -dot(zAxis, position), 1}; + const float nearZ = 0.05f, farZ = 100.f; + float left = std::tan(fov.angleLeft), right = std::tan(fov.angleRight); + float up = std::tan(fov.angleUp), down = std::tan(fov.angleDown); + float width = right - left, height = up - down; + float projection[16] = { + 2.f / width, 0, 0, 0, 0, 2.f / height, 0, 0, + (right + left) / width, (up + down) / height, -(farZ + nearZ) / (farZ - nearZ), -1, + 0, 0, -2.f * farZ * nearZ / (farZ - nearZ), 0}; + for (int column = 0; column < 4; column++) + for (int row = 0; row < 4; row++) { + float sum = 0; + for (int k = 0; k < 4; k++) sum += projection[k * 4 + row] * view[column * 4 + k]; + out[column * 4 + row] = sum; + } + } +}; diff --git a/app/src/main/cpp/sdnative/sdnative.c b/app/src/main/cpp/sdnative/sdnative.c index 3e4ef71b41..8482f38d33 100644 --- a/app/src/main/cpp/sdnative/sdnative.c +++ b/app/src/main/cpp/sdnative/sdnative.c @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -27,3 +28,16 @@ Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass cla (void)clazz; return syscall(SYS_tgkill, tgid, tid, signal) == 0 ? 0 : errno; } + +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_session_PageCacheNative_fadviseDontNeed(JNIEnv *env, jclass clazz, jstring path) { + (void)clazz; + const char *chars = (*env)->GetStringUTFChars(env, path, NULL); + if (!chars) return ENOMEM; + int fd = open(chars, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + (*env)->ReleaseStringUTFChars(env, path, chars); + if (fd < 0) return errno; + int rc = posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); + close(fd); + return rc; +} diff --git a/app/src/main/cpp/shaders/cas_ffx.frag b/app/src/main/cpp/shaders/cas_ffx.frag index 9e0b68a1f4..fff26a9fcf 100644 --- a/app/src/main/cpp/shaders/cas_ffx.frag +++ b/app/src/main/cpp/shaders/cas_ffx.frag @@ -39,7 +39,7 @@ // - Same push constants as cas.frag: ndc, input size, sharpness [0..1]. // CasSetup's const1.x = -1 / lerp(8, 5, sharpness) is computed here. // - The input is the effect chain's previous target at the same size, so the -// output pixel reads the input pixel 1:1 (texelFetch, edges clamped). +// output pixel reads the input pixel 1:1 (texel centres, edges clamped). // ============================================================================= // DD_HALF is set for the *_half_frag.h build (gen_shaders.sh): colour and @@ -64,8 +64,8 @@ layout(location = 0) in highp vec2 fragTexCoord; layout(location = 0) out vec4 outColor; vec3 CasLoad(ivec2 p) { - ivec2 sz = textureSize(InputTexture, 0); - return texelFetch(InputTexture, clamp(p, ivec2(0), sz - ivec2(1)), 0).rgb; + highp vec2 uv = (vec2(p) + 0.5) / pc.resolution; + return textureLod(InputTexture, uv, 0.0).rgb; } float AMin3F1(float x, float y, float z) { return min(x, min(y, z)); } diff --git a/app/src/main/cpp/shaders/cas_ffx_half_frag.h b/app/src/main/cpp/shaders/cas_ffx_half_frag.h index 22fbf6119b..2ba56158cc 100644 --- a/app/src/main/cpp/shaders/cas_ffx_half_frag.h +++ b/app/src/main/cpp/shaders/cas_ffx_half_frag.h @@ -1,214 +1,213 @@ - // 1116.2.0 + // 1115.1.0 #pragma once const uint32_t cas_ffx_half_code[] = { - 0x07230203,0x00010000,0x0008000b,0x000000d7,0x00000000,0x00020011,0x00000001,0x00020011, - 0x00000032,0x0006000b,0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e, - 0x00000000,0x00000001,0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000043, - 0x000000d1,0x00030010,0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005, - 0x00000004,0x6e69616d,0x00000000,0x00060005,0x0000000d,0x4c736143,0x2864616f,0x3b326976, - 0x00000000,0x00030005,0x0000000c,0x00000070,0x00070005,0x00000014,0x6e694d41,0x28314633, - 0x663b3166,0x31663b31,0x0000003b,0x00030005,0x00000011,0x00000078,0x00030005,0x00000012, - 0x00000079,0x00030005,0x00000013,0x0000007a,0x00070005,0x00000019,0x78614d41,0x28314633, - 0x663b3166,0x31663b31,0x0000003b,0x00030005,0x00000016,0x00000078,0x00030005,0x00000017, - 0x00000079,0x00030005,0x00000018,0x0000007a,0x00030005,0x0000001b,0x00007a73,0x00060005, - 0x0000001f,0x75706e49,0x78655474,0x65727574,0x00000000,0x00030005,0x00000040,0x00007073, - 0x00060005,0x00000043,0x67617266,0x43786554,0x64726f6f,0x00000000,0x00030005,0x00000045, - 0x00004350,0x00040006,0x00000045,0x00000000,0x0063646e,0x00060006,0x00000045,0x00000001, - 0x6f736572,0x6974756c,0x00006e6f,0x00060006,0x00000045,0x00000002,0x72616873,0x73656e70, - 0x00000073,0x00030005,0x00000047,0x00006370,0x00040005,0x0000004d,0x6b616570,0x00000000, - 0x00030005,0x0000005b,0x00000062,0x00040005,0x00000060,0x61726170,0x0000006d,0x00030005, - 0x00000062,0x00000064,0x00040005,0x00000066,0x61726170,0x0000006d,0x00030005,0x00000068, - 0x00000065,0x00040005,0x00000069,0x61726170,0x0000006d,0x00030005,0x0000006c,0x00000066, - 0x00040005,0x00000070,0x61726170,0x0000006d,0x00030005,0x00000072,0x00000068,0x00040005, - 0x00000076,0x61726170,0x0000006d,0x00030005,0x00000078,0x00476e6d,0x00040005,0x00000079, - 0x61726170,0x0000006d,0x00040005,0x0000007e,0x61726170,0x0000006d,0x00040005,0x00000081, - 0x61726170,0x0000006d,0x00040005,0x00000085,0x61726170,0x0000006d,0x00040005,0x00000086, - 0x61726170,0x0000006d,0x00040005,0x00000089,0x61726170,0x0000006d,0x00030005,0x0000008d, - 0x0047786d,0x00040005,0x0000008e,0x61726170,0x0000006d,0x00040005,0x00000091,0x61726170, - 0x0000006d,0x00040005,0x00000094,0x61726170,0x0000006d,0x00040005,0x00000098,0x61726170, - 0x0000006d,0x00040005,0x00000099,0x61726170,0x0000006d,0x00040005,0x0000009c,0x61726170, - 0x0000006d,0x00040005,0x000000a0,0x4d706372,0x00000047,0x00040005,0x000000a5,0x47706d61, - 0x00000000,0x00030005,0x000000af,0x00004777,0x00050005,0x000000b3,0x57706372,0x68676965, - 0x00000074,0x00030005,0x000000b9,0x00786970,0x00050005,0x000000d1,0x4374756f,0x726f6c6f, - 0x00000000,0x00030047,0x0000000d,0x00000000,0x00030047,0x00000011,0x00000000,0x00030047, - 0x00000012,0x00000000,0x00030047,0x00000013,0x00000000,0x00030047,0x00000014,0x00000000, - 0x00030047,0x00000016,0x00000000,0x00030047,0x00000017,0x00000000,0x00030047,0x00000018, - 0x00000000,0x00030047,0x00000019,0x00000000,0x00030047,0x0000001f,0x00000000,0x00040047, - 0x0000001f,0x00000021,0x00000000,0x00040047,0x0000001f,0x00000022,0x00000000,0x00030047, - 0x00000020,0x00000000,0x00030047,0x00000024,0x00000000,0x00030047,0x0000002e,0x00000000, - 0x00030047,0x0000002f,0x00000000,0x00030047,0x00000032,0x00000000,0x00030047,0x00000033, - 0x00000000,0x00030047,0x00000034,0x00000000,0x00030047,0x00000035,0x00000000,0x00030047, - 0x00000036,0x00000000,0x00030047,0x00000039,0x00000000,0x00030047,0x0000003a,0x00000000, - 0x00030047,0x0000003b,0x00000000,0x00030047,0x0000003c,0x00000000,0x00030047,0x0000003d, - 0x00000000,0x00040047,0x00000043,0x0000001e,0x00000000,0x00030047,0x00000045,0x00000002, - 0x00050048,0x00000045,0x00000000,0x00000023,0x00000000,0x00050048,0x00000045,0x00000001, - 0x00000023,0x00000010,0x00040048,0x00000045,0x00000002,0x00000000,0x00050048,0x00000045, - 0x00000002,0x00000023,0x00000018,0x00030047,0x0000004d,0x00000000,0x00030047,0x00000054, - 0x00000000,0x00030047,0x00000057,0x00000000,0x00030047,0x00000058,0x00000000,0x00030047, - 0x00000059,0x00000000,0x00030047,0x0000005b,0x00000000,0x00030047,0x00000061,0x00000000, - 0x00030047,0x00000062,0x00000000,0x00030047,0x00000067,0x00000000,0x00030047,0x00000068, - 0x00000000,0x00030047,0x0000006b,0x00000000,0x00030047,0x0000006c,0x00000000,0x00030047, - 0x00000071,0x00000000,0x00030047,0x00000072,0x00000000,0x00030047,0x00000077,0x00000000, - 0x00030047,0x00000078,0x00000000,0x00030047,0x00000079,0x00000000,0x00030047,0x0000007d, - 0x00000000,0x00030047,0x0000007e,0x00000000,0x00030047,0x00000080,0x00000000,0x00030047, - 0x00000081,0x00000000,0x00030047,0x00000083,0x00000000,0x00030047,0x00000084,0x00000000, - 0x00030047,0x00000085,0x00000000,0x00030047,0x00000086,0x00000000,0x00030047,0x00000088, - 0x00000000,0x00030047,0x00000089,0x00000000,0x00030047,0x0000008b,0x00000000,0x00030047, - 0x0000008c,0x00000000,0x00030047,0x0000008d,0x00000000,0x00030047,0x0000008e,0x00000000, - 0x00030047,0x00000090,0x00000000,0x00030047,0x00000091,0x00000000,0x00030047,0x00000093, - 0x00000000,0x00030047,0x00000094,0x00000000,0x00030047,0x00000096,0x00000000,0x00030047, - 0x00000097,0x00000000,0x00030047,0x00000098,0x00000000,0x00030047,0x00000099,0x00000000, - 0x00030047,0x0000009b,0x00000000,0x00030047,0x0000009c,0x00000000,0x00030047,0x0000009e, - 0x00000000,0x00030047,0x0000009f,0x00000000,0x00030047,0x000000a0,0x00000000,0x00030047, - 0x000000a1,0x00000000,0x00030047,0x000000a3,0x00000000,0x00030047,0x000000a4,0x00000000, - 0x00030047,0x000000a5,0x00000000,0x00030047,0x000000a6,0x00000000,0x00030047,0x000000a7, - 0x00000000,0x00030047,0x000000a8,0x00000000,0x00030047,0x000000a9,0x00000000,0x00030047, - 0x000000aa,0x00000000,0x00030047,0x000000ab,0x00000000,0x00030047,0x000000ac,0x00000000, - 0x00030047,0x000000ad,0x00000000,0x00030047,0x000000ae,0x00000000,0x00030047,0x000000af, - 0x00000000,0x00030047,0x000000b0,0x00000000,0x00030047,0x000000b1,0x00000000,0x00030047, - 0x000000b2,0x00000000,0x00030047,0x000000b3,0x00000000,0x00030047,0x000000b5,0x00000000, - 0x00030047,0x000000b6,0x00000000,0x00030047,0x000000b7,0x00000000,0x00030047,0x000000b8, - 0x00000000,0x00030047,0x000000b9,0x00000000,0x00030047,0x000000ba,0x00000000,0x00030047, - 0x000000bb,0x00000000,0x00030047,0x000000bc,0x00000000,0x00030047,0x000000bd,0x00000000, - 0x00030047,0x000000be,0x00000000,0x00030047,0x000000bf,0x00000000,0x00030047,0x000000c0, - 0x00000000,0x00030047,0x000000c1,0x00000000,0x00030047,0x000000c2,0x00000000,0x00030047, - 0x000000c3,0x00000000,0x00030047,0x000000c4,0x00000000,0x00030047,0x000000c5,0x00000000, - 0x00030047,0x000000c6,0x00000000,0x00030047,0x000000c7,0x00000000,0x00030047,0x000000c8, - 0x00000000,0x00030047,0x000000c9,0x00000000,0x00030047,0x000000ca,0x00000000,0x00030047, - 0x000000cb,0x00000000,0x00030047,0x000000cc,0x00000000,0x00030047,0x000000cd,0x00000000, - 0x00030047,0x000000ce,0x00000000,0x00030047,0x000000cf,0x00000000,0x00030047,0x000000d1, - 0x00000000,0x00040047,0x000000d1,0x0000001e,0x00000000,0x00030047,0x000000d2,0x00000000, - 0x00030047,0x000000d3,0x00000000,0x00030047,0x000000d4,0x00000000,0x00030047,0x000000d5, - 0x00000000,0x00030047,0x000000d6,0x00000000,0x00020013,0x00000002,0x00030021,0x00000003, - 0x00000002,0x00040015,0x00000006,0x00000020,0x00000001,0x00040017,0x00000007,0x00000006, - 0x00000002,0x00040020,0x00000008,0x00000007,0x00000007,0x00030016,0x00000009,0x00000020, - 0x00040017,0x0000000a,0x00000009,0x00000003,0x00040021,0x0000000b,0x0000000a,0x00000008, - 0x00040020,0x0000000f,0x00000007,0x00000009,0x00060021,0x00000010,0x00000009,0x0000000f, - 0x0000000f,0x0000000f,0x00090019,0x0000001c,0x00000009,0x00000001,0x00000000,0x00000000, - 0x00000000,0x00000001,0x00000000,0x0003001b,0x0000001d,0x0000001c,0x00040020,0x0000001e, - 0x00000000,0x0000001d,0x0004003b,0x0000001e,0x0000001f,0x00000000,0x0004002b,0x00000006, - 0x00000021,0x00000000,0x0005002c,0x00000007,0x00000026,0x00000021,0x00000021,0x0004002b, - 0x00000006,0x00000028,0x00000001,0x0005002c,0x00000007,0x00000029,0x00000028,0x00000028, - 0x00040017,0x0000002d,0x00000009,0x00000004,0x00040017,0x00000041,0x00000009,0x00000002, - 0x00040020,0x00000042,0x00000001,0x00000041,0x0004003b,0x00000042,0x00000043,0x00000001, - 0x0005001e,0x00000045,0x0000002d,0x00000041,0x00000009,0x00040020,0x00000046,0x00000009, - 0x00000045,0x0004003b,0x00000046,0x00000047,0x00000009,0x00040020,0x00000048,0x00000009, - 0x00000041,0x0004002b,0x00000009,0x0000004e,0xbf800000,0x0004002b,0x00000009,0x0000004f, - 0x41000000,0x0004002b,0x00000009,0x00000050,0x40a00000,0x0004002b,0x00000006,0x00000051, - 0x00000002,0x00040020,0x00000052,0x00000009,0x00000009,0x0004002b,0x00000009,0x00000055, - 0x00000000,0x0004002b,0x00000009,0x00000056,0x3f800000,0x00040020,0x0000005a,0x00000007, - 0x0000000a,0x0004002b,0x00000006,0x0000005d,0xffffffff,0x0005002c,0x00000007,0x0000005e, - 0x00000021,0x0000005d,0x0005002c,0x00000007,0x00000064,0x0000005d,0x00000021,0x0005002c, - 0x00000007,0x0000006e,0x00000028,0x00000021,0x0005002c,0x00000007,0x00000074,0x00000021, - 0x00000028,0x00040015,0x0000007a,0x00000020,0x00000000,0x0004002b,0x0000007a,0x0000007b, - 0x00000001,0x0004002b,0x00000009,0x000000a2,0x3a800000,0x0004002b,0x00000009,0x000000b4, - 0x40800000,0x00040020,0x000000d0,0x00000003,0x0000002d,0x0004003b,0x000000d0,0x000000d1, - 0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005, - 0x0004003b,0x00000008,0x00000040,0x00000007,0x0004003b,0x0000000f,0x0000004d,0x00000007, - 0x0004003b,0x0000005a,0x0000005b,0x00000007,0x0004003b,0x00000008,0x00000060,0x00000007, - 0x0004003b,0x0000005a,0x00000062,0x00000007,0x0004003b,0x00000008,0x00000066,0x00000007, - 0x0004003b,0x0000005a,0x00000068,0x00000007,0x0004003b,0x00000008,0x00000069,0x00000007, - 0x0004003b,0x0000005a,0x0000006c,0x00000007,0x0004003b,0x00000008,0x00000070,0x00000007, - 0x0004003b,0x0000005a,0x00000072,0x00000007,0x0004003b,0x00000008,0x00000076,0x00000007, - 0x0004003b,0x0000000f,0x00000078,0x00000007,0x0004003b,0x0000000f,0x00000079,0x00000007, - 0x0004003b,0x0000000f,0x0000007e,0x00000007,0x0004003b,0x0000000f,0x00000081,0x00000007, - 0x0004003b,0x0000000f,0x00000085,0x00000007,0x0004003b,0x0000000f,0x00000086,0x00000007, - 0x0004003b,0x0000000f,0x00000089,0x00000007,0x0004003b,0x0000000f,0x0000008d,0x00000007, - 0x0004003b,0x0000000f,0x0000008e,0x00000007,0x0004003b,0x0000000f,0x00000091,0x00000007, - 0x0004003b,0x0000000f,0x00000094,0x00000007,0x0004003b,0x0000000f,0x00000098,0x00000007, - 0x0004003b,0x0000000f,0x00000099,0x00000007,0x0004003b,0x0000000f,0x0000009c,0x00000007, - 0x0004003b,0x0000000f,0x000000a0,0x00000007,0x0004003b,0x0000000f,0x000000a5,0x00000007, - 0x0004003b,0x0000000f,0x000000af,0x00000007,0x0004003b,0x0000000f,0x000000b3,0x00000007, - 0x0004003b,0x0000005a,0x000000b9,0x00000007,0x0004003d,0x00000041,0x00000044,0x00000043, - 0x00050041,0x00000048,0x00000049,0x00000047,0x00000028,0x0004003d,0x00000041,0x0000004a, - 0x00000049,0x00050085,0x00000041,0x0000004b,0x00000044,0x0000004a,0x0004006e,0x00000007, - 0x0000004c,0x0000004b,0x0003003e,0x00000040,0x0000004c,0x00050041,0x00000052,0x00000053, - 0x00000047,0x00000051,0x0004003d,0x00000009,0x00000054,0x00000053,0x0008000c,0x00000009, - 0x00000057,0x00000001,0x0000002b,0x00000054,0x00000055,0x00000056,0x0008000c,0x00000009, - 0x00000058,0x00000001,0x0000002e,0x0000004f,0x00000050,0x00000057,0x00050088,0x00000009, - 0x00000059,0x0000004e,0x00000058,0x0003003e,0x0000004d,0x00000059,0x0004003d,0x00000007, - 0x0000005c,0x00000040,0x00050080,0x00000007,0x0000005f,0x0000005c,0x0000005e,0x0003003e, - 0x00000060,0x0000005f,0x00050039,0x0000000a,0x00000061,0x0000000d,0x00000060,0x0003003e, - 0x0000005b,0x00000061,0x0004003d,0x00000007,0x00000063,0x00000040,0x00050080,0x00000007, - 0x00000065,0x00000063,0x00000064,0x0003003e,0x00000066,0x00000065,0x00050039,0x0000000a, - 0x00000067,0x0000000d,0x00000066,0x0003003e,0x00000062,0x00000067,0x0004003d,0x00000007, - 0x0000006a,0x00000040,0x0003003e,0x00000069,0x0000006a,0x00050039,0x0000000a,0x0000006b, - 0x0000000d,0x00000069,0x0003003e,0x00000068,0x0000006b,0x0004003d,0x00000007,0x0000006d, - 0x00000040,0x00050080,0x00000007,0x0000006f,0x0000006d,0x0000006e,0x0003003e,0x00000070, - 0x0000006f,0x00050039,0x0000000a,0x00000071,0x0000000d,0x00000070,0x0003003e,0x0000006c, - 0x00000071,0x0004003d,0x00000007,0x00000073,0x00000040,0x00050080,0x00000007,0x00000075, - 0x00000073,0x00000074,0x0003003e,0x00000076,0x00000075,0x00050039,0x0000000a,0x00000077, - 0x0000000d,0x00000076,0x0003003e,0x00000072,0x00000077,0x00050041,0x0000000f,0x0000007c, - 0x00000062,0x0000007b,0x0004003d,0x00000009,0x0000007d,0x0000007c,0x0003003e,0x00000079, - 0x0000007d,0x00050041,0x0000000f,0x0000007f,0x00000068,0x0000007b,0x0004003d,0x00000009, - 0x00000080,0x0000007f,0x0003003e,0x0000007e,0x00000080,0x00050041,0x0000000f,0x00000082, - 0x0000006c,0x0000007b,0x0004003d,0x00000009,0x00000083,0x00000082,0x0003003e,0x00000081, - 0x00000083,0x00070039,0x00000009,0x00000084,0x00000014,0x00000079,0x0000007e,0x00000081, - 0x0003003e,0x00000085,0x00000084,0x00050041,0x0000000f,0x00000087,0x0000005b,0x0000007b, - 0x0004003d,0x00000009,0x00000088,0x00000087,0x0003003e,0x00000086,0x00000088,0x00050041, - 0x0000000f,0x0000008a,0x00000072,0x0000007b,0x0004003d,0x00000009,0x0000008b,0x0000008a, - 0x0003003e,0x00000089,0x0000008b,0x00070039,0x00000009,0x0000008c,0x00000014,0x00000085, - 0x00000086,0x00000089,0x0003003e,0x00000078,0x0000008c,0x00050041,0x0000000f,0x0000008f, - 0x00000062,0x0000007b,0x0004003d,0x00000009,0x00000090,0x0000008f,0x0003003e,0x0000008e, - 0x00000090,0x00050041,0x0000000f,0x00000092,0x00000068,0x0000007b,0x0004003d,0x00000009, - 0x00000093,0x00000092,0x0003003e,0x00000091,0x00000093,0x00050041,0x0000000f,0x00000095, - 0x0000006c,0x0000007b,0x0004003d,0x00000009,0x00000096,0x00000095,0x0003003e,0x00000094, - 0x00000096,0x00070039,0x00000009,0x00000097,0x00000019,0x0000008e,0x00000091,0x00000094, - 0x0003003e,0x00000098,0x00000097,0x00050041,0x0000000f,0x0000009a,0x0000005b,0x0000007b, - 0x0004003d,0x00000009,0x0000009b,0x0000009a,0x0003003e,0x00000099,0x0000009b,0x00050041, - 0x0000000f,0x0000009d,0x00000072,0x0000007b,0x0004003d,0x00000009,0x0000009e,0x0000009d, - 0x0003003e,0x0000009c,0x0000009e,0x00070039,0x00000009,0x0000009f,0x00000019,0x00000098, - 0x00000099,0x0000009c,0x0003003e,0x0000008d,0x0000009f,0x0004003d,0x00000009,0x000000a1, - 0x0000008d,0x0007000c,0x00000009,0x000000a3,0x00000001,0x00000028,0x000000a1,0x000000a2, - 0x00050088,0x00000009,0x000000a4,0x00000056,0x000000a3,0x0003003e,0x000000a0,0x000000a4, - 0x0004003d,0x00000009,0x000000a6,0x00000078,0x0004003d,0x00000009,0x000000a7,0x0000008d, - 0x00050083,0x00000009,0x000000a8,0x00000056,0x000000a7,0x0007000c,0x00000009,0x000000a9, - 0x00000001,0x00000025,0x000000a6,0x000000a8,0x0004003d,0x00000009,0x000000aa,0x000000a0, - 0x00050085,0x00000009,0x000000ab,0x000000a9,0x000000aa,0x0008000c,0x00000009,0x000000ac, - 0x00000001,0x0000002b,0x000000ab,0x00000055,0x00000056,0x0003003e,0x000000a5,0x000000ac, - 0x0004003d,0x00000009,0x000000ad,0x000000a5,0x0006000c,0x00000009,0x000000ae,0x00000001, - 0x0000001f,0x000000ad,0x0003003e,0x000000a5,0x000000ae,0x0004003d,0x00000009,0x000000b0, - 0x000000a5,0x0004003d,0x00000009,0x000000b1,0x0000004d,0x00050085,0x00000009,0x000000b2, - 0x000000b0,0x000000b1,0x0003003e,0x000000af,0x000000b2,0x0004003d,0x00000009,0x000000b5, - 0x000000af,0x00050085,0x00000009,0x000000b6,0x000000b4,0x000000b5,0x00050081,0x00000009, - 0x000000b7,0x00000056,0x000000b6,0x00050088,0x00000009,0x000000b8,0x00000056,0x000000b7, - 0x0003003e,0x000000b3,0x000000b8,0x0004003d,0x0000000a,0x000000ba,0x0000005b,0x0004003d, - 0x00000009,0x000000bb,0x000000af,0x0005008e,0x0000000a,0x000000bc,0x000000ba,0x000000bb, - 0x0004003d,0x0000000a,0x000000bd,0x00000062,0x0004003d,0x00000009,0x000000be,0x000000af, - 0x0005008e,0x0000000a,0x000000bf,0x000000bd,0x000000be,0x00050081,0x0000000a,0x000000c0, - 0x000000bc,0x000000bf,0x0004003d,0x0000000a,0x000000c1,0x0000006c,0x0004003d,0x00000009, - 0x000000c2,0x000000af,0x0005008e,0x0000000a,0x000000c3,0x000000c1,0x000000c2,0x00050081, - 0x0000000a,0x000000c4,0x000000c0,0x000000c3,0x0004003d,0x0000000a,0x000000c5,0x00000072, - 0x0004003d,0x00000009,0x000000c6,0x000000af,0x0005008e,0x0000000a,0x000000c7,0x000000c5, - 0x000000c6,0x00050081,0x0000000a,0x000000c8,0x000000c4,0x000000c7,0x0004003d,0x0000000a, - 0x000000c9,0x00000068,0x00050081,0x0000000a,0x000000ca,0x000000c8,0x000000c9,0x0004003d, - 0x00000009,0x000000cb,0x000000b3,0x0005008e,0x0000000a,0x000000cc,0x000000ca,0x000000cb, - 0x00060050,0x0000000a,0x000000cd,0x00000055,0x00000055,0x00000055,0x00060050,0x0000000a, - 0x000000ce,0x00000056,0x00000056,0x00000056,0x0008000c,0x0000000a,0x000000cf,0x00000001, - 0x0000002b,0x000000cc,0x000000cd,0x000000ce,0x0003003e,0x000000b9,0x000000cf,0x0004003d, - 0x0000000a,0x000000d2,0x000000b9,0x00050051,0x00000009,0x000000d3,0x000000d2,0x00000000, - 0x00050051,0x00000009,0x000000d4,0x000000d2,0x00000001,0x00050051,0x00000009,0x000000d5, - 0x000000d2,0x00000002,0x00070050,0x0000002d,0x000000d6,0x000000d3,0x000000d4,0x000000d5, - 0x00000056,0x0003003e,0x000000d1,0x000000d6,0x000100fd,0x00010038,0x00050036,0x0000000a, - 0x0000000d,0x00000000,0x0000000b,0x00030037,0x00000008,0x0000000c,0x000200f8,0x0000000e, - 0x0004003b,0x00000008,0x0000001b,0x00000007,0x0004003d,0x0000001d,0x00000020,0x0000001f, - 0x00040064,0x0000001c,0x00000022,0x00000020,0x00050067,0x00000007,0x00000023,0x00000022, - 0x00000021,0x0003003e,0x0000001b,0x00000023,0x0004003d,0x0000001d,0x00000024,0x0000001f, - 0x0004003d,0x00000007,0x00000025,0x0000000c,0x0004003d,0x00000007,0x00000027,0x0000001b, - 0x00050082,0x00000007,0x0000002a,0x00000027,0x00000029,0x0008000c,0x00000007,0x0000002b, - 0x00000001,0x0000002d,0x00000025,0x00000026,0x0000002a,0x00040064,0x0000001c,0x0000002c, - 0x00000024,0x0007005f,0x0000002d,0x0000002e,0x0000002c,0x0000002b,0x00000002,0x00000021, - 0x0008004f,0x0000000a,0x0000002f,0x0000002e,0x0000002e,0x00000000,0x00000001,0x00000002, - 0x000200fe,0x0000002f,0x00010038,0x00050036,0x00000009,0x00000014,0x00000000,0x00000010, - 0x00030037,0x0000000f,0x00000011,0x00030037,0x0000000f,0x00000012,0x00030037,0x0000000f, - 0x00000013,0x000200f8,0x00000015,0x0004003d,0x00000009,0x00000032,0x00000011,0x0004003d, - 0x00000009,0x00000033,0x00000012,0x0004003d,0x00000009,0x00000034,0x00000013,0x0007000c, - 0x00000009,0x00000035,0x00000001,0x00000025,0x00000033,0x00000034,0x0007000c,0x00000009, - 0x00000036,0x00000001,0x00000025,0x00000032,0x00000035,0x000200fe,0x00000036,0x00010038, - 0x00050036,0x00000009,0x00000019,0x00000000,0x00000010,0x00030037,0x0000000f,0x00000016, - 0x00030037,0x0000000f,0x00000017,0x00030037,0x0000000f,0x00000018,0x000200f8,0x0000001a, - 0x0004003d,0x00000009,0x00000039,0x00000016,0x0004003d,0x00000009,0x0000003a,0x00000017, - 0x0004003d,0x00000009,0x0000003b,0x00000018,0x0007000c,0x00000009,0x0000003c,0x00000001, - 0x00000028,0x0000003a,0x0000003b,0x0007000c,0x00000009,0x0000003d,0x00000001,0x00000028, - 0x00000039,0x0000003c,0x000200fe,0x0000003d,0x00010038 + 0x07230203,0x00010000,0x0008000b,0x000000d7,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, + 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000047,0x000000d1,0x00030010, + 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, + 0x00000000,0x00060005,0x0000000d,0x4c736143,0x2864616f,0x3b326976,0x00000000,0x00030005, + 0x0000000c,0x00000070,0x00070005,0x00000014,0x6e694d41,0x28314633,0x663b3166,0x31663b31, + 0x0000003b,0x00030005,0x00000011,0x00000078,0x00030005,0x00000012,0x00000079,0x00030005, + 0x00000013,0x0000007a,0x00070005,0x00000019,0x78614d41,0x28314633,0x663b3166,0x31663b31, + 0x0000003b,0x00030005,0x00000016,0x00000078,0x00030005,0x00000017,0x00000079,0x00030005, + 0x00000018,0x0000007a,0x00030005,0x0000001d,0x00007675,0x00030005,0x00000024,0x00004350, + 0x00040006,0x00000024,0x00000000,0x0063646e,0x00060006,0x00000024,0x00000001,0x6f736572, + 0x6974756c,0x00006e6f,0x00060006,0x00000024,0x00000002,0x72616873,0x73656e70,0x00000073, + 0x00030005,0x00000026,0x00006370,0x00060005,0x0000002f,0x75706e49,0x78655474,0x65727574, + 0x00000000,0x00030005,0x00000045,0x00007073,0x00060005,0x00000047,0x67617266,0x43786554, + 0x64726f6f,0x00000000,0x00040005,0x0000004d,0x6b616570,0x00000000,0x00030005,0x0000005a, + 0x00000062,0x00040005,0x00000060,0x61726170,0x0000006d,0x00030005,0x00000062,0x00000064, + 0x00040005,0x00000066,0x61726170,0x0000006d,0x00030005,0x00000068,0x00000065,0x00040005, + 0x00000069,0x61726170,0x0000006d,0x00030005,0x0000006c,0x00000066,0x00040005,0x00000070, + 0x61726170,0x0000006d,0x00030005,0x00000072,0x00000068,0x00040005,0x00000076,0x61726170, + 0x0000006d,0x00030005,0x00000078,0x00476e6d,0x00040005,0x00000079,0x61726170,0x0000006d, + 0x00040005,0x0000007e,0x61726170,0x0000006d,0x00040005,0x00000081,0x61726170,0x0000006d, + 0x00040005,0x00000085,0x61726170,0x0000006d,0x00040005,0x00000086,0x61726170,0x0000006d, + 0x00040005,0x00000089,0x61726170,0x0000006d,0x00030005,0x0000008d,0x0047786d,0x00040005, + 0x0000008e,0x61726170,0x0000006d,0x00040005,0x00000091,0x61726170,0x0000006d,0x00040005, + 0x00000094,0x61726170,0x0000006d,0x00040005,0x00000098,0x61726170,0x0000006d,0x00040005, + 0x00000099,0x61726170,0x0000006d,0x00040005,0x0000009c,0x61726170,0x0000006d,0x00040005, + 0x000000a0,0x4d706372,0x00000047,0x00040005,0x000000a5,0x47706d61,0x00000000,0x00030005, + 0x000000af,0x00004777,0x00050005,0x000000b3,0x57706372,0x68676965,0x00000074,0x00030005, + 0x000000b9,0x00786970,0x00050005,0x000000d1,0x4374756f,0x726f6c6f,0x00000000,0x00030047, + 0x0000000d,0x00000000,0x00030047,0x00000011,0x00000000,0x00030047,0x00000012,0x00000000, + 0x00030047,0x00000013,0x00000000,0x00030047,0x00000014,0x00000000,0x00030047,0x00000016, + 0x00000000,0x00030047,0x00000017,0x00000000,0x00030047,0x00000018,0x00000000,0x00030047, + 0x00000019,0x00000000,0x00030047,0x00000024,0x00000002,0x00050048,0x00000024,0x00000000, + 0x00000023,0x00000000,0x00050048,0x00000024,0x00000001,0x00000023,0x00000010,0x00040048, + 0x00000024,0x00000002,0x00000000,0x00050048,0x00000024,0x00000002,0x00000023,0x00000018, + 0x00030047,0x0000002f,0x00000000,0x00040047,0x0000002f,0x00000021,0x00000000,0x00040047, + 0x0000002f,0x00000022,0x00000000,0x00030047,0x00000030,0x00000000,0x00030047,0x00000033, + 0x00000000,0x00030047,0x00000034,0x00000000,0x00030047,0x00000037,0x00000000,0x00030047, + 0x00000038,0x00000000,0x00030047,0x00000039,0x00000000,0x00030047,0x0000003a,0x00000000, + 0x00030047,0x0000003b,0x00000000,0x00030047,0x0000003e,0x00000000,0x00030047,0x0000003f, + 0x00000000,0x00030047,0x00000040,0x00000000,0x00030047,0x00000041,0x00000000,0x00030047, + 0x00000042,0x00000000,0x00040047,0x00000047,0x0000001e,0x00000000,0x00030047,0x0000004d, + 0x00000000,0x00030047,0x00000054,0x00000000,0x00030047,0x00000056,0x00000000,0x00030047, + 0x00000057,0x00000000,0x00030047,0x00000058,0x00000000,0x00030047,0x0000005a,0x00000000, + 0x00030047,0x00000061,0x00000000,0x00030047,0x00000062,0x00000000,0x00030047,0x00000067, + 0x00000000,0x00030047,0x00000068,0x00000000,0x00030047,0x0000006b,0x00000000,0x00030047, + 0x0000006c,0x00000000,0x00030047,0x00000071,0x00000000,0x00030047,0x00000072,0x00000000, + 0x00030047,0x00000077,0x00000000,0x00030047,0x00000078,0x00000000,0x00030047,0x00000079, + 0x00000000,0x00030047,0x0000007d,0x00000000,0x00030047,0x0000007e,0x00000000,0x00030047, + 0x00000080,0x00000000,0x00030047,0x00000081,0x00000000,0x00030047,0x00000083,0x00000000, + 0x00030047,0x00000084,0x00000000,0x00030047,0x00000085,0x00000000,0x00030047,0x00000086, + 0x00000000,0x00030047,0x00000088,0x00000000,0x00030047,0x00000089,0x00000000,0x00030047, + 0x0000008b,0x00000000,0x00030047,0x0000008c,0x00000000,0x00030047,0x0000008d,0x00000000, + 0x00030047,0x0000008e,0x00000000,0x00030047,0x00000090,0x00000000,0x00030047,0x00000091, + 0x00000000,0x00030047,0x00000093,0x00000000,0x00030047,0x00000094,0x00000000,0x00030047, + 0x00000096,0x00000000,0x00030047,0x00000097,0x00000000,0x00030047,0x00000098,0x00000000, + 0x00030047,0x00000099,0x00000000,0x00030047,0x0000009b,0x00000000,0x00030047,0x0000009c, + 0x00000000,0x00030047,0x0000009e,0x00000000,0x00030047,0x0000009f,0x00000000,0x00030047, + 0x000000a0,0x00000000,0x00030047,0x000000a1,0x00000000,0x00030047,0x000000a3,0x00000000, + 0x00030047,0x000000a4,0x00000000,0x00030047,0x000000a5,0x00000000,0x00030047,0x000000a6, + 0x00000000,0x00030047,0x000000a7,0x00000000,0x00030047,0x000000a8,0x00000000,0x00030047, + 0x000000a9,0x00000000,0x00030047,0x000000aa,0x00000000,0x00030047,0x000000ab,0x00000000, + 0x00030047,0x000000ac,0x00000000,0x00030047,0x000000ad,0x00000000,0x00030047,0x000000ae, + 0x00000000,0x00030047,0x000000af,0x00000000,0x00030047,0x000000b0,0x00000000,0x00030047, + 0x000000b1,0x00000000,0x00030047,0x000000b2,0x00000000,0x00030047,0x000000b3,0x00000000, + 0x00030047,0x000000b5,0x00000000,0x00030047,0x000000b6,0x00000000,0x00030047,0x000000b7, + 0x00000000,0x00030047,0x000000b8,0x00000000,0x00030047,0x000000b9,0x00000000,0x00030047, + 0x000000ba,0x00000000,0x00030047,0x000000bb,0x00000000,0x00030047,0x000000bc,0x00000000, + 0x00030047,0x000000bd,0x00000000,0x00030047,0x000000be,0x00000000,0x00030047,0x000000bf, + 0x00000000,0x00030047,0x000000c0,0x00000000,0x00030047,0x000000c1,0x00000000,0x00030047, + 0x000000c2,0x00000000,0x00030047,0x000000c3,0x00000000,0x00030047,0x000000c4,0x00000000, + 0x00030047,0x000000c5,0x00000000,0x00030047,0x000000c6,0x00000000,0x00030047,0x000000c7, + 0x00000000,0x00030047,0x000000c8,0x00000000,0x00030047,0x000000c9,0x00000000,0x00030047, + 0x000000ca,0x00000000,0x00030047,0x000000cb,0x00000000,0x00030047,0x000000cc,0x00000000, + 0x00030047,0x000000cd,0x00000000,0x00030047,0x000000ce,0x00000000,0x00030047,0x000000cf, + 0x00000000,0x00030047,0x000000d1,0x00000000,0x00040047,0x000000d1,0x0000001e,0x00000000, + 0x00030047,0x000000d2,0x00000000,0x00030047,0x000000d3,0x00000000,0x00030047,0x000000d4, + 0x00000000,0x00030047,0x000000d5,0x00000000,0x00030047,0x000000d6,0x00000000,0x00020013, + 0x00000002,0x00030021,0x00000003,0x00000002,0x00040015,0x00000006,0x00000020,0x00000001, + 0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000007,0x00000007, + 0x00030016,0x00000009,0x00000020,0x00040017,0x0000000a,0x00000009,0x00000003,0x00040021, + 0x0000000b,0x0000000a,0x00000008,0x00040020,0x0000000f,0x00000007,0x00000009,0x00060021, + 0x00000010,0x00000009,0x0000000f,0x0000000f,0x0000000f,0x00040017,0x0000001b,0x00000009, + 0x00000002,0x00040020,0x0000001c,0x00000007,0x0000001b,0x0004002b,0x00000009,0x00000020, + 0x3f000000,0x00040017,0x00000023,0x00000009,0x00000004,0x0005001e,0x00000024,0x00000023, + 0x0000001b,0x00000009,0x00040020,0x00000025,0x00000009,0x00000024,0x0004003b,0x00000025, + 0x00000026,0x00000009,0x0004002b,0x00000006,0x00000027,0x00000001,0x00040020,0x00000028, + 0x00000009,0x0000001b,0x00090019,0x0000002c,0x00000009,0x00000001,0x00000000,0x00000000, + 0x00000000,0x00000001,0x00000000,0x0003001b,0x0000002d,0x0000002c,0x00040020,0x0000002e, + 0x00000000,0x0000002d,0x0004003b,0x0000002e,0x0000002f,0x00000000,0x0004002b,0x00000009, + 0x00000032,0x00000000,0x00040020,0x00000046,0x00000001,0x0000001b,0x0004003b,0x00000046, + 0x00000047,0x00000001,0x0004002b,0x00000009,0x0000004e,0xbf800000,0x0004002b,0x00000009, + 0x0000004f,0x41000000,0x0004002b,0x00000009,0x00000050,0x40a00000,0x0004002b,0x00000006, + 0x00000051,0x00000002,0x00040020,0x00000052,0x00000009,0x00000009,0x0004002b,0x00000009, + 0x00000055,0x3f800000,0x00040020,0x00000059,0x00000007,0x0000000a,0x0004002b,0x00000006, + 0x0000005c,0x00000000,0x0004002b,0x00000006,0x0000005d,0xffffffff,0x0005002c,0x00000007, + 0x0000005e,0x0000005c,0x0000005d,0x0005002c,0x00000007,0x00000064,0x0000005d,0x0000005c, + 0x0005002c,0x00000007,0x0000006e,0x00000027,0x0000005c,0x0005002c,0x00000007,0x00000074, + 0x0000005c,0x00000027,0x00040015,0x0000007a,0x00000020,0x00000000,0x0004002b,0x0000007a, + 0x0000007b,0x00000001,0x0004002b,0x00000009,0x000000a2,0x3a800000,0x0004002b,0x00000009, + 0x000000b4,0x40800000,0x00040020,0x000000d0,0x00000003,0x00000023,0x0004003b,0x000000d0, + 0x000000d1,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, + 0x00000005,0x0004003b,0x00000008,0x00000045,0x00000007,0x0004003b,0x0000000f,0x0000004d, + 0x00000007,0x0004003b,0x00000059,0x0000005a,0x00000007,0x0004003b,0x00000008,0x00000060, + 0x00000007,0x0004003b,0x00000059,0x00000062,0x00000007,0x0004003b,0x00000008,0x00000066, + 0x00000007,0x0004003b,0x00000059,0x00000068,0x00000007,0x0004003b,0x00000008,0x00000069, + 0x00000007,0x0004003b,0x00000059,0x0000006c,0x00000007,0x0004003b,0x00000008,0x00000070, + 0x00000007,0x0004003b,0x00000059,0x00000072,0x00000007,0x0004003b,0x00000008,0x00000076, + 0x00000007,0x0004003b,0x0000000f,0x00000078,0x00000007,0x0004003b,0x0000000f,0x00000079, + 0x00000007,0x0004003b,0x0000000f,0x0000007e,0x00000007,0x0004003b,0x0000000f,0x00000081, + 0x00000007,0x0004003b,0x0000000f,0x00000085,0x00000007,0x0004003b,0x0000000f,0x00000086, + 0x00000007,0x0004003b,0x0000000f,0x00000089,0x00000007,0x0004003b,0x0000000f,0x0000008d, + 0x00000007,0x0004003b,0x0000000f,0x0000008e,0x00000007,0x0004003b,0x0000000f,0x00000091, + 0x00000007,0x0004003b,0x0000000f,0x00000094,0x00000007,0x0004003b,0x0000000f,0x00000098, + 0x00000007,0x0004003b,0x0000000f,0x00000099,0x00000007,0x0004003b,0x0000000f,0x0000009c, + 0x00000007,0x0004003b,0x0000000f,0x000000a0,0x00000007,0x0004003b,0x0000000f,0x000000a5, + 0x00000007,0x0004003b,0x0000000f,0x000000af,0x00000007,0x0004003b,0x0000000f,0x000000b3, + 0x00000007,0x0004003b,0x00000059,0x000000b9,0x00000007,0x0004003d,0x0000001b,0x00000048, + 0x00000047,0x00050041,0x00000028,0x00000049,0x00000026,0x00000027,0x0004003d,0x0000001b, + 0x0000004a,0x00000049,0x00050085,0x0000001b,0x0000004b,0x00000048,0x0000004a,0x0004006e, + 0x00000007,0x0000004c,0x0000004b,0x0003003e,0x00000045,0x0000004c,0x00050041,0x00000052, + 0x00000053,0x00000026,0x00000051,0x0004003d,0x00000009,0x00000054,0x00000053,0x0008000c, + 0x00000009,0x00000056,0x00000001,0x0000002b,0x00000054,0x00000032,0x00000055,0x0008000c, + 0x00000009,0x00000057,0x00000001,0x0000002e,0x0000004f,0x00000050,0x00000056,0x00050088, + 0x00000009,0x00000058,0x0000004e,0x00000057,0x0003003e,0x0000004d,0x00000058,0x0004003d, + 0x00000007,0x0000005b,0x00000045,0x00050080,0x00000007,0x0000005f,0x0000005b,0x0000005e, + 0x0003003e,0x00000060,0x0000005f,0x00050039,0x0000000a,0x00000061,0x0000000d,0x00000060, + 0x0003003e,0x0000005a,0x00000061,0x0004003d,0x00000007,0x00000063,0x00000045,0x00050080, + 0x00000007,0x00000065,0x00000063,0x00000064,0x0003003e,0x00000066,0x00000065,0x00050039, + 0x0000000a,0x00000067,0x0000000d,0x00000066,0x0003003e,0x00000062,0x00000067,0x0004003d, + 0x00000007,0x0000006a,0x00000045,0x0003003e,0x00000069,0x0000006a,0x00050039,0x0000000a, + 0x0000006b,0x0000000d,0x00000069,0x0003003e,0x00000068,0x0000006b,0x0004003d,0x00000007, + 0x0000006d,0x00000045,0x00050080,0x00000007,0x0000006f,0x0000006d,0x0000006e,0x0003003e, + 0x00000070,0x0000006f,0x00050039,0x0000000a,0x00000071,0x0000000d,0x00000070,0x0003003e, + 0x0000006c,0x00000071,0x0004003d,0x00000007,0x00000073,0x00000045,0x00050080,0x00000007, + 0x00000075,0x00000073,0x00000074,0x0003003e,0x00000076,0x00000075,0x00050039,0x0000000a, + 0x00000077,0x0000000d,0x00000076,0x0003003e,0x00000072,0x00000077,0x00050041,0x0000000f, + 0x0000007c,0x00000062,0x0000007b,0x0004003d,0x00000009,0x0000007d,0x0000007c,0x0003003e, + 0x00000079,0x0000007d,0x00050041,0x0000000f,0x0000007f,0x00000068,0x0000007b,0x0004003d, + 0x00000009,0x00000080,0x0000007f,0x0003003e,0x0000007e,0x00000080,0x00050041,0x0000000f, + 0x00000082,0x0000006c,0x0000007b,0x0004003d,0x00000009,0x00000083,0x00000082,0x0003003e, + 0x00000081,0x00000083,0x00070039,0x00000009,0x00000084,0x00000014,0x00000079,0x0000007e, + 0x00000081,0x0003003e,0x00000085,0x00000084,0x00050041,0x0000000f,0x00000087,0x0000005a, + 0x0000007b,0x0004003d,0x00000009,0x00000088,0x00000087,0x0003003e,0x00000086,0x00000088, + 0x00050041,0x0000000f,0x0000008a,0x00000072,0x0000007b,0x0004003d,0x00000009,0x0000008b, + 0x0000008a,0x0003003e,0x00000089,0x0000008b,0x00070039,0x00000009,0x0000008c,0x00000014, + 0x00000085,0x00000086,0x00000089,0x0003003e,0x00000078,0x0000008c,0x00050041,0x0000000f, + 0x0000008f,0x00000062,0x0000007b,0x0004003d,0x00000009,0x00000090,0x0000008f,0x0003003e, + 0x0000008e,0x00000090,0x00050041,0x0000000f,0x00000092,0x00000068,0x0000007b,0x0004003d, + 0x00000009,0x00000093,0x00000092,0x0003003e,0x00000091,0x00000093,0x00050041,0x0000000f, + 0x00000095,0x0000006c,0x0000007b,0x0004003d,0x00000009,0x00000096,0x00000095,0x0003003e, + 0x00000094,0x00000096,0x00070039,0x00000009,0x00000097,0x00000019,0x0000008e,0x00000091, + 0x00000094,0x0003003e,0x00000098,0x00000097,0x00050041,0x0000000f,0x0000009a,0x0000005a, + 0x0000007b,0x0004003d,0x00000009,0x0000009b,0x0000009a,0x0003003e,0x00000099,0x0000009b, + 0x00050041,0x0000000f,0x0000009d,0x00000072,0x0000007b,0x0004003d,0x00000009,0x0000009e, + 0x0000009d,0x0003003e,0x0000009c,0x0000009e,0x00070039,0x00000009,0x0000009f,0x00000019, + 0x00000098,0x00000099,0x0000009c,0x0003003e,0x0000008d,0x0000009f,0x0004003d,0x00000009, + 0x000000a1,0x0000008d,0x0007000c,0x00000009,0x000000a3,0x00000001,0x00000028,0x000000a1, + 0x000000a2,0x00050088,0x00000009,0x000000a4,0x00000055,0x000000a3,0x0003003e,0x000000a0, + 0x000000a4,0x0004003d,0x00000009,0x000000a6,0x00000078,0x0004003d,0x00000009,0x000000a7, + 0x0000008d,0x00050083,0x00000009,0x000000a8,0x00000055,0x000000a7,0x0007000c,0x00000009, + 0x000000a9,0x00000001,0x00000025,0x000000a6,0x000000a8,0x0004003d,0x00000009,0x000000aa, + 0x000000a0,0x00050085,0x00000009,0x000000ab,0x000000a9,0x000000aa,0x0008000c,0x00000009, + 0x000000ac,0x00000001,0x0000002b,0x000000ab,0x00000032,0x00000055,0x0003003e,0x000000a5, + 0x000000ac,0x0004003d,0x00000009,0x000000ad,0x000000a5,0x0006000c,0x00000009,0x000000ae, + 0x00000001,0x0000001f,0x000000ad,0x0003003e,0x000000a5,0x000000ae,0x0004003d,0x00000009, + 0x000000b0,0x000000a5,0x0004003d,0x00000009,0x000000b1,0x0000004d,0x00050085,0x00000009, + 0x000000b2,0x000000b0,0x000000b1,0x0003003e,0x000000af,0x000000b2,0x0004003d,0x00000009, + 0x000000b5,0x000000af,0x00050085,0x00000009,0x000000b6,0x000000b4,0x000000b5,0x00050081, + 0x00000009,0x000000b7,0x00000055,0x000000b6,0x00050088,0x00000009,0x000000b8,0x00000055, + 0x000000b7,0x0003003e,0x000000b3,0x000000b8,0x0004003d,0x0000000a,0x000000ba,0x0000005a, + 0x0004003d,0x00000009,0x000000bb,0x000000af,0x0005008e,0x0000000a,0x000000bc,0x000000ba, + 0x000000bb,0x0004003d,0x0000000a,0x000000bd,0x00000062,0x0004003d,0x00000009,0x000000be, + 0x000000af,0x0005008e,0x0000000a,0x000000bf,0x000000bd,0x000000be,0x00050081,0x0000000a, + 0x000000c0,0x000000bc,0x000000bf,0x0004003d,0x0000000a,0x000000c1,0x0000006c,0x0004003d, + 0x00000009,0x000000c2,0x000000af,0x0005008e,0x0000000a,0x000000c3,0x000000c1,0x000000c2, + 0x00050081,0x0000000a,0x000000c4,0x000000c0,0x000000c3,0x0004003d,0x0000000a,0x000000c5, + 0x00000072,0x0004003d,0x00000009,0x000000c6,0x000000af,0x0005008e,0x0000000a,0x000000c7, + 0x000000c5,0x000000c6,0x00050081,0x0000000a,0x000000c8,0x000000c4,0x000000c7,0x0004003d, + 0x0000000a,0x000000c9,0x00000068,0x00050081,0x0000000a,0x000000ca,0x000000c8,0x000000c9, + 0x0004003d,0x00000009,0x000000cb,0x000000b3,0x0005008e,0x0000000a,0x000000cc,0x000000ca, + 0x000000cb,0x00060050,0x0000000a,0x000000cd,0x00000032,0x00000032,0x00000032,0x00060050, + 0x0000000a,0x000000ce,0x00000055,0x00000055,0x00000055,0x0008000c,0x0000000a,0x000000cf, + 0x00000001,0x0000002b,0x000000cc,0x000000cd,0x000000ce,0x0003003e,0x000000b9,0x000000cf, + 0x0004003d,0x0000000a,0x000000d2,0x000000b9,0x00050051,0x00000009,0x000000d3,0x000000d2, + 0x00000000,0x00050051,0x00000009,0x000000d4,0x000000d2,0x00000001,0x00050051,0x00000009, + 0x000000d5,0x000000d2,0x00000002,0x00070050,0x00000023,0x000000d6,0x000000d3,0x000000d4, + 0x000000d5,0x00000055,0x0003003e,0x000000d1,0x000000d6,0x000100fd,0x00010038,0x00050036, + 0x0000000a,0x0000000d,0x00000000,0x0000000b,0x00030037,0x00000008,0x0000000c,0x000200f8, + 0x0000000e,0x0004003b,0x0000001c,0x0000001d,0x00000007,0x0004003d,0x00000007,0x0000001e, + 0x0000000c,0x0004006f,0x0000001b,0x0000001f,0x0000001e,0x00050050,0x0000001b,0x00000021, + 0x00000020,0x00000020,0x00050081,0x0000001b,0x00000022,0x0000001f,0x00000021,0x00050041, + 0x00000028,0x00000029,0x00000026,0x00000027,0x0004003d,0x0000001b,0x0000002a,0x00000029, + 0x00050088,0x0000001b,0x0000002b,0x00000022,0x0000002a,0x0003003e,0x0000001d,0x0000002b, + 0x0004003d,0x0000002d,0x00000030,0x0000002f,0x0004003d,0x0000001b,0x00000031,0x0000001d, + 0x00070058,0x00000023,0x00000033,0x00000030,0x00000031,0x00000002,0x00000032,0x0008004f, + 0x0000000a,0x00000034,0x00000033,0x00000033,0x00000000,0x00000001,0x00000002,0x000200fe, + 0x00000034,0x00010038,0x00050036,0x00000009,0x00000014,0x00000000,0x00000010,0x00030037, + 0x0000000f,0x00000011,0x00030037,0x0000000f,0x00000012,0x00030037,0x0000000f,0x00000013, + 0x000200f8,0x00000015,0x0004003d,0x00000009,0x00000037,0x00000011,0x0004003d,0x00000009, + 0x00000038,0x00000012,0x0004003d,0x00000009,0x00000039,0x00000013,0x0007000c,0x00000009, + 0x0000003a,0x00000001,0x00000025,0x00000038,0x00000039,0x0007000c,0x00000009,0x0000003b, + 0x00000001,0x00000025,0x00000037,0x0000003a,0x000200fe,0x0000003b,0x00010038,0x00050036, + 0x00000009,0x00000019,0x00000000,0x00000010,0x00030037,0x0000000f,0x00000016,0x00030037, + 0x0000000f,0x00000017,0x00030037,0x0000000f,0x00000018,0x000200f8,0x0000001a,0x0004003d, + 0x00000009,0x0000003e,0x00000016,0x0004003d,0x00000009,0x0000003f,0x00000017,0x0004003d, + 0x00000009,0x00000040,0x00000018,0x0007000c,0x00000009,0x00000041,0x00000001,0x00000028, + 0x0000003f,0x00000040,0x0007000c,0x00000009,0x00000042,0x00000001,0x00000028,0x0000003e, + 0x00000041,0x000200fe,0x00000042,0x00010038 }; diff --git a/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md b/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md new file mode 100644 index 0000000000..0872e65ca9 --- /dev/null +++ b/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md @@ -0,0 +1 @@ +ZeroFG is fetched by CMake from hy300leosquizz-ctrl/ZeroFG (the upstream repository) at pinned commit e6ca7ef9f9765db89847b6d8eed352e458f1a8bb. DroidDeck keeps ownership of presentation; the independent presenter is not used. License: Apache-2.0 OR GPL-2.0-or-later; see the fetched ZeroFG source tree for the license text. diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index 5bdc1e8385..2cd55b2761 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -42,6 +42,11 @@ add_library(droiddeckwayland SHARED src/hudframes.c src/hudframes_jni.c ) +option(DROIDDECK_FRAME_ACQUIRE_PROBE "Build opt-in signaled producer acquire protocol support" ON) +if (DROIDDECK_FRAME_ACQUIRE_PROBE) + target_sources(droiddeckwayland PRIVATE generated/droiddeck-frame-acquire-v1-protocol.c) + target_compile_definitions(droiddeckwayland PRIVATE DROIDDECK_FRAME_ACQUIRE_PROBE=1) +endif() target_compile_options(droiddeckwayland PRIVATE $<$:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>) target_include_directories(droiddeckwayland PRIVATE @@ -59,6 +64,7 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp message(STATUS "droiddeckwayland: frame-generation engines built in (LSFG Native, DD-FG Native)") target_sources(droiddeckwayland PRIVATE src/framegen_engine.cpp + src/framegen_zerofg.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_probe.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dll.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dxbc.cpp @@ -85,12 +91,12 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../framegen ) target_compile_options(droiddeckwayland PRIVATE - $<$:-std=c++17 -fvisibility=hidden>) + $<$:-std=c++20 -fvisibility=hidden>) target_compile_definitions(droiddeckwayland PRIVATE DDFG_UPSTREAM="${DDFG_UPSTREAM}" DDFG_CHAIN_HASH="${DDFG_CHAIN_HASH}" ) - target_link_libraries(droiddeckwayland dxbc atomic) + target_link_libraries(droiddeckwayland dxbc atomic zerofg::zerofg) else() message(STATUS "droiddeckwayland: frame-generation engines NOT built in (standalone build): stub") target_sources(droiddeckwayland PRIVATE src/framegen_engine_stub.c) diff --git a/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-protocol.c b/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-protocol.c new file mode 100644 index 0000000000..3d32474f56 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-protocol.c @@ -0,0 +1,35 @@ +/* Generated by wayland-scanner 1.22.0 */ + +#include +#include +#include "wayland-util.h" + +#ifndef __has_attribute +# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ +#endif + +#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4) +#define WL_PRIVATE __attribute__ ((visibility("hidden"))) +#else +#define WL_PRIVATE +#endif + +extern const struct wl_interface wl_buffer_interface; +extern const struct wl_interface wl_surface_interface; + +static const struct wl_interface *droiddeck_frame_acquire_v1_types[] = { + &wl_surface_interface, + &wl_buffer_interface, + NULL, +}; + +static const struct wl_message droiddeck_frame_acquire_v1_requests[] = { + { "destroy", "", droiddeck_frame_acquire_v1_types + 0 }, + { "set_acquire_fence", "ooh", droiddeck_frame_acquire_v1_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface droiddeck_frame_acquire_v1_interface = { + "droiddeck_frame_acquire_v1", 1, + 2, droiddeck_frame_acquire_v1_requests, + 0, NULL, +}; diff --git a/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-server-protocol.h new file mode 100644 index 0000000000..18f9466487 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-server-protocol.h @@ -0,0 +1,128 @@ +/* Generated by wayland-scanner 1.22.0 */ + +#ifndef DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H +#define DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H + +#include +#include +#include "wayland-server.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct wl_client; +struct wl_resource; + +/** + * @page page_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 protocol + * @section page_ifaces_droiddeck_frame_acquire_v1 Interfaces + * - @subpage page_iface_droiddeck_frame_acquire_v1 - DroidDeck producer write completion for a single Wayland attachment + */ +struct droiddeck_frame_acquire_v1; +struct wl_buffer; +struct wl_surface; + +#ifndef DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE +#define DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE +/** + * @page page_iface_droiddeck_frame_acquire_v1 droiddeck_frame_acquire_v1 + * @section page_iface_droiddeck_frame_acquire_v1_desc Description + * + * Optional explicit acquire sideband independent of DRM syncobj and buffer + * allocation. Binding does not opt the client out of ordinary wl_buffer + * release or existing synchronization protocols. The server advertises it + * only when it implements all semantics for the selected display path. + * @section page_iface_droiddeck_frame_acquire_v1_api API + * See @ref iface_droiddeck_frame_acquire_v1. + */ +/** + * @defgroup iface_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 interface + * + * Optional explicit acquire sideband independent of DRM syncobj and buffer + * allocation. Binding does not opt the client out of ordinary wl_buffer + * release or existing synchronization protocols. The server advertises it + * only when it implements all semantics for the selected display path. + */ +extern const struct wl_interface droiddeck_frame_acquire_v1_interface; +#endif + +#ifndef DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM +#define DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM +enum droiddeck_frame_acquire_v1_error { + /** + * not the same client's pending DMA-BUF attachment + */ + DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT = 0, + /** + * that attachment already has an acquire fence + */ + DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE = 1, + /** + * not a real successfully signaled Linux sync_file + */ + DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE = 2, + /** + * not the paired test peer + */ + DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER = 3, +}; +#endif /* DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM */ + +/** + * @ingroup iface_droiddeck_frame_acquire_v1 + * @struct droiddeck_frame_acquire_v1_interface + */ +struct droiddeck_frame_acquire_v1_interface { + /** + */ + void (*destroy)(struct wl_client *client, + struct wl_resource *resource); + /** + * set a one-shot kernel sync_file for the pending attachment + * + * After wl_surface.attach of a non-null buffer, and before its + * next wl_surface.commit, send the producer's final writer fence + * for that exact attachment. This outer probe requires that fence + * to have already successfully signaled. The fence must be a real + * Linux sync_file, not a dma-buf, eventfd, or Vulkan OPAQUE_FD. + * The server consumes its received descriptor once for that + * attachment; the caller closes its local FD after marshalling. + * + * The receiver validates the matching pending surface and buffer + * and validates the descriptor. A duplicate, invalid, pending or + * mismatched request is a protocol error; it is never downgraded + * to implicit sync. Another attach (even the same wl_buffer), + * detach, surface/resource loss or supersession makes the old + * proof inapplicable. Metadata-only commits may amend + * receiver-side still-pending state but cannot introduce or re-use + * a fence themselves. If no request was made, the receiver keeps + * its established safe path. If a valid fence has been accepted + * and later the layer is ineligible, the buffer must not be + * copied/read before that fence is satisfied or imported as the + * source dependency. Transport never implies readiness on missed + * deadlines and never changes release/retirement requirements. + * @param fence producer's native acquire sync_file + */ + void (*set_acquire_fence)(struct wl_client *client, + struct wl_resource *resource, + struct wl_resource *surface, + struct wl_resource *buffer, + int32_t fence); +}; + + +/** + * @ingroup iface_droiddeck_frame_acquire_v1 + */ +#define DROIDDECK_FRAME_ACQUIRE_V1_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_droiddeck_frame_acquire_v1 + */ +#define DROIDDECK_FRAME_ACQUIRE_V1_SET_ACQUIRE_FENCE_SINCE_VERSION 1 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/app/src/main/cpp/waylandcomp/protocols/droiddeck-frame-acquire-v1.xml b/app/src/main/cpp/waylandcomp/protocols/droiddeck-frame-acquire-v1.xml new file mode 100644 index 0000000000..ae4c26535b --- /dev/null +++ b/app/src/main/cpp/waylandcomp/protocols/droiddeck-frame-acquire-v1.xml @@ -0,0 +1,45 @@ + + + + + Optional explicit acquire sideband independent of DRM syncobj and buffer + allocation. Binding does not opt the client out of ordinary wl_buffer + release or existing synchronization protocols. The server advertises it + only when it implements all semantics for the selected display path and + only to the test fixture's app-authorized Gamescope worker. + + + + + + + + + + + After wl_surface.attach of a non-null buffer, and before its next + wl_surface.commit, send the producer's final writer fence for that + exact attachment. This outer probe requires that fence to have already + successfully signaled. The fence must be a real Linux sync_file, not a + dma-buf, eventfd, or Vulkan OPAQUE_FD. The server consumes its received + descriptor once for that attachment; the caller closes its local FD + after marshalling. + + The receiver validates the matching pending surface and buffer and + validates the descriptor. A duplicate, invalid, pending or mismatched + request is a protocol error; it is never downgraded to implicit sync. Another attach (even the same + wl_buffer), detach, surface/resource loss or supersession makes the + old proof inapplicable. Metadata-only commits may amend receiver-side + still-pending state but cannot introduce or re-use a fence themselves. + If no request was made, the receiver keeps its established safe path. + If a valid fence has been accepted and later the layer is ineligible, + the buffer must not be copied/read before that fence is satisfied or + imported as the source dependency. Transport never implies readiness + on missed deadlines and never changes release/retirement requirements. + + + + + + + diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c index 3ac9ec78fc..26618c67f6 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c @@ -7,6 +7,7 @@ #include "droiddeck-ahb-v1-server-protocol.h" #include #include +#include #include #include #include @@ -53,6 +54,7 @@ static struct wl_list g_clients; static uint64_t g_next_id = 1; static struct wl_event_loop *g_loop; static unsigned g_stat_zero_copy; +static unsigned g_stat_producer_fence; static int g_export_failed_logged, g_import_failed_logged; static int g_advertised; static int g_mode_sent = -1; @@ -145,6 +147,12 @@ static void handle_released(uint64_t id, int fd) { if (poll(&p, 1, 0) > 0) { close(fd); } else { + if (ab->fence_src) { + struct sync_merge_data m = {.name = "droiddeck-release", .fd2 = fd}; + if (ioctl(ab->fence_fd, SYNC_IOC_MERGE, &m) == 0) { close(fd); fd = m.fence; } + wl_event_source_remove(ab->fence_src); + close(ab->fence_fd); + } ab->fence_fd = fd; ab->fence_src = wl_event_loop_add_fd(g_loop, fd, WL_EVENT_READABLE, on_fence_readable, ab); if (!ab->fence_src) { close(fd); ab->fence_fd = -1; } @@ -152,6 +160,7 @@ static void handle_released(uint64_t id, int fd) { } } } + if (ab->fence_src) return; send_deferred_release(ab); maybe_free(ab); } @@ -193,27 +202,47 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_ struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL; if (!ab) return -1; int dmabuf_fd = droiddeck_dmabuf_fd(b); - int acquire = -1; - struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1}; - if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) { - acquire = exp.fd; - } else if (dmabuf_fd >= 0) { - if (!g_export_failed_logged) { - g_export_failed_logged = 1; - droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_EXPORT_SYNC_FILE failed (%s): waiting for each frame on the CPU instead", - strerror(errno)); + int acquire = droiddeck_surface_dup_acquire(s, b); + if (acquire == -2) return -1; +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + const int explicit_acquire = acquire >= 0; +#endif + if (acquire < 0) { + struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1}; + if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) { + acquire = exp.fd; + } else { + if (!g_export_failed_logged) { + g_export_failed_logged = 1; + droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s", + dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd", + draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU"); + } + if (dmabuf_fd >= 0) { + struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN}; + int r; + do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); + } + if (draw) return -1; } - struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN}; - int r; - do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); } int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw, s ? droiddeck_surface_color(s) : NULL, ab->format); if (r < 0) return -1; if (r == 1) return 0; +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + static int explicit_logged; + if (explicit_acquire && !explicit_logged) { + explicit_logged = 1; + droiddeck_log("layer", "probe: SurfaceControl accepted a verified producer acquire fence"); + } +#endif if (!ab->on_layer) { ab->on_layer = 1; g_stat_zero_copy++; +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + if (explicit_acquire) g_stat_producer_fence++; +#endif g_last_zero_copy_ns = now_ns(); } if (s && g_announced != s) { @@ -253,6 +282,12 @@ unsigned ahb_swapchain_stats_take(void) { return n; } +unsigned ahb_swapchain_producer_fence_stats_take(void) { + unsigned n = g_stat_producer_fence; + g_stat_producer_fence = 0; + return n; +} + int ahb_swapchain_advertised(void) { return g_advertised; } uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) { diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h index 9002e6fc0a..95f1cd1418 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h @@ -20,7 +20,9 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_ int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *buffer, struct surface *s, int paced); void ahb_swapchain_surface_gone(struct surface *s); unsigned ahb_swapchain_stats_take(void); +unsigned ahb_swapchain_producer_fence_stats_take(void); int ahb_swapchain_advertised(void); +int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b); uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b); void ahb_swapchain_layer_released(void *token, int release_fd); diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index c9eceed111..112f731f5a 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -23,6 +24,14 @@ #include "linux-dmabuf-v1-server-protocol.h" #include "sc_layer.h" #include "ahb_swapchain.h" +#include "frame_acquire.h" +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE +#include "droiddeck-frame-acquire-v1-server-protocol.h" +#include +#include +#include +#include "frame_worker_peer.h" +#endif #include "display_buffers.h" #include "viewporter-server-protocol.h" #include "droiddeck-desktop-v1-server-protocol.h" @@ -210,6 +219,7 @@ struct surface { struct wl_list link; struct wl_resource *pending_buffer; + struct dd_frame_acquire pending_frame_acquire, frame_acquire; struct wl_listener pending_buffer_destroy; int pending_attach; int pending_src_set, pending_dst_set; @@ -242,6 +252,10 @@ struct surface { enum surface_role role; struct wl_resource *idle_buffer; struct wl_listener idle_buffer_destroy; + struct surface_state *waiting; + struct wl_event_source *waiting_source, *waiting_timer; + int waiting_fd; + int64_t waiting_since_ns; uint32_t *idle_px; int idle_w, idle_h; struct wl_resource *xdg_surface, *xdg_toplevel; @@ -373,6 +387,8 @@ static struct { unsigned copy_scenes; unsigned releases, releases_held; int64_t release_ns, release_max_ns; + unsigned commit_waits, commit_wait_limits; + int64_t commit_wait_ns, commit_wait_max_ns; } g_perf; static void schedule_render(void); @@ -820,6 +836,7 @@ static void unmap_toplevel(struct surface *s) { } static void drop_dmabuf(struct surface *s, int paced) { + dd_frame_acquire_clear(&s->frame_acquire); if (s->dmabuf) { wl_list_remove(&s->dmabuf_destroy.link); if (buffer_shown_elsewhere(s->dmabuf, s)) { @@ -835,17 +852,72 @@ static void drop_dmabuf(struct surface *s, int paced) { static void on_dmabuf_destroyed(struct wl_listener *l, void *data) { struct surface *s = wl_container_of(l, s, dmabuf_destroy); + dd_frame_acquire_clear(&s->frame_acquire); wl_list_remove(&s->dmabuf_destroy.link); s->dmabuf = NULL; } static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) { struct surface *s = wl_container_of(l, s, pending_buffer_destroy); + dd_frame_acquire_clear(&s->pending_frame_acquire); wl_list_remove(&s->pending_buffer_destroy.link); wl_list_init(&s->pending_buffer_destroy.link); s->pending_buffer = NULL; } +struct surface_state { + struct dd_frame_acquire frame_acquire; + struct wl_resource *buffer; + struct wl_listener buffer_destroy; + int attach; + int src_set, dst_set, opaque_set; + float src[4]; + int dst[2], opaque[4]; + struct damage_list damage_buf, damage_local; + struct wl_list frames, feedback; +}; + +static void on_state_buffer_destroyed(struct wl_listener *l, void *data) { + struct surface_state *st = wl_container_of(l, st, buffer_destroy); + dd_frame_acquire_clear(&st->frame_acquire); + wl_list_remove(&st->buffer_destroy.link); + wl_list_init(&st->buffer_destroy.link); + st->buffer = NULL; + st->attach = 0; +} + +static void surface_state_take(struct surface *s, struct surface_state *st) { + st->attach = s->pending_attach; + st->frame_acquire = s->pending_frame_acquire; + s->pending_frame_acquire.fd_plus_one = 0; + st->buffer = s->pending_buffer; + wl_list_init(&st->buffer_destroy.link); + if (st->buffer) { + wl_list_remove(&s->pending_buffer_destroy.link); + wl_list_init(&s->pending_buffer_destroy.link); + st->buffer_destroy.notify = on_state_buffer_destroyed; + wl_resource_add_destroy_listener(st->buffer, &st->buffer_destroy); + } + s->pending_buffer = NULL; + s->pending_attach = 0; + st->src_set = s->pending_src_set; + memcpy(st->src, s->pending_src, sizeof(st->src)); + st->dst_set = s->pending_dst_set; + memcpy(st->dst, s->pending_dst, sizeof(st->dst)); + st->opaque_set = s->pending_opaque_set; + memcpy(st->opaque, s->pending_opaque, sizeof(st->opaque)); + s->pending_src_set = s->pending_dst_set = s->pending_opaque_set = 0; + st->damage_buf = s->pending_damage_buf; + st->damage_local = s->pending_damage_local; + s->pending_damage_buf.n = s->pending_damage_local.n = 0; + wl_list_init(&st->frames); + wl_list_insert_list(&st->frames, &s->pending_frames); + wl_list_init(&s->pending_frames); + wl_list_init(&st->feedback); + wl_list_insert_list(&st->feedback, &s->pending_feedback); + wl_list_init(&s->pending_feedback); +} + static void fire_frames(struct wl_list *frames) { struct wl_resource *cb, *tmp; uint32_t t; @@ -1130,6 +1202,7 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r, if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link); wl_list_init(&s->pending_buffer_destroy.link); s->pending_buffer = buffer; + dd_frame_acquire_clear(&s->pending_frame_acquire); s->pending_attach = 1; if (buffer) { s->pending_buffer_destroy.notify = on_pending_buffer_destroyed; @@ -1363,35 +1436,23 @@ static void surface_drop_idle(struct surface *s) { if (buffer) send_buffer_release(buffer); } -static void surface_commit(struct wl_client *c, struct wl_resource *r) { - struct surface *s = wl_resource_get_user_data(r); +static void surface_state_apply(struct surface *s, struct surface_state *st) { struct surface *child; - if (s->xdg_toplevel && !s->toplevel_committed) { - s->toplevel_committed = 1; - send_toplevel_configure(s); + if (st->src_set) { + s->src_set = st->src[2] > 0; + memcpy(s->src, st->src, sizeof(s->src)); } + if (st->dst_set) { + s->dst_set = st->dst[0] > 0; + memcpy(s->dst, st->dst, sizeof(s->dst)); + } + if (st->opaque_set) memcpy(s->opaque, st->opaque, sizeof(s->opaque)); - if (s->pending_src_set) { - s->src_set = s->pending_src[2] > 0; - memcpy(s->src, s->pending_src, sizeof(s->src)); - s->pending_src_set = 0; - } - if (s->pending_dst_set) { - s->dst_set = s->pending_dst[0] > 0; - memcpy(s->dst, s->pending_dst, sizeof(s->dst)); - s->pending_dst_set = 0; - } - if (s->pending_opaque_set) { - memcpy(s->opaque, s->pending_opaque, sizeof(s->opaque)); - s->pending_opaque_set = 0; - } - - s->damage_buf = s->pending_damage_buf; - s->damage_local = s->pending_damage_local; - s->pending_damage_buf.n = s->pending_damage_local.n = 0; - if (s->pending_attach) { - struct wl_resource *buffer = s->pending_buffer; + s->damage_buf = st->damage_buf; + s->damage_local = st->damage_local; + if (st->attach) { + struct wl_resource *buffer = st->buffer; struct dmabuf_buffer *db = get_dmabuf(buffer); struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL; uint8_t pixel[4]; @@ -1400,15 +1461,14 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { if (!buffer) g_pace.null_attaches++; else if (!db) s->last_dmabuf = NULL; - if (buffer) { - wl_list_remove(&s->pending_buffer_destroy.link); - wl_list_init(&s->pending_buffer_destroy.link); - } - s->pending_buffer = NULL; - s->pending_attach = 0; + wl_list_remove(&st->buffer_destroy.link); + wl_list_init(&st->buffer_destroy.link); + st->buffer = NULL; + st->attach = 0; surface_drop_idle(s); buf_trace_attach(buffer); + dd_frame_acquire_clear(&s->frame_acquire); if (s->role == ROLE_CURSOR) { if (!buffer) { cursor_publish_hidden(); @@ -1420,6 +1480,8 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { if (buffer) surface_hold_idle(s, buffer); } else if (db) { take_dmabuf(s, db, buffer); + s->frame_acquire = st->frame_acquire; + st->frame_acquire.fd_plus_one = 0; } else if (shm) { drop_dmabuf(s, 1); take_shm(s, shm, buffer); @@ -1432,6 +1494,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { if (buffer) send_buffer_release(buffer); } } + dd_frame_acquire_clear(&st->frame_acquire); pending_releases_apply(s); wl_list_for_each(child, &s->children, child_link) { @@ -1442,10 +1505,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { } } - wl_list_insert_list(s->frames.prev, &s->pending_frames); - wl_list_init(&s->pending_frames); - wl_list_insert_list(s->feedback.prev, &s->pending_feedback); - wl_list_init(&s->pending_feedback); + wl_list_insert_list(s->frames.prev, &st->frames); + wl_list_init(&st->frames); + wl_list_insert_list(s->feedback.prev, &st->feedback); + wl_list_init(&st->feedback); constraints_surface_commit(s); droiddeck_color_commit(s->resource); @@ -1455,6 +1518,189 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { } schedule_render(); } + +#define COMMIT_WAIT_LIMIT_MS 1000 + +static struct surface *g_zero_copy_shown, *g_unwaited; + +static int state_unfinished_fd(const struct surface *s, const struct surface_state *st, int *unwaited) { + struct dmabuf_buffer *db = st->attach ? get_dmabuf(st->buffer) : NULL; + int fd = -1; + *unwaited = 0; + for (int i = 0; db && fd < 0 && i < db->n_planes; i++) { + if (db->fd[i] < 0) continue; + struct pollfd p = {.fd = db->fd[i], .events = POLLIN}; + int r; + do { r = poll(&p, 1, 0); } while (r < 0 && errno == EINTR); + if (r == 0) fd = db->fd[i]; + } + if (fd >= 0 && s == g_zero_copy_shown && ahb_swapchain_has_ahb(db)) { + *unwaited = 1; + return -1; + } + return fd; +} + +static void settle_unwaited(void) { + struct surface *s = g_unwaited; + if (!s) return; + g_unwaited = NULL; + struct dmabuf_buffer *db = s->dmabuf_buf; + const int64_t deadline = now_ns() + 100000000LL; + for (int i = 0; db && i < db->n_planes; i++) { + if (db->fd[i] < 0) continue; + struct pollfd p = {.fd = db->fd[i], .events = POLLIN}; + for (;;) { + const int64_t left = deadline - now_ns(); + const int r = poll(&p, 1, left > 0 ? (int)((left + 999999) / 1000000) : 0); + if (r >= 0 || errno != EINTR || left <= 0) break; + } + } +} + +static void surface_state_discard(struct surface_state *st) { + dd_frame_acquire_clear(&st->frame_acquire); + struct wl_resource *cb, *tmp; + wl_list_remove(&st->buffer_destroy.link); + wl_resource_for_each_safe(cb, tmp, &st->frames) wl_resource_destroy(cb); + feedback_discard_all(&st->feedback); + free(st); +} + +static void surface_state_merge(struct surface_state *older, struct surface_state *newer) { + if (older->attach && !newer->attach) { + newer->attach = 1; + newer->buffer = older->buffer; + newer->frame_acquire = older->frame_acquire; + older->frame_acquire.fd_plus_one = 0; + wl_list_remove(&older->buffer_destroy.link); + wl_list_init(&older->buffer_destroy.link); + if (newer->buffer) { + newer->buffer_destroy.notify = on_state_buffer_destroyed; + wl_resource_add_destroy_listener(newer->buffer, &newer->buffer_destroy); + } + wl_list_insert_list(&newer->feedback, &older->feedback); + wl_list_init(&older->feedback); + } else if (older->attach) { + if (older->buffer && older->buffer != newer->buffer) send_buffer_release(older->buffer); + g_pace.replaced += feedback_discard_all(&older->feedback); + } + if (older->src_set && !newer->src_set) { + newer->src_set = 1; + memcpy(newer->src, older->src, sizeof(newer->src)); + } + if (older->dst_set && !newer->dst_set) { + newer->dst_set = 1; + memcpy(newer->dst, older->dst, sizeof(newer->dst)); + } + if (older->opaque_set && !newer->opaque_set) { + newer->opaque_set = 1; + memcpy(newer->opaque, older->opaque, sizeof(newer->opaque)); + } + for (int i = 0; i < older->damage_buf.n; i++) + note_damage(&newer->damage_buf, older->damage_buf.r[i][0], older->damage_buf.r[i][1], + older->damage_buf.r[i][2], older->damage_buf.r[i][3]); + for (int i = 0; i < older->damage_local.n; i++) + note_damage(&newer->damage_local, older->damage_local.r[i][0], older->damage_local.r[i][1], + older->damage_local.r[i][2], older->damage_local.r[i][3]); + wl_list_insert_list(&newer->frames, &older->frames); + wl_list_init(&older->frames); + surface_state_discard(older); +} + +static void surface_wait_stop(struct surface *s) { + if (s->waiting_source) wl_event_source_remove(s->waiting_source); + if (s->waiting_timer) wl_event_source_remove(s->waiting_timer); + if (s->waiting_fd >= 0) close(s->waiting_fd); + s->waiting_source = s->waiting_timer = NULL; + s->waiting_fd = -1; +} + +static void surface_wait_end(struct surface *s, int over_limit) { + struct surface_state *st = s->waiting; + if (!st) return; + surface_wait_stop(s); + s->waiting = NULL; + const int64_t waited = now_ns() - s->waiting_since_ns; + g_perf.commit_waits++; + g_perf.commit_wait_ns += waited; + if (waited > g_perf.commit_wait_max_ns) g_perf.commit_wait_max_ns = waited; + if (over_limit) g_perf.commit_wait_limits++; + if (st->attach && g_unwaited == s) g_unwaited = NULL; + surface_state_apply(s, st); + free(st); +} + +static int on_commit_ready(int fd, uint32_t mask, void *data) { + surface_wait_end(data, 0); + return 0; +} + +static int on_commit_wait_limit(void *data) { + static int said; + if (!said) { + said = 1; + droiddeck_log("compositor", "a client's GPU writes ran past %d ms; its frame is shown as it is", COMMIT_WAIT_LIMIT_MS); + } + surface_wait_end(data, 1); + return 0; +} + +static int surface_wait_start(struct surface *s, int fd, int timeout_ms) { + struct wl_event_loop *loop = wl_display_get_event_loop(g_display); + s->waiting_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0); + if (s->waiting_fd >= 0) { + s->waiting_source = wl_event_loop_add_fd(loop, s->waiting_fd, WL_EVENT_READABLE, on_commit_ready, s); + s->waiting_timer = wl_event_loop_add_timer(loop, on_commit_wait_limit, s); + } + if (!s->waiting_source || !s->waiting_timer || + wl_event_source_timer_update(s->waiting_timer, timeout_ms) != 0) { + surface_wait_stop(s); + return -1; + } + return 0; +} + +static void surface_commit(struct wl_client *c, struct wl_resource *r) { + struct surface *s = wl_resource_get_user_data(r); + + if (s->xdg_toplevel && !s->toplevel_committed) { + s->toplevel_committed = 1; + send_toplevel_configure(s); + } + struct surface_state *st = calloc(1, sizeof(*st)); + if (!st) { + struct surface_state now; + surface_state_take(s, &now); + surface_state_apply(s, &now); + return; + } + surface_state_take(s, st); + const int was_waiting = s->waiting != NULL; + if (was_waiting) { + surface_wait_stop(s); + surface_state_merge(s->waiting, st); + s->waiting = NULL; + } + int unwaited; + const int fd = state_unfinished_fd(s, st, &unwaited); + if (!was_waiting) s->waiting_since_ns = now_ns(); + const int64_t left_ms = COMMIT_WAIT_LIMIT_MS - (now_ns() - s->waiting_since_ns) / 1000000; + if (fd >= 0 && left_ms > 0 && surface_wait_start(s, fd, (int)left_ms) == 0) { + s->waiting = st; + return; + } + const int attaches = st->attach; + if (was_waiting) { + s->waiting = st; + surface_wait_end(s, fd >= 0 && left_ms <= 0); + } else { + surface_state_apply(s, st); + free(st); + } + if (unwaited) g_unwaited = s; + else if (attaches && g_unwaited == s) g_unwaited = NULL; +} static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {} static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {} static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r, @@ -1478,6 +1724,210 @@ static const struct wl_surface_interface surface_impl = { .offset = surface_offset, }; +int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b) { + return s && s->dmabuf && s->dmabuf_buf == b ? dd_frame_acquire_dup(&s->frame_acquire) : -1; +} + +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE +// Private signed fixture: only the app-owned worker decision may issue a grant. +static pthread_mutex_t frame_worker_lock = PTHREAD_MUTEX_INITIALIZER; +static char frame_worker_file[PATH_MAX]; +static struct dd_worker_grant frame_worker_grant; +static int frame_worker_pidfd = -1; +static bool frame_worker_map_reported; + +static enum dd_worker_stat_result frame_worker_starttime(pid_t pid, uint64_t *out) { + char proc[64], line[4096]; + snprintf(proc, sizeof(proc), "/proc/%d/stat", pid); + FILE *f = fopen(proc, "re"); + if (!f) return dd_worker_open_failure(errno); + // Proc writes one bounded line; truncation is a read failure, not invisibility. + bool read = fgets(line, sizeof(line), f) != NULL && strchr(line, '\n') != NULL; + fclose(f); + return read ? dd_worker_parse_start(line, out) : DD_WORKER_STAT_READ; +} + +void droiddeck_frame_worker_revoke(int owner, int pid) { + pthread_mutex_lock(&frame_worker_lock); + if (frame_worker_grant.owner == (uint32_t)owner && + (!pid || frame_worker_grant.pid == (uint32_t)pid)) { + if (frame_worker_pidfd >= 0) close(frame_worker_pidfd); + frame_worker_pidfd = -1; + frame_worker_grant = (struct dd_worker_grant){0}; + } + pthread_mutex_unlock(&frame_worker_lock); +} + +int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path, + uint64_t expected_dev, uint64_t expected_ino, uint64_t receipt) { + struct stat st; + if (owner <= 0 || pid <= 1 || !receipt || !path || + strlen(path) >= sizeof(frame_worker_file) || lstat(path, &st) < 0 || !S_ISREG(st.st_mode) || + (uint64_t)st.st_dev != expected_dev || (uint64_t)st.st_ino != expected_ino || + st.st_uid != getuid()) { + droiddeck_log("probe", "worker_admission=NATIVE_FILE"); + return 0; + } + int pidfd = syscall(__NR_pidfd_open, pid, 0); + if (pidfd < 0) { + droiddeck_log("probe", "worker_admission=NATIVE_PIDFD"); + return 0; // No fallback to a recyclable PID. + } + struct pollfd alive = {.fd = pidfd, .events = POLLIN}; + uint64_t raw_start = 0; + enum dd_worker_stat_result stat = frame_worker_starttime(pid, &raw_start); + switch (stat) { + case DD_WORKER_STAT_OK: + if (raw_start != receipt) droiddeck_log("probe", "worker_admission=NATIVE_STAT_MISMATCH"); + break; + case DD_WORKER_STAT_DENIED: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_DENIED"); break; + case DD_WORKER_STAT_HIDDEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_HIDDEN"); break; + case DD_WORKER_STAT_OPEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_OTHER"); break; + case DD_WORKER_STAT_READ: droiddeck_log("probe", "worker_admission=NATIVE_STAT_READ"); break; + case DD_WORKER_STAT_PARSE: droiddeck_log("probe", "worker_admission=NATIVE_STAT_PARSE"); break; + case DD_WORKER_STAT_ZERO: droiddeck_log("probe", "worker_admission=NATIVE_STAT_ZERO"); break; + } + if (!dd_worker_receipt_allows_reserve(stat, raw_start, receipt)) { close(pidfd); return 0; } + if (poll(&alive, 1, 0) != 0) { + droiddeck_log("probe", "worker_admission=NATIVE_PIDFD_NOT_LIVE"); + close(pidfd); + return 0; + } + pthread_mutex_lock(&frame_worker_lock); + if (frame_worker_pidfd < 0) { + strcpy(frame_worker_file, path); + frame_worker_grant = (struct dd_worker_grant){ + .owner = owner, .uid = getuid(), .pid = pid, .start_ticks = receipt, .expires = expires, + .dev_major = major(st.st_dev), .dev_minor = minor(st.st_dev), .ino = st.st_ino, + .canonical_file = frame_worker_file, .app_launch_verified = true, .final_go = true, + }; + frame_worker_map_reported = false; + frame_worker_pidfd = pidfd; + pidfd = -1; + } + pthread_mutex_unlock(&frame_worker_lock); + if (pidfd >= 0) { + droiddeck_log("probe", "worker_admission=NATIVE_ALREADY_RESERVED"); + close(pidfd); + return 0; + } + droiddeck_log("probe", "frame acquire reserved one app-verified worker"); + return 1; +} + +static bool frame_worker_verified_exec_locked(const struct dd_worker_grant *g, uint64_t now) { + char proc[64], line[PATH_MAX + 128]; + const char *failure = "worker_admission=MAP_STARTTIME"; + uint64_t raw_start = 0; + if (frame_worker_starttime(g->pid, &raw_start) != DD_WORKER_STAT_OK || raw_start != g->start_ticks) + goto reject; + snprintf(proc, sizeof(proc), "/proc/%u/maps", g->pid); + FILE *f = fopen(proc, "re"); + failure = "worker_admission=MAP_OPEN"; + if (!f) goto reject; + bool matched = false; + size_t budget = 2 * 1024 * 1024; + while (budget && fgets(line, sizeof(line), f)) { + size_t n = strlen(line); + if (!n || line[n - 1] != '\n' || n > budget) break; + budget -= n; + if (dd_worker_grant_matches(g, g->owner, g->uid, g->pid, raw_start, now, line)) { + matched = true; + break; + } + } + fclose(f); + if (matched) return true; + failure = "worker_admission=MAP_IDENTITY"; +reject: + if (!frame_worker_map_reported) { + frame_worker_map_reported = true; + droiddeck_log("probe", "%s", failure); + } + return false; +} + +static int frame_acquire_peer_allowed(const struct wl_client *client, bool verify_exec, bool bind) { + pid_t pid = 0; + uid_t uid = (uid_t)-1; + wl_client_get_credentials(client, &pid, &uid, NULL); + struct timespec t; + if (clock_gettime(CLOCK_BOOTTIME, &t) < 0) return 0; + uint64_t now = (uint64_t)t.tv_sec * 1000 + (uint64_t)t.tv_nsec / 1000000; + pthread_mutex_lock(&frame_worker_lock); + const struct dd_worker_grant *g = &frame_worker_grant; + struct pollfd alive = {.fd = frame_worker_pidfd, .events = POLLIN}; + bool allowed = frame_worker_pidfd >= 0 && uid == getuid() && pid > 1 && + g->pid == (uint32_t)pid && g->uid == uid && now < g->expires && + poll(&alive, 1, 0) == 0 && (!verify_exec || + (frame_worker_verified_exec_locked(g, now) && poll(&alive, 1, 0) == 0)); + // The short startup authorization may not be renewed by registry enumeration. + // Only an authenticated bind activates the grant for the lifetime of this live, + // unreplaced worker; session teardown revokes it independently of process exit. + if (allowed && bind) frame_worker_grant.expires = UINT64_MAX; + pthread_mutex_unlock(&frame_worker_lock); + return allowed; +} + +static bool frame_acquire_global_filter(const struct wl_client *client, const struct wl_global *global, void *data) { + return wl_global_get_interface(global) != &droiddeck_frame_acquire_v1_interface || + frame_acquire_peer_allowed(client, true, false); +} + +static void frame_acquire_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void frame_acquire_set(struct wl_client *client, struct wl_resource *resource, + struct wl_resource *surface, struct wl_resource *buffer, int32_t fd) { + if (!frame_acquire_peer_allowed(client, false, false)) { + close(fd); + wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER, + "paired capture peer is not authorized"); + return; + } + struct surface *s = NULL; + if (surface && buffer && wl_resource_get_client(surface) == client && + wl_resource_get_client(buffer) == client && + wl_resource_instance_of(surface, &wl_surface_interface, &surface_impl) && + get_dmabuf(buffer)) + s = wl_resource_get_user_data(surface); + if (!s || !s->pending_attach || s->pending_buffer != buffer) { + close(fd); + wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT, + "fence does not match pending DMA-BUF attachment"); + return; + } + enum dd_frame_acquire_result result = dd_frame_acquire_set(&s->pending_frame_acquire, fd); + if (result == DD_ACQUIRE_DUPLICATE) + wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE, + "pending attachment already has a fence"); + else if (result == DD_ACQUIRE_INVALID) + wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE, + "expected an already signaled Linux sync_file"); +} + +static const struct droiddeck_frame_acquire_v1_interface frame_acquire_impl = { + .destroy = frame_acquire_destroy, + .set_acquire_fence = frame_acquire_set, +}; + +static void bind_frame_acquire(struct wl_client *client, void *data, uint32_t version, uint32_t id) { + if (!frame_acquire_peer_allowed(client, true, true)) { + wl_client_post_implementation_error(client, "paired capture peer is not authorized"); + return; + } + struct wl_resource *resource = + wl_resource_create(client, &droiddeck_frame_acquire_v1_interface, 1, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &frame_acquire_impl, NULL, NULL); + droiddeck_log("probe", "frame acquire bound to app-issued worker and exact executable map"); +} +#endif + static void detach_from_parent(struct surface *s) { if (!s->parent) return; wl_list_remove(&s->child_link); @@ -1487,6 +1937,7 @@ static void detach_from_parent(struct surface *s) { static void surface_resource_destroy(struct wl_resource *r) { struct surface *s = wl_resource_get_user_data(r); + dd_frame_acquire_clear(&s->pending_frame_acquire); struct surface *child, *tmp; struct wl_resource *cb, *cbtmp; @@ -1516,6 +1967,13 @@ static void surface_resource_destroy(struct wl_resource *r) { child->parent = NULL; } if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link); + if (s->waiting) { + surface_wait_stop(s); + surface_state_discard(s->waiting); + s->waiting = NULL; + } + if (g_zero_copy_shown == s) g_zero_copy_shown = NULL; + if (g_unwaited == s) g_unwaited = NULL; pending_releases_forget_surface(s); drop_dmabuf(s, 0); ahb_swapchain_surface_gone(s); @@ -1579,6 +2037,7 @@ static void compositor_create_surface(struct wl_client *c, struct wl_resource *r wl_list_init(&s->child_link); wl_list_init(&s->toplevel_link); wl_list_init(&s->pending_buffer_destroy.link); + s->waiting_fd = -1; wl_list_init(&s->idle_buffer_destroy.link); wl_list_insert(&g_surfaces, &s->link); wl_resource_set_implementation(s->resource, &surface_impl, s, surface_resource_destroy); @@ -2043,6 +2502,69 @@ static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t struct draw_list { struct vkp_draw *d; int n, cap; }; +#define ZERO_COPY_FALLBACK_SIGNATURES 32u +enum zero_copy_fallback_reason { + ZERO_COPY_NO_SURFACE_BUFFER = 1, + ZERO_COPY_NO_GRALLOC_AHB = 2, + ZERO_COPY_AHB_PRESENT_FAILED = 3 +}; +struct zero_copy_fallback_signature { + uint32_t reason, format, stride, offset; + int width, height; + uint64_t modifier; +}; +static struct zero_copy_fallback_signature g_zero_copy_fallbacks[ZERO_COPY_FALLBACK_SIGNATURES]; +static uint32_t g_zero_copy_fallback_count; +static int g_zero_copy_fallback_limit_logged; + +static int zero_copy_fallback_should_log(const struct dmabuf_buffer *b, uint32_t reason) { + const struct zero_copy_fallback_signature key = { + .reason = reason, .format = b ? b->format : 0, + .stride = b && b->n_planes ? b->stride[0] : 0, + .offset = b && b->n_planes ? b->offset[0] : 0, + .width = b ? b->width : 0, .height = b ? b->height : 0, + .modifier = b ? b->modifier : 0}; + for (uint32_t i = 0; i < g_zero_copy_fallback_count; i++) { + const struct zero_copy_fallback_signature *seen = &g_zero_copy_fallbacks[i]; + if (seen->reason == key.reason && seen->format == key.format && seen->stride == key.stride && + seen->offset == key.offset && seen->width == key.width && seen->height == key.height && + seen->modifier == key.modifier) + return 0; + } + if (g_zero_copy_fallback_count >= ZERO_COPY_FALLBACK_SIGNATURES) { + if (!g_zero_copy_fallback_limit_logged) { + g_zero_copy_fallback_limit_logged = 1; + droiddeck_log("layer", "zero-copy: further fallback diagnostics suppressed after %u distinct buffer signatures", + ZERO_COPY_FALLBACK_SIGNATURES); + } + return 0; + } + g_zero_copy_fallbacks[g_zero_copy_fallback_count++] = key; + return 1; +} + +static void note_zero_copy_fallback(struct surface *s, const struct dmabuf_buffer *b, uint32_t reason, + int scene_w, int scene_h, int present_result) { + if (!zero_copy_fallback_should_log(b, reason)) return; + char name[160] = "unknown surface"; + if (s) describe(s, name, sizeof(name)); + if (reason == ZERO_COPY_NO_SURFACE_BUFFER) { + droiddeck_log("layer", "zero-copy: layer candidate %s has no associated Wayland surface buffer; using the layer-copy path", + name); + } else { + droiddeck_log("layer", "zero-copy: %s buffer %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx %s; " + "scene %dx%d will use the layer-copy path (direct-present result %d)", + name, b->format & 0xff, (b->format >> 8) & 0xff, (b->format >> 16) & 0xff, + (b->format >> 24) & 0xff, b->width, b->height, + b->n_planes ? b->stride[0] : 0, b->n_planes ? b->offset[0] : 0, + (unsigned long long)b->modifier, + reason == ZERO_COPY_NO_GRALLOC_AHB + ? "has no registered gralloc AHardwareBuffer" + : "has a registered gralloc AHardwareBuffer but direct presentation failed", + scene_w, scene_h, present_result); + } +} + static int add_cursor(struct draw_list *dl, int scene_w); static struct vkp_image *surface_image(struct surface *s) { @@ -2162,17 +2684,53 @@ static int black_fill_below(const struct draw_list *dl, int n) { return 1; } +#define LAYER_CANDIDATE_DIAGNOSTICS 32u +static unsigned g_layer_candidate_diag_count; +static int g_layer_candidate_diag_limit; + +static void note_layer_candidate_skip(const struct vkp_draw *d, int index, int reason, + int scene_w, int scene_h) { + static int seen[LAYER_CANDIDATE_DIAGNOSTICS][8]; + const int key[8] = {index, reason, scene_w, scene_h, d->dx, d->dy, d->dw, d->dh}; + for (unsigned i = 0; i < g_layer_candidate_diag_count; i++) + if (!memcmp(seen[i], key, sizeof(key))) return; + if (g_layer_candidate_diag_count >= LAYER_CANDIDATE_DIAGNOSTICS) { + if (!g_layer_candidate_diag_limit++) droiddeck_log("layer", "zero-copy: further candidate-rejection details suppressed after %u signatures", + LAYER_CANDIDATE_DIAGNOSTICS); + return; + } + memcpy(seen[g_layer_candidate_diag_count++], key, sizeof(key)); + const char *why = reason == 1 ? "translucent draw" : + reason == 2 ? "image is not DMA-BUF" : + reason == 3 ? "source rectangle is outside/invalid" : + reason == 4 ? "draw rectangle is outside scene or invalid" : + "not fullscreen and no black backing below"; + droiddeck_log("layer", "zero-copy: candidate draw %d rejected: %s; scene %dx%d, dst %dx%d at %d,%d, src %.2f,%.2f %.2fx%.2f, image %dx%d", + index, why, scene_w, scene_h, d->dw, d->dh, d->dx, d->dy, + d->sx, d->sy, d->sw, d->sh, vkp_image_width(d->img), vkp_image_height(d->img)); +} + static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) { for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) { const struct vkp_draw *d = &dl->d[i]; - if (d->blend) continue; - if (!vkp_image_is_dmabuf(d->img)) continue; + if (d->blend) { note_layer_candidate_skip(d, i, 1, scene_w, scene_h); continue; } + if (!vkp_image_is_dmabuf(d->img)) { note_layer_candidate_skip(d, i, 2, scene_w, scene_h); continue; } if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f || d->sx + d->sw >= vkp_image_width(d->img) + 1.0f || - d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue; + d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) { + note_layer_candidate_skip(d, i, 3, scene_w, scene_h); + continue; + } if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i; if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w || - d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue; + d->dy + d->dh > scene_h) { + note_layer_candidate_skip(d, i, 4, scene_w, scene_h); + continue; + } + if (!black_fill_below(dl, i)) { + note_layer_candidate_skip(d, i, 5, scene_w, scene_h); + continue; + } return i; } return -1; @@ -2193,6 +2751,56 @@ static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : ""); } +static struct surface *surface_for_image(const struct vkp_image *img); + +static void note_layer_candidate_rejected(const struct draw_list *dl, int scene_w, int scene_h) { + static int seen[32][14]; + static unsigned seen_count; + static int limit_logged; + static time_t window_start; + struct timespec now_ts; + const struct vkp_draw *a = dl->n > 0 ? &dl->d[dl->n - 1] : NULL; + const struct vkp_draw *b = dl->n > 1 ? &dl->d[dl->n - 2] : NULL; + struct surface *sa = a ? surface_for_image(a->img) : NULL; + struct surface *sb = b ? surface_for_image(b->img) : NULL; + const int signature[14] = { + dl->n, scene_w, scene_h, + a ? a->dw : 0, a ? a->dh : 0, + a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0, + a ? vkp_image_is_dmabuf(a->img) : 0, a ? a->blend : 0, sa && sa->dmabuf_buf ? 1 : 0, + b ? b->dw : 0, b ? b->dh : 0, b ? vkp_image_is_dmabuf(b->img) : 0, sb && sb->dmabuf_buf ? 1 : 0 + }; + clock_gettime(CLOCK_MONOTONIC, &now_ts); + if (!window_start || now_ts.tv_sec - window_start >= 30) { + seen_count = 0; + limit_logged = 0; + window_start = now_ts.tv_sec; + } + for (unsigned i = 0; i < seen_count; i++) + if (!memcmp(signature, seen[i], sizeof(signature))) return; + if (seen_count >= 32) { + if (!limit_logged++) droiddeck_log("layer", "zero-copy: further fullscreen-candidate rejection details suppressed after 32 signatures in 30 seconds"); + return; + } + memcpy(seen[seen_count++], signature, sizeof(signature)); + char below[48]; + if (b) + snprintf(below, sizeof(below), "%s %dx%d", + vkp_image_is_dmabuf(b->img) ? "DMA-BUF" : "non-DMA-BUF", b->dw, b->dh); + else + snprintf(below, sizeof(below), "none"); + droiddeck_log("layer", "zero-copy: no eligible fullscreen DMA-BUF layer candidate: scene %dx%d, %d draws; " + "top draw %dx%d at %d,%d image %dx%d %s%s surface=%s dmabuf=%s; " + "draw below %s", + scene_w, scene_h, dl->n, a ? a->dw : 0, a ? a->dh : 0, a ? a->dx : 0, a ? a->dy : 0, + a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0, + a && vkp_image_is_dmabuf(a->img) ? "DMA-BUF" : "non-DMA-BUF", + a && a->blend ? " blended" : "", + sa ? "associated" : "unassociated", + sa && sa->dmabuf_buf ? "yes" : "no", + below); +} + static struct surface *surface_for_image(const struct vkp_image *img) { struct surface *s; wl_list_for_each(s, &g_surfaces, link) @@ -2201,16 +2809,56 @@ static struct surface *surface_for_image(const struct vkp_image *img) { } static struct surface *ahb_layer_only_candidate(int scene_w, int scene_h) { + static struct { + const struct surface *surface; + int reason, scene_w, scene_h, w, h, buf_w, buf_h, x, y, src_set, dst_set, children; + } seen[32]; + static unsigned seen_count; + static int limit_logged; struct surface *s; - int w, h; + int w = 0, h = 0, reason = 0; if (wl_list_empty(&g_toplevels)) return NULL; s = wl_container_of(g_toplevels.prev, s, toplevel_link); - if (!s->dmabuf_buf || s->dmabuf_buf->img || !ahb_swapchain_has_ahb(s->dmabuf_buf)) return NULL; - if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) return NULL; - if (!wl_list_empty(&s->children)) return NULL; - if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) return NULL; + if (!s->dmabuf_buf) reason = 1; + else if (s->dmabuf_buf->img) reason = 2; + else if (!ahb_swapchain_has_ahb(s->dmabuf_buf)) reason = 3; + else if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) reason = 4; + else if (!wl_list_empty(&s->children)) reason = 5; + else if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) reason = 6; surface_size(s, &w, &h); - if (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h) return NULL; + if (!reason && (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h)) reason = 7; + if (reason) { + int found = 0; + for (unsigned i = 0; i < seen_count; i++) { + if (seen[i].surface == s && seen[i].reason == reason && seen[i].scene_w == scene_w && + seen[i].scene_h == scene_h && seen[i].w == w && seen[i].h == h && + seen[i].buf_w == s->buf_w && seen[i].buf_h == s->buf_h && seen[i].x == s->x && + seen[i].y == s->y && seen[i].src_set == s->src_set && seen[i].dst_set == s->dst_set && + seen[i].children == !wl_list_empty(&s->children)) { found = 1; break; } + } + if (!found && seen_count < 32) { + seen[seen_count].surface = s; seen[seen_count].reason = reason; + seen[seen_count].scene_w = scene_w; seen[seen_count].scene_h = scene_h; + seen[seen_count].w = w; seen[seen_count].h = h; seen[seen_count].buf_w = s->buf_w; seen[seen_count].buf_h = s->buf_h; + seen[seen_count].x = s->x; seen[seen_count].y = s->y; seen[seen_count].src_set = s->src_set; + seen[seen_count].dst_set = s->dst_set; seen[seen_count].children = !wl_list_empty(&s->children); + seen_count++; + const char *why = reason == 1 ? "no DMA-BUF buffer" : + reason == 2 ? "buffer is already importable by Vulkan" : + reason == 3 ? "no registered gralloc AHardwareBuffer" : + reason == 4 ? "surface is positioned/cropped/scaled" : + reason == 5 ? "surface has child surfaces" : + reason == 6 ? "hidden shell surface" : "surface or buffer dimensions differ from scene"; + char name[160]; describe(s, name, sizeof(name)); + droiddeck_log("layer", "zero-copy: AHardwareBuffer-only candidate rejected: %s; %s, scene %dx%d, surface %dx%d at %d,%d, buffer %dx%d, crop=%d destination=%d children=%d", + why, name, scene_w, scene_h, w, h, s->x, s->y, s->buf_w, s->buf_h, + s->src_set, s->dst_set, !wl_list_empty(&s->children)); + } else if (!found && !limit_logged) { + limit_logged = 1; + droiddeck_log("layer", "zero-copy: further AHardwareBuffer-only candidate diagnostics suppressed after 32 signatures"); + } + return NULL; + } return s; } @@ -2502,7 +3150,13 @@ static int64_t scene_next_due(int64_t now, int64_t due, int limit) { static void render_scene(void) { g_scene_due_ns = scene_next_due(now_ns(), g_scene_due_ns, g_fps_limit); - if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; } + if (atomic_load(&g_stream_on)) { + g_dirty_since_ns = 0; + g_zero_copy_shown = NULL; + settle_unwaited(); + render_stream(); + return; + } struct draw_list dl = {0}; struct surface *s; int w, h; @@ -2576,6 +3230,8 @@ static void render_scene(void) { } else { cursor_hdr_said = 0; } + g_zero_copy_shown = NULL; + if (hdr_route == 1 || hdr_route == 2) settle_unwaited(); if (hdr_route == 1) { static int fell_back; vkp_apply_window_request(); @@ -2609,6 +3265,7 @@ static void render_scene(void) { } if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on && !ahb_only) { + settle_unwaited(); rendered = vkp_render(w, h, dl.d, dl.n) == 0; } else if (hdr_route == 0 || hdr_route == 3) { const int pass_on = fx_on || framegen; @@ -2644,7 +3301,10 @@ static void render_scene(void) { struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL; const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL; if (li < 0) ls = layer_only; - if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on); + if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) { + if (!cursor_on && !bfi) note_layer_candidate_rejected(&dl, w, h); + note_copy_scene(&dl, w, h, cursor_on); + } if (cardboard) ls = NULL; if (cursor_on) ls = NULL; if (bfi) ls = NULL; @@ -2658,6 +3318,7 @@ static void render_scene(void) { vkp_apply_window_request(); int r = -1; const int fg_pass = framegen && fx_on && li >= 0; + if (framegen && li >= 0) settle_unwaited(); const int generated = (framegen && li >= 0) ? sc_layer_present_generated(&dl.d[li], 1, NULL, w, h, fg_pass, ls ? droiddeck_surface_color(ls) : NULL) : 0; @@ -2671,16 +3332,34 @@ static void render_scene(void) { r = generated >= 0 ? 0 : -1; else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf)) r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld); - if (!fg_pass && generated >= 0 && r != 0 && li >= 0) - r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h) - : sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL); + if (!fg_pass && generated >= 0 && !fx_on && !framegen && r != 0) { + if (!ls || !ls->dmabuf_buf) + note_zero_copy_fallback(ls, NULL, ZERO_COPY_NO_SURFACE_BUFFER, w, h, r); + else if (!ahb_swapchain_has_ahb(ls->dmabuf_buf)) + note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_NO_GRALLOC_AHB, w, h, r); + else + note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_AHB_PRESENT_FAILED, w, h, r); + } + if (r == 0 && !fg_pass) g_zero_copy_shown = ls; + else settle_unwaited(); + int ov = 0, ov_done = 0; + if (!fg_pass && generated >= 0 && r != 0 && li >= 0) { + if (fx_on) { + r = sc_layer_present_pass(&dl.d[li], 1, w, h); + } else { + r = sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL, + over == 1 ? &dl.d[li + 1] : NULL, &ov); + ov_done = 1; + } + } if (r == 0) { if (ls) ls->drawn = 1; - int go[8], ov = 0; - if (over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go)) + int go[8]; + if (!ov_done && over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go)) ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1; if (ov <= 0) sc_layer_hide_overlay(); if (ov < 0) { + settle_unwaited(); sc_layer_hide(); rendered = vkp_render(w, h, dl.d, dl.n) == 0; copy = 1; @@ -2690,12 +3369,14 @@ static void render_scene(void) { g_scene_queues = sc_layer_queues(); } } else { + settle_unwaited(); sc_layer_hide(); rendered = vkp_render(w, h, dl.d, dl.n) == 0; copy = 1; hdr_copy = "its display layer was unavailable this frame"; } } else { + settle_unwaited(); sc_layer_hide(); rendered = vkp_render(w, h, dl.d, dl.n) == 0; copy = 1; @@ -4131,11 +4812,15 @@ static void output_resized(void) { wl_display_flush_clients(g_display); } -static int on_input_readable(int fd, uint32_t mask, void *data) { +static void dispatch_input(int fd, int remaining) { struct input_msg m; int vsync = 0; int64_t vsync_ns = 0; - while (read(fd, &m, sizeof(m)) == (ssize_t)sizeof(m)) { + while (remaining != 0) { + ssize_t n = read(fd, &m, sizeof(m)); + if (n < 0 && errno == EINTR) continue; + if (n != (ssize_t)sizeof(m)) break; + if (remaining > 0) --remaining; switch (m.type) { case 1: deliver_key(&m); break; case 2: pointer_event(m.p1, m.p2, 0, 0); break; @@ -4177,9 +4862,27 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { wl_display_flush_clients(g_display); } if (vsync) on_vsync(vsync_ns); +} + +static int on_input_readable(int fd, uint32_t mask, void *data) { + dispatch_input(fd, -1); return 0; } +void droiddeck_dispatch_pending_input(void) { + int fd = g_input_pipe[0]; + if (fd < 0) return; + + int bytes; + int result; + do { + result = ioctl(fd, FIONREAD, &bytes); + } while (result < 0 && errno == EINTR); + if (result == 0 && bytes >= (int)sizeof(struct input_msg)) { + dispatch_input(fd, bytes / (int)sizeof(struct input_msg)); + } +} + void droiddeck_wayland_set_scale_mode(int mode, int alignment) { if (g_input_pipe[1] < 0) { vk_present_set_scale_mode(mode, alignment); @@ -4316,6 +5019,11 @@ void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y) void droiddeck_inject_key(uint32_t evdev, int pressed) { key_event(evdev, pressed); } +int droiddeck_key_is_down(uint32_t evdev) { + return evdev < sizeof(g_keys_down) * 8 && + (g_keys_down[evdev >> 3] & (1u << (evdev & 7))) != 0; +} + static struct wl_event_source *g_stats_timer; volatile unsigned g_zero_copy_last; @@ -4325,6 +5033,7 @@ static int on_stats_timer(void *data) { struct surface *s; wl_list_for_each(s, &g_toplevels, toplevel_link) windows++; unsigned zero_copy = ahb_swapchain_stats_take(); + unsigned verified = ahb_swapchain_producer_fence_stats_take(); unsigned layer_frames = sc_layer_frames_take(); g_zero_copy_last = zero_copy; unsigned generated = vkp_framegen_stats_take(); @@ -4333,7 +5042,8 @@ static int on_stats_timer(void *data) { int off = 0; if (g_zero_copy || zero_copy) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u zero-copy frames", zero_copy); if (layer_frames) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u layer frames", layer_frames); - if (generated) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated); + if (generated) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated); + if (verified) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u verified acquire frames", verified); droiddeck_log("stats", "last 10 s: %u frames on screen (%.1f fps) | %u GPU frames from games | %u window redraws | %d windows open%s", g_stat_frames + generated, (g_stat_frames + generated) / 10.0, g_stat_dmabuf, g_stat_shm, windows, extra); } @@ -4344,11 +5054,12 @@ static int on_stats_timer(void *data) { unsigned aimed_next, aimed_later, aimed_even; sc_layer_aim_take(&aimed_next, &aimed_later, &aimed_even); #define PERF_MS(sum, n) ((n) ? (double)(sum) / 1e6 / (double)(n) : 0.0) - if (g_perf.scenes || vp.presents || g_perf.releases || drops) + if (g_perf.scenes || vp.presents || g_perf.releases || drops || g_perf.commit_waits) droiddeck_log("perf", "last 10 s: %u ticks, %u scenes, %u on screen (copy %u, zero-copy %u, layer copy %u) | " "render_scene %.2f/%.2f ms | base %u black kept, %u presented | acquire %.2f/%.2f ms | " "present %.2f/%.2f ms (%u) | fence wait %.2f/%.2f ms (%u, %u GPU release waits) | " - "release %.2f/%.2f ms (%u, %u held) | %u pool drops | layer frames timed for the next refresh %u, " + "release %.2f/%.2f ms (%u, %u held) | commits held for client writes %.2f/%.2f ms (%u, %u past the limit) | " + "%u pool drops | layer frames timed for the next refresh %u, " "the one after %u, held to an even step %u", g_perf.ticks, g_perf.scenes, g_stat_frames, g_perf.copy_scenes, zero_copy, layer_frames, PERF_MS(g_perf.scene_ns, g_perf.scenes), (double)g_perf.scene_max_ns / 1e6, @@ -4357,7 +5068,9 @@ static int on_stats_timer(void *data) { PERF_MS(vp.present_ns, vp.presents), (double)vp.present_max_ns / 1e6, vp.presents, PERF_MS(vp.wait_ns, vp.waits), (double)vp.wait_max_ns / 1e6, vp.waits, vp.gpu_release_waits, PERF_MS(g_perf.release_ns, g_perf.releases), (double)g_perf.release_max_ns / 1e6, - g_perf.releases, g_perf.releases_held, drops, aimed_next, aimed_later, aimed_even); + g_perf.releases, g_perf.releases_held, + PERF_MS(g_perf.commit_wait_ns, g_perf.commit_waits), (double)g_perf.commit_wait_max_ns / 1e6, + g_perf.commit_waits, g_perf.commit_wait_limits, drops, aimed_next, aimed_later, aimed_even); #undef PERF_MS memset(&g_perf, 0, sizeof(g_perf)); } @@ -4531,6 +5244,12 @@ int droiddeck_wayland_run(void) { wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager); droiddeck_ext_init(display); ahb_swapchain_init(display); +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + if (ahb_swapchain_advertised()) { + wl_display_set_global_filter(display, frame_acquire_global_filter, NULL); + wl_global_create(display, &droiddeck_frame_acquire_v1_interface, 1, NULL, bind_frame_acquire); + } +#endif display_buffers_init(display); diff --git a/app/src/main/cpp/waylandcomp/src/display_buffers.c b/app/src/main/cpp/waylandcomp/src/display_buffers.c index 99f6993a56..f6ee1eb0d3 100644 --- a/app/src/main/cpp/waylandcomp/src/display_buffers.c +++ b/app/src/main/cpp/waylandcomp/src/display_buffers.c @@ -62,8 +62,40 @@ struct entry { static struct wl_list g_entries; static struct wl_event_loop *g_loop; static uint64_t g_next_id = 1; -static int g_refused_logged; static int g_ubwc_promised; + +#define DISPLAY_BUFFER_MISMATCH_SIGNATURES 64u +struct display_buffer_mismatch_signature { + uint32_t kind, format, stride, offset; + int width, height; + uint64_t modifier; +}; +static struct display_buffer_mismatch_signature g_mismatch_signatures[DISPLAY_BUFFER_MISMATCH_SIGNATURES]; +static uint32_t g_mismatch_signature_count; +static int g_mismatch_limit_logged; + +static int mismatch_should_log(const struct dmabuf_buffer *b, uint32_t kind) { + const struct display_buffer_mismatch_signature key = { + .kind = kind, .format = b->format, .stride = b->stride[0], .offset = b->offset[0], + .width = b->width, .height = b->height, .modifier = b->modifier}; + for (uint32_t i = 0; i < g_mismatch_signature_count; i++) { + const struct display_buffer_mismatch_signature *seen = &g_mismatch_signatures[i]; + if (seen->kind == key.kind && seen->format == key.format && seen->stride == key.stride && + seen->offset == key.offset && seen->width == key.width && seen->height == key.height && + seen->modifier == key.modifier) + return 0; + } + if (g_mismatch_signature_count >= DISPLAY_BUFFER_MISMATCH_SIGNATURES) { + if (!g_mismatch_limit_logged) { + g_mismatch_limit_logged = 1; + droiddeck_log("layer", "display buffers: further mismatch diagnostics suppressed after %u distinct buffer signatures", + DISPLAY_BUFFER_MISMATCH_SIGNATURES); + } + return 0; + } + g_mismatch_signatures[g_mismatch_signature_count++] = key; + return 1; +} static int g_ubwc_probed[2]; static uint32_t ahb_format_of(uint32_t drm, uint64_t modifier) { @@ -238,16 +270,51 @@ static void handle_alloc(struct peer *p, const struct display_buffers_request *q } else { if (ahb) AHardwareBuffer_release(ahb); fd = -1; - if (sized && wanted && (compressed || !g_refused_logged)) { - g_refused_logged = 1; - droiddeck_log(compressed ? "error" : "layer", "display buffers: no gralloc buffer matches pid %d's %ux%u " - "%c%c%c%c %s layout (stride %u bytes, pixels at %u, %llu bytes; gralloc's layout has pixels at " - "%llu, %llu bytes): %s", (int)p->pid, q->width, q->height, - q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff, - compressed ? "UBWC" : "linear", q->stride, q->offset, (unsigned long long)q->size, - (unsigned long long)(compressed ? ubwc_meta_size(q->width, q->height) : 0), - (unsigned long long)(compressed ? ubwc_size(q->width, q->height, q->stride) : q->size), - compressed ? "its compressed frames cannot be shown" : "its frames keep the copy path"); + static struct { + pid_t pid; + uint32_t width, height, format, stride, offset, reason; + uint64_t size, modifier; + } refused[32]; + static unsigned refused_count; + static int refused_limit_logged; + uint32_t reason = !sized ? 1u : !sane ? 2u : !wanted ? 3u : + !ahb_swapchain_advertised() ? 4u : + p->count >= DISPLAY_BUFFERS_MAX_PER_CLIENT ? 5u : 6u; + int seen = 0; + for (unsigned i = 0; i < refused_count; i++) { + if (refused[i].pid == p->pid && refused[i].width == q->width && refused[i].height == q->height && + refused[i].format == q->format && refused[i].stride == q->stride && refused[i].offset == q->offset && + refused[i].size == q->size && refused[i].modifier == q->modifier && refused[i].reason == reason) { + seen = 1; + break; + } + } + if (!seen && refused_count < 32) { + refused[refused_count].pid = p->pid; + refused[refused_count].width = q->width; + refused[refused_count].height = q->height; + refused[refused_count].format = q->format; + refused[refused_count].stride = q->stride; + refused[refused_count].offset = q->offset; + refused[refused_count].size = q->size; + refused[refused_count].modifier = q->modifier; + refused[refused_count].reason = reason; + refused_count++; + const char *why = reason == 1 ? "invalid dimensions, format, or stride" : + reason == 2 ? "size/offset/layout sanity check failed" : + reason == 3 ? "zero-copy or UBWC offering is disabled" : + reason == 4 ? "AHardwareBuffer swapchain is not advertised" : + reason == 5 ? "per-client allocation limit reached" : + "gralloc allocation/fd/size validation failed"; + droiddeck_log(compressed ? "error" : "layer", + "display buffers: allocation refused for pid %d: %s; request %ux%u %c%c%c%c %s stride=%u offset=%u size=%llu modifier=0x%llx (client has %d allocations)", + (int)p->pid, why, q->width, q->height, + q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff, + compressed ? "UBWC" : "linear", q->stride, q->offset, + (unsigned long long)q->size, (unsigned long long)q->modifier, p->count); + } else if (!seen && !refused_limit_logged) { + refused_limit_logged = 1; + droiddeck_log("layer", "display buffers: further allocation-refusal diagnostics suppressed after 32 signatures"); } } if (reply(p, &r, fd) != 0 && e) entry_free(e); @@ -299,9 +366,18 @@ static int on_listen(int fd, uint32_t mask, void *data) { } void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b) { + static int invalid_logged; struct stat st; struct entry *e; - if (!g_loop || wl_list_empty(&g_entries) || b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) return; + if (!g_loop || wl_list_empty(&g_entries)) return; + if (b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) { + if (!invalid_logged) { + invalid_logged = 1; + droiddeck_log("layer", "display buffers: cannot associate %s's DMA-BUF with gralloc (plane count %u; expected one plane at offset 0, or fstat failed)", + droiddeck_client_name(c), b->n_planes); + } + return; + } wl_list_for_each(e, &g_entries, link) { if (e->dev != st.st_dev || e->ino != st.st_ino) continue; AHardwareBuffer_Desc d; @@ -311,11 +387,27 @@ void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, stru (uint32_t)b->height == e->height : (b->modifier == MOD_LINEAR || b->modifier == MOD_INVALID) && e->stride == b->stride[0]; - if (laid_out && e->format == ahb_format_of(b->format, e->modifier) && b->width > 0 && b->height > 0 && - (uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height) + const uint32_t expected_format = ahb_format_of(b->format, e->modifier); + const int dimensions = b->width > 0 && b->height > 0 && + (uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height; + if (laid_out && e->format == expected_format && dimensions) { ahb_swapchain_adopt(c, buffer, b, e->ahb, e->modifier); + } else if (mismatch_should_log(b, 2)) { + droiddeck_log("layer", "display buffers: gralloc DMA-BUF identity matched but layout was rejected for %s: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; gralloc %ux%u stride %u format 0x%x, expected format 0x%x (layout %s, dimensions %s)", + droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff, + (b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height, + b->stride[0], b->offset[0], (unsigned long long)b->modifier, + e->width, e->height, e->stride, e->format, expected_format, + laid_out ? "ok" : "mismatch", dimensions ? "ok" : "mismatch"); + } return; } + if (mismatch_should_log(b, 1)) { + droiddeck_log("layer", "display buffers: no registered gralloc allocation matches %s's DMA-BUF identity: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; imported normally, copy path only", + droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff, + (b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height, + b->stride[0], b->offset[0], (unsigned long long)b->modifier); + } } void display_buffers_init(struct wl_display *display) { diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c index 1172c095b0..041f9c6c2b 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c @@ -4,12 +4,14 @@ #include #include #include +#include +#include #include #include "droiddeck_ext.h" #include "ahb_swapchain.h" #include "droiddeck_color.h" -enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT }; +enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD }; struct host_msg { enum host_kind kind; @@ -23,6 +25,32 @@ static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; static struct host_msg *g_head, *g_tail; static int g_wake[2] = {-1, -1}; +/* Compositor-thread-only fallback ordering state. */ +static int g_pending_token, g_pending_submit; +static int g_fallback_failed; +static int g_next_token = 1; +static struct host_msg *g_deferred_head, *g_deferred_tail; +static size_t g_deferred_count, g_deferred_bytes; +static int g_deferred_overflow; +static int g_completed_token, g_completed_result; + +#define DROIDDECK_EVDEV_KEY_MAX 768 +#define DROIDDECK_TEXT_DEFERRED_LIMIT 256 +#define DROIDDECK_TEXT_DEFERRED_BYTES (256 * 1024) +static unsigned char g_ordered_key_down[DROIDDECK_EVDEV_KEY_MAX]; + +void droiddeck_host_text_input_fallback_complete(int token, int result) { + pthread_mutex_lock(&g_mu); + g_completed_token = token; + g_completed_result = result; + pthread_mutex_unlock(&g_mu); + if (g_wake[1] >= 0) { + char c = 1; + ssize_t n = write(g_wake[1], &c, 1); + (void)n; + } +} + static void host_post(enum host_kind kind, const char *text, size_t len, int a, int b) { struct host_msg *m = calloc(1, sizeof(*m)); if (!m) return; @@ -51,6 +79,9 @@ void droiddeck_host_clipboard_text(const char *utf8, int len) { void droiddeck_host_text_commit(const char *utf8, int len) { host_post(HOST_TEXT_COMMIT, utf8, len > 0 ? (size_t)len : 0, 0, 0); } +void droiddeck_host_text_commit_and_submit(const char *utf8, int len) { + if (len > 0) host_post(HOST_TEXT_COMMIT, utf8, (size_t)len, 1, 0); +} void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end) { host_post(HOST_TEXT_PREEDIT, utf8, len > 0 ? (size_t)len : 0, cursor_begin, cursor_end); } @@ -63,23 +94,173 @@ void droiddeck_host_zero_copy(int on, int live) { void droiddeck_host_hdr_output(int on) { host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0); } +void droiddeck_host_key(int evdev, int state) { + host_post(HOST_KEY, NULL, 0, evdev, state); +} + +void droiddeck_host_select_game_field(int copy) { + host_post(HOST_SELECT_GAME_FIELD, NULL, 0, copy, 0); +} + +static void tap_unheld_key(uint32_t key) { + if (droiddeck_key_is_down(key)) return; + droiddeck_inject_key(key, 1); + droiddeck_inject_key(key, 0); +} + +static void select_game_field(int copy) { + /* Apply pending raw releases before using the compositor's held-key state. */ + droiddeck_dispatch_pending_input(); + int temporary_ctrl = !droiddeck_key_is_down(KEY_LEFTCTRL) && !droiddeck_key_is_down(KEY_RIGHTCTRL); + if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 1); + tap_unheld_key(KEY_A); + if (copy) tap_unheld_key(KEY_C); + if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 0); +} + +static void restore_deferred_to_front(void) { + if (g_deferred_head) { + g_deferred_tail->next = g_head; + if (!g_head) g_tail = g_deferred_tail; + g_head = g_deferred_head; + g_deferred_head = g_deferred_tail = NULL; + g_deferred_count = g_deferred_bytes = 0; + } +} + +/* Only suppress the queued submit for this commit, not a later commit or a held-key release. */ +static void discard_queued_submit(void) { + struct host_msg *prev = NULL; + struct host_msg *m = g_head; + int enter_held = g_ordered_key_down[KEY_ENTER]; + int key_pad_enter_held = g_ordered_key_down[KEY_KPENTER]; + while (m) { + int soft_submit = 0; + if (m->kind == HOST_TEXT_COMMIT) { + if (m->a || m->len == 0) break; + soft_submit = 1; + size_t i = 0; + for (; i < m->len; i++) { + char c = m->text[i]; + if (c != '\r' && c != '\n') soft_submit = 0; + if (c != '\r' && c != '\n' && c != '\b' && c != '\t' && c != 0x7f) break; + } + if (i != m->len) break; + } + struct host_msg *next = m->next; + int *held = m->a == KEY_ENTER ? &enter_held : m->a == KEY_KPENTER ? &key_pad_enter_held : NULL; + if (soft_submit || (m->kind == HOST_KEY && held && (m->b != 0 || !*held))) { + if (prev) prev->next = next; else g_head = next; + if (g_tail == m) g_tail = prev; + free(m->text); + free(m); + } else { + if (m->kind == HOST_KEY && held) *held = 0; + prev = m; + } + m = next; + } +} + +static int release_held_key(const struct host_msg *m) { + int k = m->a; + if (m->kind != HOST_KEY || m->b != 0 || k < 0 || k >= DROIDDECK_EVDEV_KEY_MAX || + !g_ordered_key_down[k]) return 0; + g_ordered_key_down[k] = 0; + droiddeck_inject_key((uint32_t)k, 0); + return 1; +} + +static void discard_deferred_input(void) { + struct host_msg *m = g_deferred_head; + while (m) { + struct host_msg *next = m->next; + release_held_key(m); + free(m->text); + free(m); + m = next; + } + g_deferred_head = g_deferred_tail = NULL; + g_deferred_count = g_deferred_bytes = 0; +} static int on_wake(int fd, uint32_t mask, void *data) { char buf[64]; while (read(fd, buf, sizeof(buf)) > 0) {} for (;;) { + int deferred = 0, submit = 0; pthread_mutex_lock(&g_mu); + if (g_pending_token != 0 && g_completed_token == g_pending_token) { + int result = g_completed_result; + g_completed_token = 0; + restore_deferred_to_front(); + if (result != DROIDDECK_TEXT_DELIVERED) discard_queued_submit(); + if (result == DROIDDECK_TEXT_UNRESOLVED) { + g_fallback_failed = 1; + } else { + if (result == DROIDDECK_TEXT_DELIVERED) submit = g_pending_submit; + g_pending_submit = 0; + g_pending_token = 0; + g_fallback_failed = 0; + g_deferred_overflow = 0; + } + } struct host_msg *m = g_head; - if (m) { g_head = m->next; if (!g_head) g_tail = NULL; } + if (m) { g_head = m->next; if (!g_head) g_tail = NULL; m->next = NULL; } pthread_mutex_unlock(&g_mu); + if (submit) tap_unheld_key(KEY_ENTER); if (!m) break; + if (g_pending_token != 0 && + (m->kind == HOST_TEXT_COMMIT || m->kind == HOST_TEXT_PREEDIT || + m->kind == HOST_TEXT_DELETE || m->kind == HOST_KEY || + m->kind == HOST_SELECT_GAME_FIELD)) { + int released_during_recovery = g_fallback_failed && release_held_key(m); + if (released_during_recovery || g_deferred_overflow || + g_deferred_count == DROIDDECK_TEXT_DEFERRED_LIMIT || + m->len > DROIDDECK_TEXT_DEFERRED_BYTES - g_deferred_bytes) { + if (!released_during_recovery) { + /* An incomplete queue could replay a submit or lose a paired release. */ + if (!g_deferred_overflow) + droiddeck_log("text-input", "deferred input exceeded the recovery queue limit"); + discard_deferred_input(); + release_held_key(m); + g_deferred_overflow = 1; + } + free(m->text); + free(m); + continue; + } + if (g_deferred_tail) g_deferred_tail->next = m; else g_deferred_head = m; + g_deferred_tail = m; + g_deferred_count++; + g_deferred_bytes += m->len; + deferred = 1; + } + if (deferred) continue; switch (m->kind) { case HOST_CLIPBOARD: clipboard_host_text(m->text, m->len); m->text = NULL; break; case HOST_TEXT_COMMIT: - text_input_host_commit(m->text ? m->text : "", m->len); + if (!text_input_host_commit(m->text ? m->text : "", m->len)) { + int token = 0; + if (g_next_token == INT_MAX) g_next_token = 1; + else g_next_token++; + token = g_next_token; + g_pending_token = 0; + if (droiddeck_on_text_input_fallback(m->text ? m->text : "", (int)m->len, token)) { + g_pending_token = token; + g_pending_submit = m->a; + } else { + droiddeck_log("text-input", "fallback had no accepting Android listener"); + pthread_mutex_lock(&g_mu); + discard_queued_submit(); + pthread_mutex_unlock(&g_mu); + } + } else if (m->a) { + tap_unheld_key(KEY_ENTER); + } break; case HOST_TEXT_PREEDIT: text_input_host_preedit(m->text ? m->text : "", m->len, m->a, m->b); @@ -93,6 +274,19 @@ static int on_wake(int fd, uint32_t mask, void *data) { case HOST_HDR_OUTPUT: droiddeck_color_set_output(m->a); break; + case HOST_SELECT_GAME_FIELD: + select_game_field(m->a); + break; + case HOST_KEY: + if (m->b == 1) { + int k = m->a; + if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 1; + } else if (m->b == 0) { + int k = m->a; + if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 0; + } + droiddeck_inject_key((uint32_t)m->a, m->b); + break; } free(m->text); free(m); diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h index ca359557e4..d7813eb7eb 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h @@ -15,22 +15,34 @@ struct wl_display *droiddeck_get_display(void); struct wl_resource *droiddeck_ime_target(void); void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y); void droiddeck_inject_key(uint32_t evdev, int pressed); +int droiddeck_key_is_down(uint32_t evdev); +void droiddeck_dispatch_pending_input(void); void droiddeck_on_clipboard_text(const char *utf8, int len); +int droiddeck_on_text_input_fallback(const char *utf8, int len, int token); void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h); void droiddeck_host_clipboard_text(const char *utf8, int len); void droiddeck_host_text_commit(const char *utf8, int len); +void droiddeck_host_text_commit_and_submit(const char *utf8, int len); void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end); void droiddeck_host_text_delete(int before, int after); void droiddeck_host_zero_copy(int on, int live); void droiddeck_host_hdr_output(int on); +void droiddeck_host_key(int evdev, int state); +void droiddeck_host_select_game_field(int copy); +enum droiddeck_text_input_result { + DROIDDECK_TEXT_NOT_DELIVERED = 0, + DROIDDECK_TEXT_DELIVERED = 1, + DROIDDECK_TEXT_UNRESOLVED = 2, +}; +void droiddeck_host_text_input_fallback_complete(int token, int result); void clipboard_init(struct wl_display *display); void clipboard_host_text(char *utf8, size_t len); void text_input_init(struct wl_display *display); -void text_input_host_commit(const char *utf8, size_t len); +int text_input_host_commit(const char *utf8, size_t len); void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end); void text_input_host_delete(int before, int after); void toplevel_icon_init(struct wl_display *display); diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.c b/app/src/main/cpp/waylandcomp/src/effects_chain.c index d711e565f3..6d307dcd7d 100644 --- a/app/src/main/cpp/waylandcomp/src/effects_chain.c +++ b/app/src/main/cpp/waylandcomp/src/effects_chain.c @@ -3,6 +3,7 @@ #include "blend_pass.h" #include "vk_loader.h" #include "vk_present.h" +#include "framegen_bridge.h" #include #include #include @@ -69,6 +70,7 @@ static struct fx_settings g_set = { .gamma = 1.0f, .saturation = 1.0f, .s_raw = 100.0f, .look = "Off"}; static volatile int g_changed; static struct fx_settings g_cur; +static struct fx_settings g_generated_settings; static int g_cur_valid; static void set_begin(void) { pthread_mutex_lock(&g_lock); } @@ -235,13 +237,24 @@ static VkDescriptorPool g_dpool; static VkSampler g_sampler; enum { P_SGSR, P_SGSR_HQ, P_NIS, P_EASU, P_RCAS, P_CAS, P_COLOR, P_FXAA, P_FXAA_TOON, P_SMAA_EDGE, P_SMAA_WEIGHTS, P_SMAA_BLEND, P_TOON, P_TOON_COLOR, P_HDR, P_NTSC, P_CRT, P_DEBAND, P_NIS_LUMA, P_COUNT }; static VkPipeline g_pipe[P_COUNT]; -static struct fx_target g_t[2], g_mid, g_smaa_edges, g_smaa_weights; +struct fx_context { + struct fx_target targets[2], mid, nissrc; + struct { VkImage img; VkImageView view; VkDescriptorSet ds; int w, h; } scene; +}; +#define FX_CONTEXTS (VKP_FG_MAX_GENERATIONS + 2) +static struct fx_context g_contexts[FX_CONTEXTS]; +static int g_context; +#define g_t (g_contexts[g_context].targets) +#define g_mid (g_contexts[g_context].mid) +#define g_nissrc (g_contexts[g_context].nissrc) +static struct fx_target g_smaa_edges, g_smaa_weights; /* Half set: NIS = nis_luma prepass (scene rgb + luma in alpha, scene size) into g_nissrc, then * nis3 gathers its luma from that alpha, its coefficient banks (nis_coef.h) in a uniform buffer * at descriptor set 1 (g_pl_nis = {g_dsl, g_coef_dsl}, same push-constant range as g_pl). * Old set (or no buffer): nis.frag on the scene, P_NIS_LUMA unused. */ -static struct fx_target g_nissrc; static int g_nis_fast; +static int g_nis_attempted; +static int g_upscale_half; static VkDescriptorSetLayout g_coef_dsl; static VkPipelineLayout g_pl_nis; static VkDescriptorPool g_coef_pool; @@ -249,7 +262,7 @@ static VkDescriptorSet g_coef_ds; static VkBuffer g_coef_buf; static VkDeviceMemory g_coef_mem; -static struct { VkImage img; VkImageView view; VkDescriptorSet ds; int w, h; } g_scene; +#define g_scene (g_contexts[g_context].scene) void vkp_effects_bind_device(VkDevice dev, VkPhysicalDevice pd, const VkPhysicalDeviceMemoryProperties *memprops) { @@ -347,7 +360,53 @@ static void scene_release(void) { } void vkp_effects_forget_image(VkImage img) { - if (img && g_scene.img == img) scene_release(); + int saved = g_context; + for (g_context = 0; g_context < FX_CONTEXTS; g_context++) + if (img && g_scene.img == img) scene_release(); + g_context = saved; +} + +VkImageView vkp_effects_framegen_image_view(VkImage img, int w, int h, VkFormat fmt) { + if (!g_dev || !img || w <= 0 || h <= 0 || fmt == VK_FORMAT_UNDEFINED) return VK_NULL_HANDLE; + + for (int i = 0; i < FX_CONTEXTS; ++i) { + struct fx_context *ctx = &g_contexts[i]; + if (ctx->scene.img == img && ctx->scene.view) return ctx->scene.view; + for (int j = 0; j < 2; ++j) + if (ctx->targets[j].img == img && ctx->targets[j].view) return ctx->targets[j].view; + if (ctx->mid.img == img && ctx->mid.view) return ctx->mid.view; + if (ctx->nissrc.img == img && ctx->nissrc.view) return ctx->nissrc.view; + } + if (g_smaa_edges.img == img && g_smaa_edges.view) return g_smaa_edges.view; + if (g_smaa_weights.img == img && g_smaa_weights.view) return g_smaa_weights.view; + + /* The effects chain can bypass every pass and return the compositor's scene image + * directly. Keep a view for that image in the existing per-context cache so the + * normal image-forget path destroys it before the image itself. */ + int saved = g_context; + g_context = 0; + if (g_scene.img != img || g_scene.view == VK_NULL_HANDLE || + g_scene.w != w || g_scene.h != h) { + scene_release(); + VkImageView view = make_view(img, fmt); + if (!view) { + g_context = saved; + return VK_NULL_HANDLE; + } + g_scene.img = img; + g_scene.view = view; + g_scene.w = w; + g_scene.h = h; + g_scene.ds = VK_NULL_HANDLE; + } + VkImageView result = g_scene.view; + g_context = saved; + return result; +} + +void vkp_effects_release_generated_sources(void) { + for (g_context = 1; g_context < FX_CONTEXTS; g_context++) scene_release(); + g_context = 0; } static int scene_ensure(VkImage img, int w, int h) { @@ -473,9 +532,14 @@ static int upscale_half_set(void) { static void objects_destroy(void) { if (!g_dev) return; - scene_release(); - target_destroy(&g_t[0]); target_destroy(&g_t[1]); target_destroy(&g_mid); - target_destroy(&g_smaa_edges); target_destroy(&g_smaa_weights); target_destroy(&g_nissrc); + int saved = g_context; + for (g_context = 0; g_context < FX_CONTEXTS; g_context++) { + scene_release(); + target_destroy(&g_t[0]); target_destroy(&g_t[1]); target_destroy(&g_mid); + target_destroy(&g_nissrc); + } + g_context = saved; + target_destroy(&g_smaa_edges); target_destroy(&g_smaa_weights); for (int i = 0; i < P_COUNT; i++) { if (g_pipe[i]) g_vk.DestroyPipeline(g_dev, g_pipe[i], NULL); g_pipe[i] = VK_NULL_HANDLE; } if (g_dpool) g_vk.DestroyDescriptorPool(g_dev, g_dpool, NULL); if (g_pl) g_vk.DestroyPipelineLayout(g_dev, g_pl, NULL); @@ -486,6 +550,7 @@ static void objects_destroy(void) { if (g_rp) g_vk.DestroyRenderPass(g_dev, g_rp, NULL); g_dpool = VK_NULL_HANDLE; g_pl = VK_NULL_HANDLE; g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE; g_rp = VK_NULL_HANDLE; g_smaa_rp = VK_NULL_HANDLE; + g_nis_fast = 0; g_nis_attempted = 0; g_upscale_half = 0; g_ready = 0; } @@ -505,7 +570,9 @@ void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt, int scene_ : target_fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? "the HDR picture for frame generation" : "the HDR composition's picture: PQ, or tone-mapped SDR with HDR output off"); } else if (scene_fmt != g_scene_fmt) { - scene_release(); + int saved = g_context; + for (g_context = 0; g_context < FX_CONTEXTS; g_context++) scene_release(); + g_context = saved; g_scene_fmt = scene_fmt; } } @@ -556,75 +623,17 @@ static int objects_ensure(void) { VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 2, .pSetLayouts = set_layouts, .pushConstantRangeCount = 1, .pPushConstantRanges = &pcr}; if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl) != VK_SUCCESS) goto fail; - VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 10}; + VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, FX_CONTEXTS * 5 + 2}; VkDescriptorPoolCreateInfo dpi = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, - .flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = 10, + .flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = FX_CONTEXTS * 5 + 2, .poolSizeCount = 1, .pPoolSizes = &ps}; if (g_vk.CreateDescriptorPool(g_dev, &dpi, NULL, &g_dpool) != VK_SUCCESS) goto fail; - VkShaderModule vert = shader(upscale_vert_code, sizeof(upscale_vert_code)); - if (!vert) goto fail; -#define MKL(slot, code, name, layout) do { g_pipe[slot] = post_pipeline_for_renderpass(vert, code, sizeof(code), g_rp, name, layout); if (!g_pipe[slot]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; } } while (0) -#define MK(slot, code, name) MKL(slot, code, name, g_pl) - const int half = upscale_half_set(); + g_upscale_half = upscale_half_set(); g_nis_fast = 0; - if (half && !fx_alpha_holds_luma(g_fx_fmt)) - droiddeck_log("effects", "NIS uses nis.frag: the chain format has no 8-bit alpha for the luma prepass"); - else if (half && coef_create() != 0) - droiddeck_log("effects", "NIS coefficient buffer unavailable; NIS uses nis.frag"); - else if (half) - g_nis_fast = 1; - if (half) { - MK(P_SGSR, sgsr_half_code, "sgsr_half"); - MK(P_SGSR_HQ, sgsr_quality_half_code, "sgsr_quality_half"); - if (g_nis_fast) { - /* optional: a driver that rejects either fast NIS pipeline gets nis.frag, not a dead chain */ - g_pipe[P_NIS] = post_pipeline_for_renderpass(vert, nis3_half_code, sizeof(nis3_half_code), g_rp, "nis3_half", g_pl_nis); - g_pipe[P_NIS_LUMA] = g_pipe[P_NIS] - ? post_pipeline_for_renderpass(vert, nis_luma_half_code, sizeof(nis_luma_half_code), g_rp, "nis_luma_half", g_pl) - : VK_NULL_HANDLE; - if (!g_pipe[P_NIS] || !g_pipe[P_NIS_LUMA]) { - if (g_pipe[P_NIS]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS], NULL); - g_pipe[P_NIS] = VK_NULL_HANDLE; - coef_destroy(); - g_nis_fast = 0; - droiddeck_log("effects", "fast NIS pipelines failed to build; NIS uses nis.frag"); - } - } - if (!g_nis_fast) MK(P_NIS, nis_code, "nis"); - MK(P_EASU, fsr_easu_half_code, "fsr_easu_half"); - MK(P_RCAS, fsr_rcas_half_code, "fsr_rcas_half"); - MK(P_CAS, cas_ffx_half_code, "cas_ffx_half"); - } else { - MK(P_SGSR, sgsr_code, "sgsr"); - MK(P_SGSR_HQ, sgsr_quality_code, "sgsr_quality"); - MK(P_NIS, nis_code, "nis"); - MK(P_EASU, fsr_easu_code, "fsr_easu"); - MK(P_RCAS, fsr_rcas_code, "fsr_rcas"); - MK(P_CAS, cas_code, "cas"); - } - MK(P_COLOR, color_code, "color"); - MK(P_FXAA, fxaa_code, "fxaa"); - MK(P_FXAA_TOON, fxaa_toon_code, "fxaa_toon"); - g_pipe[P_SMAA_EDGE] = post_pipeline_for_renderpass( - vert, smaa_edge_code, sizeof(smaa_edge_code), g_smaa_rp, "smaa_edge", g_pl); - if (!g_pipe[P_SMAA_EDGE]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; } - g_pipe[P_SMAA_WEIGHTS] = post_pipeline_for_renderpass( - vert, smaa_weights_code, sizeof(smaa_weights_code), g_smaa_rp, "smaa_weights", g_pl); - if (!g_pipe[P_SMAA_WEIGHTS]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; } - MK(P_SMAA_BLEND, smaa_blend_code, "smaa_blend"); - MK(P_TOON, toon_code, "toon"); - MK(P_TOON_COLOR, toon_color_code, "toon_color"); - MK(P_HDR, hdr_code, "hdr"); - MK(P_NTSC, ntsc_code, "ntsc"); - MK(P_CRT, crt_code, "crt"); - MK(P_DEBAND, deband_code, "deband"); -#undef MK -#undef MKL - g_vk.DestroyShaderModule(g_dev, vert, NULL); + g_nis_attempted = 0; g_ready = 1; - droiddeck_log("effects", "chain ready: 16 pipelines (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, SMAA edge/weights/blend, Toon, HDR, NTSC, CRT, deband), %s upscalers%s, on %s", - half ? "half-precision" : "old fp32", g_nis_fast ? " + NIS luma prepass" : "", vkp_gpu_name()); + droiddeck_log("effects", "shared resources ready on %s; effect pipelines are created when needed", vkp_gpu_name()); return 0; fail: objects_destroy(); @@ -633,6 +642,95 @@ fail: return -1; } +static int chain_failed(void) { + objects_destroy(); + g_ready = -1; + droiddeck_log("error", "effects: the screen-effect chain could not be built on this driver; effects are off for this session"); + return -1; +} + +static int pipelines_ensure(int spatial, const struct fx_settings *s) { + VkShaderModule vert = VK_NULL_HANDLE; +#define MKL(needed, slot, code, name, render_pass, layout) do { \ + if ((needed) && !g_pipe[slot]) { \ + if (!vert && !(vert = shader(upscale_vert_code, sizeof(upscale_vert_code)))) goto fail; \ + g_pipe[slot] = post_pipeline_for_renderpass(vert, code, sizeof(code), render_pass, name, layout); \ + if (!g_pipe[slot]) goto fail; \ + } \ +} while (0) +#define MK(needed, slot, code, name) MKL(needed, slot, code, name, g_rp, g_pl) + if (spatial == 3) { + if (g_upscale_half) MK(1, P_SGSR, sgsr_half_code, "sgsr_half"); + else MK(1, P_SGSR, sgsr_code, "sgsr"); + } + if (spatial == 8) { + if (g_upscale_half) MK(1, P_SGSR_HQ, sgsr_quality_half_code, "sgsr_quality_half"); + else MK(1, P_SGSR_HQ, sgsr_quality_code, "sgsr_quality"); + } + if (spatial == 4 || spatial == 5) { + if (g_upscale_half) MK(1, P_EASU, fsr_easu_half_code, "fsr_easu_half"); + else MK(1, P_EASU, fsr_easu_code, "fsr_easu"); + if (s->sharp_pct != 0) { + if (g_upscale_half) MK(1, P_RCAS, fsr_rcas_half_code, "fsr_rcas_half"); + else MK(1, P_RCAS, fsr_rcas_code, "fsr_rcas"); + } + } + if (spatial == 6) { + if (g_upscale_half) MK(1, P_RCAS, fsr_rcas_half_code, "fsr_rcas_half"); + else MK(1, P_RCAS, fsr_rcas_code, "fsr_rcas"); + } + if (spatial == 7) { + if (g_upscale_half && !g_nis_attempted) { + g_nis_attempted = 1; + if (!fx_alpha_holds_luma(g_fx_fmt)) + droiddeck_log("effects", "NIS uses nis.frag: the chain format has no 8-bit alpha for the luma prepass"); + else if (coef_create() != 0) + droiddeck_log("effects", "NIS coefficient buffer unavailable; NIS uses nis.frag"); + else { + if (!vert && !(vert = shader(upscale_vert_code, sizeof(upscale_vert_code)))) goto fail; + g_pipe[P_NIS] = post_pipeline_for_renderpass(vert, nis3_half_code, sizeof(nis3_half_code), g_rp, "nis3_half", g_pl_nis); + if (g_pipe[P_NIS]) + g_pipe[P_NIS_LUMA] = post_pipeline_for_renderpass(vert, nis_luma_half_code, sizeof(nis_luma_half_code), g_rp, "nis_luma_half", g_pl); + if (g_pipe[P_NIS] && g_pipe[P_NIS_LUMA]) g_nis_fast = 1; + else { + if (g_pipe[P_NIS]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS], NULL); + if (g_pipe[P_NIS_LUMA]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS_LUMA], NULL); + g_pipe[P_NIS] = VK_NULL_HANDLE; + g_pipe[P_NIS_LUMA] = VK_NULL_HANDLE; + coef_destroy(); + droiddeck_log("effects", "fast NIS pipelines failed to build; NIS uses nis.frag"); + } + } + } + if (!g_nis_fast) MK(1, P_NIS, nis_code, "nis"); + else if (g_upscale_half) MK(1, P_SGSR, sgsr_half_code, "sgsr_half"); + } + if (cas_active(s)) { + if (g_upscale_half) MK(1, P_CAS, cas_ffx_half_code, "cas_ffx_half"); + else MK(1, P_CAS, cas_code, "cas"); + } + if (s->color_on && !(s->toon && g_fx_fmt == FX_FORMAT)) MK(1, P_COLOR, color_code, "color"); + if (s->aa_mode == 1 || s->aa_mode == 2) MK(1, P_FXAA, fxaa_code, "fxaa"); + if (s->aa_mode == 2) { + MKL(1, P_SMAA_EDGE, smaa_edge_code, "smaa_edge", g_smaa_rp, g_pl); + MKL(1, P_SMAA_WEIGHTS, smaa_weights_code, "smaa_weights", g_smaa_rp, g_pl); + MK(1, P_SMAA_BLEND, smaa_blend_code, "smaa_blend"); + } + if (s->toon && s->color_on && g_fx_fmt == FX_FORMAT) MK(1, P_TOON_COLOR, toon_color_code, "toon_color"); + else if (s->toon) MK(1, P_TOON, toon_code, "toon"); + if (s->hdr_on) MK(1, P_HDR, hdr_code, "hdr"); + if (s->ntsc) MK(1, P_NTSC, ntsc_code, "ntsc"); + if (s->crt) MK(1, P_CRT, crt_code, "crt"); + if (deband_active(s)) MK(1, P_DEBAND, deband_code, "deband"); +#undef MK +#undef MKL + if (vert) g_vk.DestroyShaderModule(g_dev, vert, NULL); + return 0; +fail: + if (vert) g_vk.DestroyShaderModule(g_dev, vert, NULL); + return chain_failed(); +} + static void barrier(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to, VkPipelineStageFlags src_stage, VkAccessFlags src_access, @@ -681,14 +779,26 @@ static void pass_dual(VkCommandBuffer cmd, VkPipeline p, struct fx_target *dst, static const float FULL_NDC[4] = {-1.0f, -1.0f, 1.0f, 1.0f}; #define SET_NDC(pc) memcpy((pc).ndc, FULL_NDC, sizeof(FULL_NDC)) -VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h, - int out_w, int out_h, int *res_w, int *res_h) { +struct fx_source_state { + VkImageLayout layout; + VkPipelineStageFlags stage; + VkAccessFlags access; +}; + +static VkImage effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h, + int out_w, int out_h, int *res_w, int *res_h, + VkImageLayout input_layout, const struct fx_settings *frozen, + struct fx_source_state *source_state) { struct fx_settings snapshot; const struct fx_settings *s; - vkp_effects_sync(); - pthread_mutex_lock(&g_lock); - snapshot = g_cur; - pthread_mutex_unlock(&g_lock); + if (frozen) { + snapshot = *frozen; + } else { + vkp_effects_sync(); + pthread_mutex_lock(&g_lock); + snapshot = g_cur; + pthread_mutex_unlock(&g_lock); + } s = &snapshot; *res_w = scene_w; *res_h = scene_h; @@ -723,7 +833,7 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce effect_count(s) - (fuse_toon_color ? 1 : 0) - (fuse_fxaa_toon ? 1 : 0); - if ((spatial || nfx) && objects_ensure() == 0 && scene_ensure(scene, scene_w, scene_h) == 0 && + if ((spatial || nfx) && objects_ensure() == 0 && pipelines_ensure(spatial, s) == 0 && scene_ensure(scene, scene_w, scene_h) == 0 && target_ensure(&g_t[0], cw, ch, FX_TARGET_USAGE, "chain") == 0 && (chain_passes < 2 || target_ensure(&g_t[1], cw, ch, FX_TARGET_USAGE, "chain") == 0) && (!(spatial == 4 || spatial == 5) || s->sharp_pct == 0 || target_ensure(&g_mid, cw, ch, FX_SCRATCH_USAGE, "EASU") == 0)) { @@ -748,8 +858,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce g_vk.CmdSetScissor(cmd, 0, 1, &chain_sc); if (spatial) { - barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, + if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT}; + barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT); struct fx_target *dst = FREE_TARGET(); if (spatial == 3 || spatial == 8 || spatial == 7) { @@ -809,8 +921,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce cur = dst; cur_ds = dst->ds; } else if (resize) { struct fx_target *dst = FREE_TARGET(); - barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, + if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT}; + barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); barrier(cmd, dst->img, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); @@ -823,8 +937,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT); cur = dst; cur_ds = dst->ds; } else { - barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, + if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT}; + barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT); cur = NULL; cur_ds = g_scene.ds; } @@ -907,8 +1023,59 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce return scene; } - barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, + if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT}; + barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); return scene; } + +VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h, + int out_w, int out_h, int *res_w, int *res_h) { + return effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, NULL, NULL); +} + +int vkp_effects_prepare_generated(void) { + vkp_effects_sync(); + pthread_mutex_lock(&g_lock); + g_generated_settings = g_cur; + pthread_mutex_unlock(&g_lock); + return spatial_mode(g_generated_settings.scaling) && g_generated_settings.scaling != 6 && + effect_count(&g_generated_settings) == 0; +} + +VkImage vkp_effects_run_before_generated(VkCommandBuffer cmd, VkImage scene, int w, int h, + int *res_w, int *res_h) { + struct fx_settings settings = g_generated_settings; + settings.scaling = 0; + return effects_run(cmd, scene, w, h, w, h, res_w, res_h, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &settings, NULL); +} + +VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h, + int out_w, int out_h, int slot, int *res_w, int *res_h) { + if (slot < 0 || slot > VKP_FG_MAX_GENERATIONS) { + *res_w = scene_w; *res_h = scene_h; + return scene; + } + g_context = slot + 1; + struct fx_source_state source_state = {0}; + VkImage result = effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h, + VK_IMAGE_LAYOUT_GENERAL, &g_generated_settings, &source_state); + if (result != scene) { + barrier(cmd, result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); + barrier(cmd, scene, source_state.layout, VK_IMAGE_LAYOUT_GENERAL, + source_state.stage, source_state.access, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT); + } else if (source_state.layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { + barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); + } + g_context = 0; + return result; +} diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.h b/app/src/main/cpp/waylandcomp/src/effects_chain.h index 0617dd954f..a0aba31138 100644 --- a/app/src/main/cpp/waylandcomp/src/effects_chain.h +++ b/app/src/main/cpp/waylandcomp/src/effects_chain.h @@ -18,10 +18,17 @@ VkFilter vkp_effects_blit_filter(void); VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h, int out_w, int out_h, int *res_w, int *res_h); +int vkp_effects_prepare_generated(void); +void vkp_effects_release_generated_sources(void); +VkImage vkp_effects_run_before_generated(VkCommandBuffer cmd, VkImage scene, int w, int h, + int *res_w, int *res_h); +VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h, + int out_w, int out_h, int slot, int *res_w, int *res_h); void vkp_effects_destroy(void); void vkp_effects_forget_image(VkImage img); +VkImageView vkp_effects_framegen_image_view(VkImage img, int w, int h, VkFormat fmt); void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt, int scene_is_pq); diff --git a/app/src/main/cpp/waylandcomp/src/frame_acquire.h b/app/src/main/cpp/waylandcomp/src/frame_acquire.h new file mode 100644 index 0000000000..44ff28333a --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/frame_acquire.h @@ -0,0 +1,39 @@ +#ifndef DD_FRAME_ACQUIRE_H +#define DD_FRAME_ACQUIRE_H +#include +#include +#include +#include +#include + +/* A zero-initialized slot owns no descriptor. Only an already successful + * sync_file can enter this slot; display-side release ownership is separate. */ +struct dd_frame_acquire { int fd_plus_one; }; +enum dd_frame_acquire_result { DD_ACQUIRE_OK, DD_ACQUIRE_DUPLICATE, DD_ACQUIRE_INVALID }; + +static inline void dd_frame_acquire_clear(struct dd_frame_acquire *f) { + if (f->fd_plus_one) close(f->fd_plus_one - 1); + f->fd_plus_one = 0; +} + +static inline enum dd_frame_acquire_result +dd_frame_acquire_set(struct dd_frame_acquire *f, int fd) { + enum dd_frame_acquire_result result; + struct sync_file_info info = {0}; + if (f->fd_plus_one) result = DD_ACQUIRE_DUPLICATE; + else if (fd < 0 || fd == INT_MAX || ioctl(fd, SYNC_IOC_FILE_INFO, &info) != 0 || + info.status != 1 || info.num_fences == 0) result = DD_ACQUIRE_INVALID; + else { + f->fd_plus_one = fd + 1; + return DD_ACQUIRE_OK; + } + if (fd >= 0) close(fd); + return result; +} + +static inline int dd_frame_acquire_dup(const struct dd_frame_acquire *f) { + if (!f->fd_plus_one) return -1; /* Legacy: no explicit attachment proof. */ + int fd = fcntl(f->fd_plus_one - 1, F_DUPFD_CLOEXEC, 0); + return fd < 0 ? -2 : fd; /* Do not re-enter the legacy direct path. */ +} +#endif diff --git a/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h b/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h new file mode 100644 index 0000000000..989e59b336 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h @@ -0,0 +1,81 @@ +#ifndef DD_WORKER_PEER_H +#define DD_WORKER_PEER_H +#include +#include +#include +#include +#include +#include +#include + +/* Model of one app-issued, session-bound authorization record. No callers, + * property access, proc traversal, or authorization is installed by this file. */ +struct dd_worker_grant { + uint32_t owner, uid, pid, dev_major, dev_minor; + uint64_t start_ticks, ino, expires; + const char *canonical_file; + bool app_launch_verified, final_go; +}; + +enum dd_worker_stat_result { + DD_WORKER_STAT_OK, DD_WORKER_STAT_DENIED, DD_WORKER_STAT_HIDDEN, DD_WORKER_STAT_OPEN, + DD_WORKER_STAT_READ, DD_WORKER_STAT_PARSE, DD_WORKER_STAT_ZERO, +}; + +static inline enum dd_worker_stat_result dd_worker_parse_start(const char *line, uint64_t *out) { + const char *p = strrchr(line, ')'); + if (!p || p[1] != ' ' || !p[2] || p[3] != ' ') return DD_WORKER_STAT_PARSE; + p += 2; + // State is field 3. The starttime (22) is always followed by vsize (23). + for (int field = 3; field < 22; ++field) { + p = strchr(p, ' '); + if (!p) return DD_WORKER_STAT_PARSE; + while (*p == ' ') ++p; + } + char *end; + if (*p < '0' || *p > '9') return DD_WORKER_STAT_PARSE; + errno = 0; + uint64_t value = strtoull(p, &end, 10); + if (errno || end == p || *end != ' ') return DD_WORKER_STAT_PARSE; + if (!value) return DD_WORKER_STAT_ZERO; + *out = value; + return DD_WORKER_STAT_OK; +} + +static inline enum dd_worker_stat_result dd_worker_open_failure(int error) { + if (error == EACCES || error == EPERM) return DD_WORKER_STAT_DENIED; + if (error == ENOENT || error == ESRCH) return DD_WORKER_STAT_HIDDEN; + return DD_WORKER_STAT_OPEN; +} + +static inline bool dd_worker_receipt_allows_reserve(enum dd_worker_stat_result stat, + uint64_t raw, uint64_t receipt) { + if (!receipt) return false; + if (stat == DD_WORKER_STAT_OK) return raw == receipt; + // Only a visibility denial can defer the broker-side stat check, not any + // bad read, malformed record, mismatched timestamp, or other open error. + return stat == DD_WORKER_STAT_DENIED || stat == DD_WORKER_STAT_HIDDEN; +} + +static inline bool dd_worker_map_matches(const struct dd_worker_grant *g, const char *line) { + unsigned major, minor; + uint64_t lo, hi, off, ino; + int prefix = 0; + char mode[5]; + if (!g->canonical_file || !*g->canonical_file || + sscanf(line, "%" SCNx64 "-%" SCNx64 " %4s %" SCNx64 " %x:%x %" SCNu64 " %n", + &lo,&hi,mode,&off,&major,&minor,&ino,&prefix)!=7 || + prefix <= 0 || hi <= lo || strlen(mode)!=4 || mode[2]!='x' || + major!=g->dev_major || minor!=g->dev_minor || !ino || ino!=g->ino) + return false; + size_t path_len=strcspn(line+prefix,"\r\n"); + return strlen(g->canonical_file)==path_len && !memcmp(line+prefix,g->canonical_file,path_len); +} + +static inline bool dd_worker_grant_matches(const struct dd_worker_grant *g, uint32_t owner, + uint32_t uid, uint32_t pid, uint64_t start, uint64_t now, const char *executable_map) { + return g && g->app_launch_verified && g->final_go && owner && owner==g->owner && + uid==g->uid && pid>1 && pid==g->pid && start && start==g->start_ticks && + nowexpires && executable_map && dd_worker_map_matches(g,executable_map); +} +#endif diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c index 007b2dcbde..7745c3ddc0 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c @@ -1,7 +1,9 @@ #define _POSIX_C_SOURCE 200809L #include "framegen_bridge.h" #include "framegen_engine.h" +#include "effects_chain.h" #include "vk_loader.h" +#include "sc_layer.h" #include #include #include @@ -35,7 +37,7 @@ static VkQueue g_queue; static uint32_t g_qfam; static _Atomic int g_dev_ready, g_dev_lost; static int g_features_enabled; -static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok; +static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok, g_caps_zero_ok; static VkPhysicalDeviceMemoryProperties g_memprops; static struct { PFN_vkCreateImage CreateImage; @@ -86,9 +88,44 @@ static int64_t now_ns(void) { return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec; } +/* The pair the last run made, for the display probe and the pacer: when its real frame reached the + * compositor, the game moment each generated frame shows, and the refresh the pacer timed each for. */ +static _Atomic int g_pacer_on; +static int g_layer_path; +static int g_out_gens; +static int64_t g_out_planned[VKP_FG_MAX_GENERATIONS + 1]; +static int64_t g_completion_issue; + +void vkp_framegen_set_pacer(int on) { + if (atomic_exchange(&g_pacer_on, on ? 1 : 0) != (on ? 1 : 0)) { + fge_pacer_reset(); + FGLOG("ZeroFG pacer %s", on ? "on: frame generation times its frames itself" : "off: the display layer times them"); + } +} + +static int pacer_wanted(void) { return atomic_load(&g_pacer_on); } + +void vkp_framegen_pacer_abort(void) { + g_completion_issue = 0; + fge_pacer_reset(); +} + +void vkp_framegen_output_planned(int k, int gens, int64_t *planned) { + *planned = (k < 0 || k >= gens || k >= g_out_gens) + ? g_out_planned[g_out_gens] : g_out_planned[k]; +} + +void vkp_framegen_completed(void) { + if (!g_completion_issue) return; + fge_pacer_completed(g_completion_issue, now_ns()); + g_completion_issue = 0; +} + +void vkp_framegen_real_shown(int64_t planned_ns, int64_t shown_ns) { fge_pacer_shown(planned_ns, shown_ns); } + void vkp_framegen_set_engine(int kind) { - if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG) kind = VKP_FG_ENGINE_LSFG; + if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG && kind != VKP_FG_ENGINE_ZEROFG) kind = VKP_FG_ENGINE_LSFG; atomic_store(&g_kind, kind); atomic_store(&g_failed_kind, -1); atomic_store(&g_cfg_dirty, 1); @@ -117,6 +154,11 @@ void vkp_framegen_set_lsfg_cache_path(const char *path) { pthread_mutex_unlock(&g_lock); } +void vkp_framegen_set_layer_timing(int layer) { + g_layer_path = layer; + fge_set_layer_timing(layer); +} + void vkp_framegen_set_tuning(float flow_scale, float refresh_hz) { if (flow_scale < 0.25f) flow_scale = 0.25f; if (flow_scale > 1.0f) flow_scale = 1.0f; @@ -145,15 +187,15 @@ static void mark_failed(int kind) { int vkp_framegen_problem(void) { if (!atomic_load(&g_dev_ready)) return -1; int kind = atomic_load(&g_kind); - int caps_ok = kind == VKP_FG_ENGINE_DDFG - ? atomic_load(&g_caps_ddfg_ok) - : atomic_load(&g_caps_lsfg_ok); + int caps_ok = kind == VKP_FG_ENGINE_ZEROFG ? atomic_load(&g_caps_zero_ok) : + kind == VKP_FG_ENGINE_DDFG ? atomic_load(&g_caps_ddfg_ok) : + atomic_load(&g_caps_lsfg_ok); if (!caps_ok) return 1; if (start_failed_for(kind)) return 2; if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2; return 0; } -const char *vkp_framegen_caps_reason(void) { return fge_caps_reason(); } +const char *vkp_framegen_caps_reason(void) { return fge_caps_reason(atomic_load(&g_kind)); } void vkp_framegen_stats(float out[6]) { float accepted = 0.0f, src = 0.0f, thermal = -1.0f; @@ -186,12 +228,14 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled); atomic_store(&g_caps_lsfg_ok, fge_caps_ok(VKP_FG_ENGINE_LSFG)); atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG)); + atomic_store(&g_caps_zero_ok, fge_caps_ok(VKP_FG_ENGINE_ZEROFG)); atomic_store(&g_dev_lost, 0); atomic_store(&g_dev_ready, vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier); - FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s", - fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(), - fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable"); + FGLOG("engines ready on compositor device: LSFG %s, DD-FG %s, ZeroFG %s", + fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", + fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable", + fge_caps_ok(VKP_FG_ENGINE_ZEROFG) ? "available" : "unavailable"); } void vkp_framegen_device_lost(void) { @@ -226,7 +270,10 @@ static void destroy_ring(void) { if (vk.DeviceWaitIdle) vk.DeviceWaitIdle(g_dev); for (uint32_t i = 0; i < g_ring_n; i++) { if (g_ring[i].view) vk.DestroyImageView(g_dev, g_ring[i].view, NULL); - if (g_ring[i].img) vk.DestroyImage(g_dev, g_ring[i].img, NULL); + if (g_ring[i].img) { + vkp_effects_forget_image(g_ring[i].img); + vk.DestroyImage(g_dev, g_ring[i].img, NULL); + } if (g_ring[i].mem) vk.FreeMemory(g_dev, g_ring[i].mem, NULL); memset(&g_ring[i], 0, sizeof(g_ring[i])); } @@ -279,16 +326,18 @@ static int engine_usable(void) { int kind = atomic_load(&g_kind); int ready = atomic_load(&g_dev_ready); int lost = atomic_load(&g_dev_lost); - int caps_ok = kind == VKP_FG_ENGINE_DDFG - ? atomic_load(&g_caps_ddfg_ok) - : atomic_load(&g_caps_lsfg_ok); + int caps_ok = kind == VKP_FG_ENGINE_ZEROFG ? atomic_load(&g_caps_zero_ok) : + kind == VKP_FG_ENGINE_DDFG ? atomic_load(&g_caps_ddfg_ok) : + atomic_load(&g_caps_lsfg_ok); return ready && !lost && caps_ok && !start_failed_for(kind); } int vkp_framegen_format_ok(VkFormat fmt) { - if (fmt == VK_FORMAT_R8G8B8A8_UNORM) return 1; if (!g_dev_ready || g_dev_lost || format_refused(fmt)) return 0; - return fge_format_ok(fmt); + int kind = atomic_load(&g_kind); + if (kind == VKP_FG_ENGINE_ZEROFG) return fge_format_ok(VKP_FG_ENGINE_ZEROFG, fmt); + if (fmt == VK_FORMAT_R8G8B8A8_UNORM) return 1; + return fge_format_ok(kind, fmt); } static void refuse_format(VkFormat fmt, int kind, int w, int h, const char *what) { @@ -373,11 +422,14 @@ static void log_arm_transition(int armed, int kind, int mult) { int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, int w, int h, VkFormat fmt, VkImage gens[VKP_FG_MAX_GENERATIONS]) { - (void)scene_view; int kind = atomic_load(&g_kind); int armed = atomic_load(&g_armed); int mult = atomic_load(&g_mult); g_planned = 0; + const int64_t issue = now_ns(); + g_out_gens = 0; + memset(g_out_planned, 0, sizeof(g_out_planned)); + g_completion_issue = 0; if (!armed || !engine_usable() || w <= 0 || h <= 0) { log_arm_transition(0, kind, mult); return 0; } if (!ensure_engine(kind)) { log_arm_transition(0, kind, mult); return 0; } log_arm_transition(1, kind, mult); @@ -419,8 +471,31 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, ++g_source_frames; const uint64_t game_frames = droiddeck_game_frames(); - uint32_t n_gen = fge_plan(g_ring_n, game_frames ? game_frames : g_source_frames, g_presented_rate); + const uint64_t planning_sequence = game_frames ? game_frames : g_source_frames; + uint32_t n_gen = fge_plan(g_ring_n, planning_sequence, g_presented_rate); if (n_gen > g_ring_n) n_gen = g_ring_n; + if (kind == VKP_FG_ENGINE_ZEROFG && n_gen > 0 && !scene_view) { + scene_view = vkp_effects_framegen_image_view(scene, w, h, fmt); + if (!scene_view) { + static int view_warning; + if (!view_warning++) FGLOG("ZeroFG could not create a view for the source image; showing real frames only"); + n_gen = 0; + } + } + fge_set_phases(NULL, 0); + if (kind == VKP_FG_ENGINE_ZEROFG && pacer_wanted() && g_layer_path) { + int64_t vsync = 0, period = 0; + sc_layer_timeline(&vsync, &period); + int64_t planned[VKP_FG_MAX_GENERATIONS + 1]; + float phases[VKP_FG_MAX_GENERATIONS + 1]; + const uint32_t count = period > 0 + ? fge_pacer_plan((uint32_t)mult, period, vsync, issue, n_gen, planned, phases) : 0; + if (count >= 1 && count - 1 <= n_gen) { + n_gen = count - 1; + for (uint32_t i = 0; i < count; i++) g_out_planned[i] = planned[i]; + fge_set_phases(phases, n_gen); + } + } g_planned = n_gen; VkImageMemoryBarrier bars[1 + VKP_FG_MAX_GENERATIONS]; @@ -448,21 +523,25 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, NULL, 0, NULL, nb, bars); - fge_process(cmd, scene, (uint32_t)w, (uint32_t)h, n_gen); + fge_process(cmd, scene, scene_view, (uint32_t)w, (uint32_t)h, fmt, planning_sequence, n_gen); for (uint32_t g = 0; g < n_gen; g++) { fge_generate(cmd, g, n_gen, g_ring[g].img, g_ring[g].view, (uint32_t)w, (uint32_t)h); gens[g] = g_ring[g].img; } if (n_gen) { nb = 0; + const VkAccessFlags generated_access = kind == VKP_FG_ENGINE_ZEROFG + ? VK_ACCESS_MEMORY_WRITE_BIT : VK_ACCESS_SHADER_WRITE_BIT; + const VkPipelineStageFlags generated_stage = kind == VKP_FG_ENGINE_ZEROFG + ? VK_PIPELINE_STAGE_ALL_COMMANDS_BIT : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; for (uint32_t g = 0; g < n_gen; g++) bars[nb++] = (VkImageMemoryBarrier){ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .srcAccessMask = generated_access, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, .oldLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_ring[g].img, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; - vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + vk.CmdPipelineBarrier(cmd, generated_stage, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, nb, bars); if (!g_generating_logged) { g_generating_logged = 1; @@ -472,6 +551,8 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? ", FP16: the HDR picture" : ""); } } + g_out_gens = (int)n_gen; + if (n_gen > 0) g_completion_issue = issue; return (int)n_gen; } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.h b/app/src/main/cpp/waylandcomp/src/framegen_bridge.h index 573d6fd3c6..3412eda7f1 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.h +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.h @@ -6,7 +6,7 @@ #endif #include -enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1 }; +enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1, VKP_FG_ENGINE_ZEROFG = 2 }; #define VKP_FG_MAX_GENERATIONS 3 void vkp_framegen_set_engine(int kind); @@ -26,6 +26,18 @@ void vkp_framegen_device_lost(void); int vkp_framegen_active(void); int vkp_framegen_extra_images(void); +/* 1 when the next run's frames are shown through the scene layer's timed group, 0 through the swapchain's FIFO. */ +void vkp_framegen_set_layer_timing(int layer); +/* ZeroFG's pacer (include/zerofg/inline_pacer.h) times the layer's frames instead of the layer's own spacing. */ +void vkp_framegen_set_pacer(int on); +/* Reset pacing history when a planned real-frame pair is aborted before presentation. */ +void vkp_framegen_pacer_abort(void); +/* Refresh planned for output k of the last run (k == gens: its real frame; 0: use layer timing). */ +void vkp_framegen_output_planned(int k, int gens, int64_t *planned); +/* The last run's GPU work finished (the compositor's fence signalled). */ +void vkp_framegen_completed(void); +/* A real frame the pacer timed for planned_ns was shown at shown_ns. */ +void vkp_framegen_real_shown(int64_t planned_ns, int64_t shown_ns); int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, int w, int h, VkFormat fmt, VkImage gens[VKP_FG_MAX_GENERATIONS]); void vkp_framegen_presented(int generated); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp index 014c7c7ec8..6f0b6db6b0 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -13,6 +14,9 @@ #include "lsfg/lsfg_probe.h" #include "lsfg/lsfg_vkd.h" #include "ddfg/ddfg_engine.h" +#include "framegen_zerofg.h" + +#include #define ELOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "framegen: " __VA_ARGS__) #define ELOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "framegen: " __VA_ARGS__) @@ -22,15 +26,21 @@ namespace { VkTable g_table{}; lsfg::Caps g_caps{}; VkPhysicalDeviceVulkan12Features g_v12{}; +VkPhysicalDeviceVulkan13Features g_v13{}; VkPhysicalDeviceFeatures2 g_f2{}; VkPhysicalDevice g_pd = VK_NULL_HANDLE; VkDevice g_dev = VK_NULL_HANDLE; VkQueue g_queue = VK_NULL_HANDLE; uint32_t g_qfam = 0; bool g_probed = false, g_ready = false; +bool g_zero_supported = false, g_zero_enabled = false; +zerofg::InlinePacer g_pacer; +zerofg::InlineReadiness g_readiness; +std::mutex g_pacer_mutex; std::unique_ptr g_lsfg; std::unique_ptr g_ddfg; +std::vector> g_retained_ddfg; int g_kind = -1; char g_build[96] = ""; @@ -87,30 +97,57 @@ const void *fge_probe(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica if (n) enumExts(pd, nullptr, &n, exts.data()); } g_caps = lsfg::Caps{}; - - - g_caps.features = lsfg::queryFeatures(g_table, pd, exts, false); + g_caps.features = lsfg::queryFeatures(g_table, pd, exts, false); g_caps.probedFormat = ring_fmt; g_caps.storageOnSwapchainFormat = g_table.GetPhysicalDeviceFormatProperties ? lsfg::probeStorageFormat(g_table, pd, ring_fmt) : false; g_caps.linearBlitOnSwapchainFormat = g_table.GetPhysicalDeviceFormatProperties ? lsfg::probeLinearBlit(g_table, pd, ring_fmt) : false; g_probed = true; - if (!g_caps.features.deviceGatesPass()) { + + VkPhysicalDeviceProperties props{}; + if (g_table.GetPhysicalDeviceProperties) g_table.GetPhysicalDeviceProperties(pd, &props); + VkPhysicalDeviceVulkan13Features supported13{}; + supported13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES; + VkPhysicalDeviceFeatures2 supported2{}; + supported2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + if (props.apiVersion >= VK_API_VERSION_1_3) supported2.pNext = &supported13; + if (g_table.GetPhysicalDeviceFeatures2) g_table.GetPhysicalDeviceFeatures2(pd, &supported2); + g_zero_supported = props.apiVersion >= VK_API_VERSION_1_3 && + supported13.synchronization2 == VK_TRUE && + supported2.features.shaderStorageImageExtendedFormats == VK_TRUE; + g_zero_enabled = false; + + const bool lsfg_supported = g_caps.features.deviceGatesPass(); + if (!lsfg_supported) { lsfg::explain(g_caps); ELOG("device gates for the LSFG chain fail: %s", g_caps.reason); + } + if (!lsfg_supported && !g_zero_supported) { + g_v12 = {}; + g_v13 = {}; + g_f2 = {}; return nullptr; } + g_v12 = VkPhysicalDeviceVulkan12Features{}; g_v12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; - g_v12.vulkanMemoryModel = VK_TRUE; + g_v12.vulkanMemoryModel = + g_caps.features.vulkanMemoryModel ? VK_TRUE : VK_FALSE; g_v12.vulkanMemoryModelDeviceScope = g_caps.features.vulkanMemoryModelDeviceScope ? VK_TRUE : VK_FALSE; + g_v13 = VkPhysicalDeviceVulkan13Features{}; + g_v13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES; + g_v13.synchronization2 = g_zero_supported ? VK_TRUE : VK_FALSE; + if (g_zero_supported) g_v12.pNext = &g_v13; + g_f2 = VkPhysicalDeviceFeatures2{}; g_f2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; g_f2.pNext = &g_v12; - g_f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; - g_f2.features.shaderStorageImageExtendedFormats = VK_TRUE; + g_f2.features.shaderStorageImageWriteWithoutFormat = + supported2.features.shaderStorageImageWriteWithoutFormat ? VK_TRUE : VK_FALSE; + g_f2.features.shaderStorageImageExtendedFormats = + supported2.features.shaderStorageImageExtendedFormats ? VK_TRUE : VK_FALSE; return &g_f2; } @@ -121,14 +158,29 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica fill_device(dev); g_caps.featuresEnabled = features_enabled != 0; lsfg::explain(g_caps); + VkPhysicalDeviceProperties props{}; + if (g_table.GetPhysicalDeviceProperties) g_table.GetPhysicalDeviceProperties(pd, &props); + g_zero_enabled = g_zero_supported && features_enabled != 0; + zfg_device_ready(gipa, inst, pd, dev, + props.apiVersion > VK_API_VERSION_1_3 ? VK_API_VERSION_1_3 : props.apiVersion, + g_zero_enabled, + g_zero_enabled && g_f2.features.shaderStorageImageExtendedFormats == VK_TRUE); g_ready = true; - ELOG("device ready: lsfg caps '%s', storage on ring format %d", g_caps.reason, - (int)g_caps.storageOnSwapchainFormat); + ELOG("device ready: lsfg caps '%s', storage on ring format %d, ZeroFG %s", + g_caps.reason, (int)g_caps.storageOnSwapchainFormat, + g_zero_enabled ? "available" : "unavailable"); } void fge_device_lost(void) { g_lsfg.reset(); - g_ddfg.reset(); + if (g_ddfg) { + if (g_ddfg->destroy()) g_ddfg.reset(); + else g_retained_ddfg.push_back(std::move(g_ddfg)); + } + // The device is being torn down. Unknown-completion resources must not be + // passed to Vulkan destruction calls; the VkDevice teardown reclaims them. + for (auto& engine : g_retained_ddfg) engine->abandon(); + g_retained_ddfg.clear(); g_kind = -1; g_dev = VK_NULL_HANDLE; g_queue = VK_NULL_HANDLE; @@ -141,24 +193,45 @@ void fge_device_lost(void) { g_v12 = {}; g_f2 = {}; g_build[0] = 0; + g_zero_supported = g_zero_enabled = false; + zfg_device_lost(); } int fge_caps_ok(int kind) { if (!g_ready) return 0; + if (kind == 2) return g_zero_enabled && zfg_caps_ok(); if (kind == 1) return g_caps.storageOnSwapchainFormat ? 1 : 0; return g_caps.supported() ? 1 : 0; } -const char *fge_caps_reason(void) { return g_caps.reason; } +int fge_engine_available(int kind) { return fge_caps_ok(kind); } -int fge_format_ok(VkFormat fmt) { +const char *fge_caps_reason(int kind) { + if (kind == 2 && !g_zero_enabled) + return "ZeroFG requires Vulkan 1.3, synchronization2 and extended storage-image formats"; + if (kind == 2) return zfg_caps_reason(); + return g_caps.reason; +} + +int fge_format_ok(int kind, VkFormat fmt) { + if (kind == 2) return zfg_format_ok(fmt); if (!g_ready || !g_table.GetPhysicalDeviceFormatProperties || fmt == VK_FORMAT_UNDEFINED) return 0; return lsfg::probeStorageFormat(g_table, g_pd, fmt) && lsfg::probeLinearBlit(g_table, g_pd, fmt) ? 1 : 0; } int fge_start(int kind, const char *cache_path) { fge_stop(); + fge_pacer_reset(); if (!g_ready) return -1; + if (kind == 2) { + if (!g_zero_enabled || !zfg_start()) { + ELOGE("ZeroFG engine init failed"); + return -1; + } + g_kind = 2; + std::snprintf(g_build, sizeof(g_build), "ZeroFG ReallyZero, Vulkan 1.3 Compat"); + return 0; + } if (kind == 1) { auto e = std::make_unique(); if (!e->init(g_table, g_pd, g_dev, g_qfam, g_queue)) { @@ -193,13 +266,30 @@ int fge_start(int kind, const char *cache_path) { } void fge_stop(void) { - if ((g_lsfg || g_ddfg) && g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev); + if ((g_kind == 0 || g_kind == 2) && g_table.DeviceWaitIdle && g_dev) + g_table.DeviceWaitIdle(g_dev); + g_lsfg.reset(); - g_ddfg.reset(); + + for (auto it = g_retained_ddfg.begin(); it != g_retained_ddfg.end();) { + if ((*it)->destroy()) it = g_retained_ddfg.erase(it); + else ++it; + } + + if (g_ddfg) { + if (g_ddfg->destroy()) g_ddfg.reset(); + else { + ELOGE("ddfg-native: retaining engine until GPU completion is known or device teardown"); + g_retained_ddfg.push_back(std::move(g_ddfg)); + } + } + + zfg_stop(); g_kind = -1; } int fge_unavailable(void) { + if (g_kind == 2) return zfg_unavailable(); if (g_kind == 1) return g_ddfg && g_ddfg->unavailable() ? 1 : 0; return g_lsfg && g_lsfg->unavailable() ? 1 : 0; } @@ -207,11 +297,13 @@ int fge_unavailable(void) { void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz, int model, int perf_preset) { if (multiplier < 2) multiplier = 2; + if (g_kind == 2) { zfg_configure(multiplier, refresh_hz); return; } if (g_kind == 1 && g_ddfg) g_ddfg->configure(multiplier, model, perf_preset, flow_scale); else if (g_lsfg) g_lsfg->configure(multiplier, target_fps, flow_scale, refresh_hz); } int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { + if (g_kind == 2) return zfg_prepare(w, h, fmt); if (g_kind == 1) return g_ddfg && g_ddfg->prepare(w, h, fmt) ? 1 : 0; if (!g_lsfg) return 0; g_lsfg->setGuestExtent(w, h); @@ -219,24 +311,74 @@ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { } uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) { + if (g_kind == 2) return zfg_plan(capacity, source_frames); if (g_kind == 1) return g_ddfg ? g_ddfg->plan(capacity) : 0; if (!g_lsfg) return 0; g_lsfg->setPresentedRate(presented_rate); return g_lsfg->plan(capacity, source_frames); } -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) { +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t w, uint32_t h, VkFormat fmt, uint64_t sequence, uint32_t gens) { + if (g_kind == 2) { + zfg_process(cmd, source, source_view, w, h, fmt, sequence, gens); + return; + } if (g_kind == 1) { if (g_ddfg) g_ddfg->process(cmd, source, w, h, gens); return; } if (g_lsfg) g_lsfg->process(cmd, source, w, h, gens); } void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h) { + if (g_kind == 2) { zfg_generate(cmd, g, count, img, view, w, h); return; } if (g_kind == 1) { if (g_ddfg) g_ddfg->generateInto(cmd, g, count, img, view, w, h); return; } if (g_lsfg) g_lsfg->generateInto(cmd, g, g, img, view, w, h); } +void fge_set_layer_timing(int layer) { zfg_set_layer_timing(layer); } + +void fge_set_phases(const float *phases, uint32_t count) { zfg_set_phases(phases, count); } + +float fge_phase(uint32_t index, uint32_t count) { + if (g_kind == 2) return zfg_phase(index, count); + return static_cast(index + 1) / static_cast(count + 1); +} + +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases) { + if (period_ns <= 0 || issue_ns <= 0) return 0; + std::lock_guard lock(g_pacer_mutex); + g_pacer.SetMultiplier(multiplier); + g_pacer.ObserveVsync(static_cast(period_ns), static_cast(vsync_ns > 0 ? vsync_ns : 0)); + const uint64_t issue = static_cast(issue_ns); + const zerofg::InlinePacer::Plan plan = + g_pacer.PlanPair(issue, issue + g_readiness.MarginNs(static_cast(period_ns)), max_generated + 1); + for (uint32_t i = 0; i < plan.count; i++) { + present_ns[i] = static_cast(plan.outputs[i].present_ns); + phases[i] = plan.outputs[i].phase; + } + return plan.count; +} + +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns) { + std::lock_guard lock(g_pacer_mutex); + if (issue_ns > 0 && done_ns > issue_ns) + g_readiness.ObserveCompleted(static_cast(issue_ns), static_cast(done_ns)); +} + +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns) { + std::lock_guard lock(g_pacer_mutex); + if (planned_ns > 0 && shown_ns > 0) + g_pacer.ObserveRealShown(static_cast(planned_ns), static_cast(shown_ns)); +} + +void fge_pacer_reset(void) { + std::lock_guard lock(g_pacer_mutex); + g_pacer.Reset(); +} + void fge_forget_targets(void) { + if (g_kind == 2) { zfg_forget_targets(); return; } if (g_lsfg) g_lsfg->forgetTargets(); } @@ -246,10 +388,14 @@ void fge_telemetry(float *accepted, float *source_rate, float *thermal) { *accepted = (float)g_lsfg->acceptedGenerations(); *source_rate = g_lsfg->sourceRate(); *thermal = (float)g_lsfg->thermalStatus(); + } else if (g_kind == 2) { + zfg_telemetry(accepted, source_rate); } } -const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; } +const char *fge_engine_name(int kind) { + return kind == 2 ? "ZeroFG" : kind == 1 ? "DD-FG Native" : "LSFG Native"; +} const char *fge_build_info(void) { return g_build; } } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.h b/app/src/main/cpp/waylandcomp/src/framegen_engine.h index d52ce3ffd4..8295a930f3 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.h +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.h @@ -16,8 +16,9 @@ void fge_device_lost(void); void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd, VkDevice dev, VkQueue queue, uint32_t qfam, int features_enabled); int fge_caps_ok(int kind); -const char *fge_caps_reason(void); -int fge_format_ok(VkFormat fmt); +const char *fge_caps_reason(int kind); +int fge_format_ok(int kind, VkFormat fmt); +int fge_engine_available(int kind); int fge_start(int kind, const char *cache_path); void fge_stop(void); @@ -26,10 +27,22 @@ void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, f int model, int perf_preset); int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt); uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate); -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens); +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t w, uint32_t h, VkFormat fmt, uint64_t sequence, uint32_t gens); void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h); void fge_forget_targets(void); +void fge_set_layer_timing(int layer); +/* The phases the pacer chose for the next pair's generated frames (engines that can take any phase). */ +void fge_set_phases(const float *phases, uint32_t count); +/* The phase generated frame [index] of [count] shows. */ +float fge_phase(uint32_t index, uint32_t count); + +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases); +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns); +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns); +void fge_pacer_reset(void); void fge_telemetry(float *accepted, float *source_rate, float *thermal); const char *fge_engine_name(int kind); const char *fge_build_info(void); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c b/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c index 3d11228577..6dcf3a8d5b 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c @@ -10,9 +10,12 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica (void)gipa; (void)inst; (void)pd; (void)dev; (void)queue; (void)qfam; (void)features_enabled; } void fge_device_lost(void) {} +void zfg_discard_history_update(void) {} +void zfg_commit_history_update(void) {} int fge_caps_ok(int kind) { (void)kind; return 0; } -const char *fge_caps_reason(void) { return "frame-generation engines not built into this compositor"; } -int fge_format_ok(VkFormat fmt) { (void)fmt; return 0; } +const char *fge_caps_reason(int kind) { (void)kind; return "frame-generation engines not built into this compositor"; } +int fge_format_ok(int kind, VkFormat fmt) { (void)kind; (void)fmt; return 0; } +int fge_engine_available(int kind) { (void)kind; return 0; } int fge_start(int kind, const char *cache_path) { (void)kind; (void)cache_path; return -1; } void fge_stop(void) {} int fge_unavailable(void) { return 1; } @@ -24,16 +27,28 @@ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { (void)w; (void)h; (void) uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) { (void)capacity; (void)source_frames; (void)presented_rate; return 0; } -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) { - (void)cmd; (void)source; (void)w; (void)h; (void)gens; +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, uint32_t w, uint32_t h, + VkFormat fmt, uint64_t sequence, uint32_t gens) { + (void)cmd; (void)source; (void)source_view; (void)w; (void)h; (void)fmt; (void)sequence; (void)gens; } void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h) { (void)cmd; (void)g; (void)count; (void)img; (void)view; (void)w; (void)h; } void fge_forget_targets(void) {} +void fge_set_layer_timing(int layer) { (void)layer; } +void fge_set_phases(const float *phases, uint32_t count) { (void)phases; (void)count; } +float fge_phase(uint32_t index, uint32_t count) { return (float)(index + 1) / (float)(count + 1); } +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases) { + (void)multiplier; (void)period_ns; (void)vsync_ns; (void)issue_ns; (void)max_generated; (void)present_ns; (void)phases; + return 0; +} +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns) { (void)issue_ns; (void)done_ns; } +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns) { (void)planned_ns; (void)shown_ns; } +void fge_pacer_reset(void) {} void fge_telemetry(float *accepted, float *source_rate, float *thermal) { *accepted = 0.0f; *source_rate = 0.0f; *thermal = -1.0f; } -const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; } +const char *fge_engine_name(int kind) { return kind == 2 ? "ZeroFG" : kind == 1 ? "DD-FG Native" : "LSFG Native"; } const char *fge_build_info(void) { return "stub"; } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_jni.c b/app/src/main/cpp/waylandcomp/src/framegen_jni.c index e5a51456ed..e210597b8f 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_jni.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_jni.c @@ -14,6 +14,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenArmed(JNI vkp_framegen_set_armed(armed ? 1 : 0, (int)multiplier, (int)targetFps); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenPacer(JNIEnv *env, jclass clazz, jboolean on) { + (void)env; (void)clazz; + vkp_framegen_set_pacer(on ? 1 : 0); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLsfgCachePath(JNIEnv *env, jclass clazz, jstring path) { (void)clazz; diff --git a/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp new file mode 100644 index 0000000000..786c830964 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp @@ -0,0 +1,602 @@ +#include "framegen_zerofg.h" +#include "sc_layer.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#define ZFG_LOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "ZeroFG: " __VA_ARGS__) +#define ZFG_ERR(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "ZeroFG: " __VA_ARGS__) + +namespace { +PFN_vkGetInstanceProcAddr g_gipa = nullptr; +PFN_vkGetDeviceProcAddr g_gdpa = nullptr; +VkInstance g_instance = VK_NULL_HANDLE; +VkPhysicalDevice g_physical = VK_NULL_HANDLE; +VkDevice g_device = VK_NULL_HANDLE; +uint32_t g_api_version = VK_API_VERSION_1_0; +bool g_synchronization2 = false, g_extended_formats = false; +bool g_ready = false, g_supported = false, g_failed = false; +char g_reason[160] = "device has not been checked"; + +PFN_vkGetPhysicalDeviceMemoryProperties g_GetPhysicalDeviceMemoryProperties = nullptr; +PFN_vkGetPhysicalDeviceFormatProperties g_GetPhysicalDeviceFormatProperties = nullptr; +PFN_vkCreateImage g_CreateImage = nullptr; +PFN_vkDestroyImage g_DestroyImage = nullptr; +PFN_vkCreateImageView g_CreateImageView = nullptr; +PFN_vkDestroyImageView g_DestroyImageView = nullptr; +PFN_vkGetImageMemoryRequirements g_GetImageMemoryRequirements = nullptr; +PFN_vkAllocateMemory g_AllocateMemory = nullptr; +PFN_vkFreeMemory g_FreeMemory = nullptr; +PFN_vkBindImageMemory g_BindImageMemory = nullptr; +PFN_vkCmdPipelineBarrier g_CmdPipelineBarrier = nullptr; +PFN_vkCmdCopyImage g_CmdCopyImage = nullptr; +PFN_vkDeviceWaitIdle g_DeviceWaitIdle = nullptr; +VkPhysicalDeviceMemoryProperties g_memory_properties{}; + +std::unique_ptr g_interpolator; +VkImage g_history = VK_NULL_HANDLE; +VkImageView g_history_view = VK_NULL_HANDLE; +VkDeviceMemory g_history_memory = VK_NULL_HANDLE; +uint32_t g_width = 0, g_height = 0; +VkFormat g_format = VK_FORMAT_UNDEFINED; +bool g_history_layout_defined = false, g_history_valid = false; +uint64_t g_history_sequence = 0; +bool g_history_recorded_pending = false; +uint64_t g_history_recorded_sequence = 0; +std::array g_fallback_outputs{}; +VkImage g_current = VK_NULL_HANDLE; +VkImageView g_current_view = VK_NULL_HANDLE; +uint64_t g_current_sequence = 0; +bool g_pair_pending = false; + +// Pacing. The compositor presents a pair's generated frames and its real frame back to back in FIFO, +// so they reach the panel on consecutive refreshes right after the tick that drew them. +constexpr uint64_t kBreakNs = 250000000ull; +constexpr size_t kIntervalWindow = 8; +constexpr size_t kMinIntervals = 4; +constexpr double kSlotTolerance = 0.15; +uint32_t g_multiplier = 2; +float g_refresh_hz = 0.0f; +bool g_layer_timing = false; +// The phases the pacer chose for this pair (count 0: none, the timing above decides). +std::array g_external_phases{}; +uint32_t g_external_count = 0; +uint64_t g_last_sequence = 0; +uint64_t g_last_issue_ns = 0; +uint64_t g_pair_interval_ns = 0; +uint32_t g_prev_count = 0, g_pair_count = 0; +std::array g_intervals{}; +size_t g_interval_count = 0, g_interval_next = 0; + +uint64_t now_ns() { + return static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count()); +} + +void reset_pacing() { + g_last_issue_ns = 0; + g_pair_interval_ns = 0; + g_prev_count = g_pair_count = 0; + g_interval_count = g_interval_next = 0; +} + +uint64_t period_ns() { + return g_refresh_hz > 1.0f ? static_cast(1e9 / static_cast(g_refresh_hz)) : 0; +} + +uint64_t typical_interval_ns() { + if (g_interval_count < kMinIntervals) return 0; + std::array sorted = g_intervals; + std::sort(sorted.begin(), sorted.begin() + g_interval_count); + return sorted[g_interval_count / 2]; +} + +void note_sequence(uint64_t sequence) { + if (sequence == g_last_sequence) return; + const uint64_t now = now_ns(); + if (sequence < g_last_sequence) { + // The frame counter changed source (game frames vs compositor scenes): no pair across it. + g_history_valid = false; + g_history_sequence = 0; + reset_pacing(); + } else if (g_last_issue_ns && now > g_last_issue_ns) { + const uint64_t interval = now - g_last_issue_ns; + if (interval > kBreakNs) { + reset_pacing(); + } else { + g_pair_interval_ns = interval; + g_intervals[g_interval_next] = interval; + g_interval_next = (g_interval_next + 1) % kIntervalWindow; + g_interval_count = std::min(g_interval_count + 1, kIntervalWindow); + } + } + g_last_sequence = sequence; + g_last_issue_ns = now; +} + +// Generated frames a pair can show without its presents queueing past the next game frame: +// one refresh each, the real frame one more, all inside the game's typical frame interval. +uint32_t pair_capacity(uint32_t wanted) { + const uint64_t period = period_ns(); + const uint64_t typical = typical_interval_ns(); + if (!period || !typical) return wanted; + const double slots = std::floor(static_cast(typical) / static_cast(period) + kSlotTolerance); + return slots < 2.0 ? 0u : std::min(wanted, static_cast(slots) - 1u); +} + +// The scene layer (sc_layer.c) shows a group of [count] generated frames and then B, frame k of the group +// max(k, round(k * gap / (count + 1))) refreshes after the first, a group every game frame interval. +float layer_phase(uint32_t index, uint32_t count, uint64_t period) { + const float even = static_cast(index + 1) / static_cast(count + 1); + int64_t cadence_gap = 0; + int cadence_frames = 0; + sc_layer_cadence_info(&cadence_gap, &cadence_frames); + const uint64_t gap = cadence_gap > 0 ? static_cast(cadence_gap) : typical_interval_ns(); + const uint32_t group_frames = cadence_frames > static_cast(count) + ? static_cast(cadence_frames) : count + 1; + if (!gap) return even; + const int64_t slots = static_cast((gap + period / 2) / period); + if (slots < static_cast(group_frames)) return even; + const auto step = [&](uint32_t k) { + const int64_t s = static_cast((static_cast(k) * gap / group_frames + period / 2) / period); + return std::max(s, k); + }; + const double phase = static_cast(step(index) - step(count) + slots) / static_cast(slots); + return static_cast(std::clamp(phase, 0.05, 0.95)); +} + +// FIFO presents the generated group and B back-to-back; phase uses the measured real-frame span. +float pair_phase(uint32_t index, uint32_t count) { + if (g_external_count == count && index < count) return std::clamp(g_external_phases[index], 0.01f, 0.99f); + const float even = static_cast(index + 1) / static_cast(count + 1); + const uint64_t period = period_ns(); + if (!period) return even; + if (g_layer_timing) return layer_phase(index, count, period); + if (!g_pair_interval_ns) return even; + const double span = static_cast(g_pair_interval_ns) + + (static_cast(count) - static_cast(g_prev_count)) * static_cast(period); + if (span <= static_cast(period) * (count + 1)) return even; + const double phase = 1.0 - static_cast(count - index) * static_cast(period) / span; + return static_cast(std::clamp(phase, 0.05, 0.95)); +} + +void load_device_functions() { + if (g_gipa && g_instance) { + g_GetPhysicalDeviceMemoryProperties = + reinterpret_cast( + g_gipa(g_instance, "vkGetPhysicalDeviceMemoryProperties")); + g_GetPhysicalDeviceFormatProperties = + reinterpret_cast( + g_gipa(g_instance, "vkGetPhysicalDeviceFormatProperties")); + } + if (!g_gdpa || !g_device) return; +#define LOAD(name) g_##name = reinterpret_cast(g_gdpa(g_device, "vk" #name)) + LOAD(CreateImage); + LOAD(DestroyImage); + LOAD(CreateImageView); + LOAD(DestroyImageView); + LOAD(GetImageMemoryRequirements); + LOAD(AllocateMemory); + LOAD(FreeMemory); + LOAD(BindImageMemory); + LOAD(CmdPipelineBarrier); + LOAD(CmdCopyImage); + LOAD(DeviceWaitIdle); +#undef LOAD +} + +void clear_history_state() { + g_history_valid = false; + g_history_sequence = 0; + g_pair_pending = false; + g_current = VK_NULL_HANDLE; + g_current_view = VK_NULL_HANDLE; + g_current_sequence = 0; +} + +void destroy_history() { + if (g_device) { + if (g_history_view && g_DestroyImageView) g_DestroyImageView(g_device, g_history_view, nullptr); + if (g_history && g_DestroyImage) g_DestroyImage(g_device, g_history, nullptr); + if (g_history_memory && g_FreeMemory) g_FreeMemory(g_device, g_history_memory, nullptr); + } + g_history = VK_NULL_HANDLE; + g_history_view = VK_NULL_HANDLE; + g_history_memory = VK_NULL_HANDLE; + g_width = g_height = 0; + g_format = VK_FORMAT_UNDEFINED; + g_history_layout_defined = false; + clear_history_state(); +} + +uint32_t find_memory_type(uint32_t bits) { + uint32_t fallback = UINT32_MAX; + for (uint32_t i = 0; i < g_memory_properties.memoryTypeCount; ++i) { + if ((bits & (1u << i)) == 0) continue; + const auto flags = g_memory_properties.memoryTypes[i].propertyFlags; + if (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) return i; + if (fallback == UINT32_MAX) fallback = i; + } + return fallback; +} + +bool make_history(uint32_t width, uint32_t height, VkFormat format) { + if (!g_CreateImage || !g_GetImageMemoryRequirements || !g_AllocateMemory || + !g_BindImageMemory || !g_CreateImageView || !g_GetPhysicalDeviceMemoryProperties) { + std::snprintf(g_reason, sizeof(g_reason), "Vulkan image functions unavailable"); + return false; + } + VkImageCreateInfo image_info{}; + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = format; + image_info.extent = {width, height, 1}; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + if (g_CreateImage(g_device, &image_info, nullptr, &g_history) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not create temporal history image"); + return false; + } + + VkMemoryRequirements requirements{}; + g_GetImageMemoryRequirements(g_device, g_history, &requirements); + const uint32_t memory_index = find_memory_type(requirements.memoryTypeBits); + if (memory_index == UINT32_MAX) { + std::snprintf(g_reason, sizeof(g_reason), "no compatible memory for temporal history"); + destroy_history(); + return false; + } + VkMemoryAllocateInfo allocation{}; + allocation.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = memory_index; + if (g_AllocateMemory(g_device, &allocation, nullptr, &g_history_memory) != VK_SUCCESS || + g_BindImageMemory(g_device, g_history, g_history_memory, 0) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not allocate temporal history memory"); + destroy_history(); + return false; + } + + VkImageViewCreateInfo view_info{}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.image = g_history; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = format; + view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + if (g_CreateImageView(g_device, &view_info, nullptr, &g_history_view) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not create temporal history view"); + destroy_history(); + return false; + } + g_width = width; + g_height = height; + g_format = format; + g_history_layout_defined = false; + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; + clear_history_state(); + return true; +} + +void copy_current_to_history(VkCommandBuffer cmd, VkImage source, + uint32_t width, uint32_t height, uint64_t sequence) { + if (!g_history || !source || !g_CmdPipelineBarrier || !g_CmdCopyImage) return; + VkImageMemoryBarrier before{}; + before.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + const bool layout_defined = g_history_layout_defined || g_history_recorded_pending; + before.srcAccessMask = layout_defined ? VK_ACCESS_SHADER_READ_BIT : 0; + before.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + before.oldLayout = layout_defined ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED; + before.newLayout = VK_IMAGE_LAYOUT_GENERAL; + before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.image = g_history; + before.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, + layout_defined ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &before); + + VkImageCopy region{}; + region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.extent = {width, height, 1}; + g_CmdCopyImage(cmd, source, VK_IMAGE_LAYOUT_GENERAL, g_history, VK_IMAGE_LAYOUT_GENERAL, 1, ®ion); + + VkImageMemoryBarrier after{}; + after.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + after.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + after.newLayout = VK_IMAGE_LAYOUT_GENERAL; + after.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.image = g_history; + after.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 0, nullptr, 0, nullptr, 1, &after); + g_history_recorded_pending = true; + g_history_recorded_sequence = sequence; + g_pair_pending = false; +} + +void copy_current_to_output(VkCommandBuffer cmd, VkImage output, uint32_t width, uint32_t height) { + if (!g_current || !output || !g_CmdPipelineBarrier || !g_CmdCopyImage) return; + VkImageMemoryBarrier before{}; + before.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT; + before.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + before.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + before.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.image = output; + before.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, 1, &before); + VkImageCopy region{}; + region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.extent = {width, height, 1}; + g_CmdCopyImage(cmd, g_current, VK_IMAGE_LAYOUT_GENERAL, + output, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); + VkImageMemoryBarrier after{}; + after.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT; + after.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + after.newLayout = VK_IMAGE_LAYOUT_GENERAL; + after.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.image = output; + after.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + 0, 0, nullptr, 0, nullptr, 1, &after); +} +} // namespace + +extern "C" { +void zfg_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, + VkPhysicalDevice physical_device, VkDevice device, + uint32_t api_version, int synchronization2_enabled, + int extended_storage_formats_enabled) { + g_gipa = gipa; + g_instance = instance; + g_physical = physical_device; + g_device = device; + g_api_version = api_version; + g_synchronization2 = synchronization2_enabled != 0; + g_extended_formats = extended_storage_formats_enabled != 0; + g_gdpa = g_gipa && g_instance + ? reinterpret_cast(g_gipa(g_instance, "vkGetDeviceProcAddr")) + : nullptr; + load_device_functions(); + if (g_GetPhysicalDeviceMemoryProperties && g_physical) + g_GetPhysicalDeviceMemoryProperties(g_physical, &g_memory_properties); + g_ready = g_device != VK_NULL_HANDLE; + g_supported = g_ready && g_api_version >= VK_API_VERSION_1_3 && + g_synchronization2 && g_extended_formats; + g_failed = false; + std::snprintf(g_reason, sizeof(g_reason), "%s", g_supported ? "available" : + "requires Vulkan 1.3, synchronization2 and shaderStorageImageExtendedFormats"); +} + +void zfg_device_lost(void) { + g_interpolator.reset(); + destroy_history(); + g_gipa = nullptr; g_gdpa = nullptr; + g_instance = VK_NULL_HANDLE; g_physical = VK_NULL_HANDLE; g_device = VK_NULL_HANDLE; + g_ready = g_supported = g_failed = false; + g_synchronization2 = g_extended_formats = false; + g_api_version = VK_API_VERSION_1_0; + g_GetPhysicalDeviceMemoryProperties = nullptr; + g_GetPhysicalDeviceFormatProperties = nullptr; + g_CreateImage = nullptr; g_DestroyImage = nullptr; + g_CreateImageView = nullptr; g_DestroyImageView = nullptr; + g_GetImageMemoryRequirements = nullptr; g_AllocateMemory = nullptr; + g_FreeMemory = nullptr; g_BindImageMemory = nullptr; + g_CmdPipelineBarrier = nullptr; g_CmdCopyImage = nullptr; g_DeviceWaitIdle = nullptr; + g_memory_properties = {}; + std::snprintf(g_reason, sizeof(g_reason), "device lost"); +} + +int zfg_caps_ok(void) { return g_supported ? 1 : 0; } +const char *zfg_caps_reason(void) { return g_reason; } + +int zfg_start(void) { + if (!g_supported || !g_ready) return 0; + if (g_interpolator) return 1; + zerofg::CreateInfo info{}; + info.vulkan.instance = g_instance; + info.vulkan.physical_device = g_physical; + info.vulkan.device = g_device; + info.vulkan.get_instance_proc_addr = g_gipa; + info.mode = zerofg::Mode::kReallyZero; + info.backend = zerofg::Backend::kCompat; + info.frame_context_count = 4; + info.capabilities.effective_api_version = g_api_version; + info.capabilities.synchronization2_enabled = g_synchronization2; + info.capabilities.shader_storage_image_extended_formats_enabled = g_extended_formats; + zerofg::Status status = zerofg::Status::kSuccess; + g_interpolator = zerofg::Interpolator::Create(info, &status); + if (!g_interpolator) { + std::snprintf(g_reason, sizeof(g_reason), "interpolator creation failed (%d)", (int)status); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + g_failed = false; + ZFG_LOG("ReallyZero engine ready (Compat backend)"); + return 1; +} + +void zfg_stop(void) { + g_interpolator.reset(); + destroy_history(); + reset_pacing(); + g_last_sequence = 0; + g_failed = false; +} +int zfg_unavailable(void) { return g_failed || !g_interpolator ? 1 : 0; } + +int zfg_format_ok(VkFormat format) { + if (!g_supported || !g_GetPhysicalDeviceFormatProperties || format == VK_FORMAT_UNDEFINED) return 0; + VkFormatProperties input{}; + g_GetPhysicalDeviceFormatProperties(g_physical, format, &input); + const VkFormatFeatureFlags sampled = + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; + if ((input.optimalTilingFeatures & sampled) != sampled) return 0; + if (format == VK_FORMAT_A2B10G10R10_UNORM_PACK32) + return (input.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; + VkFormatProperties internal{}; + g_GetPhysicalDeviceFormatProperties(g_physical, VK_FORMAT_A2B10G10R10_UNORM_PACK32, &internal); + const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_BLIT_SRC_BIT; + return (input.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT) != 0 && + (internal.optimalTilingFeatures & needed) == needed; +} + +int zfg_prepare(uint32_t width, uint32_t height, VkFormat format) { + if (!g_interpolator || g_failed || !width || !height) return 0; + if (!zfg_format_ok(format)) { + std::snprintf(g_reason, sizeof(g_reason), "unsupported input/output format %d", (int)format); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + if (g_width == width && g_height == height && g_format == format && g_history) return 1; + if (g_DeviceWaitIdle) g_DeviceWaitIdle(g_device); + destroy_history(); + const zerofg::Status resized = g_interpolator->Resize(width, height, format, format); + if (resized != zerofg::Status::kSuccess) { + std::snprintf(g_reason, sizeof(g_reason), "resize failed (%d)", (int)resized); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + if (!make_history(width, height, format)) { + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + ZFG_LOG("prepared %ux%u format %d", width, height, (int)format); + return 1; +} + +void zfg_configure(uint32_t multiplier, float refresh_hz) { + g_multiplier = std::clamp(multiplier, 2, 4); + g_refresh_hz = refresh_hz > 1.0f ? refresh_hz : 0.0f; +} + +void zfg_set_layer_timing(int layer) { g_layer_timing = layer != 0; } + +void zfg_set_phases(const float *phases, uint32_t count) { + g_external_count = phases ? std::min(count, static_cast(g_external_phases.size())) : 0; + for (uint32_t i = 0; i < g_external_count; i++) g_external_phases[i] = phases[i]; +} + +float zfg_phase(uint32_t index, uint32_t count) { return pair_phase(index, count); } + +uint32_t zfg_plan(uint32_t capacity, uint64_t sequence) { + if (!g_interpolator || g_failed) return 0; + note_sequence(sequence); + if (!g_history_valid || sequence <= g_history_sequence || !g_pair_interval_ns) return 0; + return pair_capacity(std::min({capacity, 3u, g_multiplier - 1})); +} + +void zfg_telemetry(float *generated, float *source_rate) { + const uint64_t typical = typical_interval_ns(); + *generated = static_cast(g_pair_count); + *source_rate = typical ? static_cast(1e9 / static_cast(typical)) : 0.0f; +} + +void zfg_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t width, uint32_t height, VkFormat format, + uint64_t sequence, uint32_t generations) { + g_pair_pending = false; + g_fallback_outputs.fill(false); + if (!g_interpolator || g_failed || !source || !g_history || + format != g_format || width != g_width || height != g_height) return; + if (sequence > g_history_sequence) { + g_prev_count = g_pair_count; + g_pair_count = generations; + } + if (generations == 0 || !g_history_valid || sequence <= g_history_sequence) { + copy_current_to_history(cmd, source, width, height, sequence); + return; + } + if (!source_view) return; + g_current = source; + g_current_view = source_view; + g_current_sequence = sequence; + g_pair_pending = true; +} + +void zfg_generate(VkCommandBuffer cmd, uint32_t index, uint32_t count, + VkImage output, VkImageView output_view, uint32_t width, uint32_t height) { + if (!g_pair_pending || !g_interpolator || !g_history_valid || index >= count || !output || !output_view) return; + const float phase = pair_phase(index, count); + zerofg::Image previous{}; + previous.image = g_history; previous.view = g_history_view; + previous.layout = VK_IMAGE_LAYOUT_GENERAL; previous.format = g_format; + previous.width = g_width; previous.height = g_height; + previous.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + previous.sequence = g_history_sequence; + zerofg::Image current{}; + current.image = g_current; current.view = g_current_view; + current.layout = VK_IMAGE_LAYOUT_GENERAL; current.format = g_format; + current.width = g_width; current.height = g_height; + current.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + current.sequence = g_current_sequence; + zerofg::Image result{}; + result.image = output; result.view = output_view; + result.layout = VK_IMAGE_LAYOUT_GENERAL; result.format = g_format; + result.width = width; result.height = height; + result.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + + const zerofg::Status status = + g_interpolator->Interpolate(cmd, index, previous, current, phase, result); + if (status != zerofg::Status::kSuccess) { + ZFG_ERR("interpolation status %d; copying the real frame as fallback", (int)status); + g_fallback_outputs[index] = true; + copy_current_to_output(cmd, output, width, height); + } + if (index + 1 >= count) { + copy_current_to_history(cmd, g_current, width, height, g_current_sequence); + g_pair_pending = false; + } +} + +void zfg_commit_history_update(void) { + if (!g_history_recorded_pending) return; + g_history_layout_defined = true; + g_history_valid = true; + g_history_sequence = g_history_recorded_sequence; + g_history_recorded_pending = false; +} + +void zfg_discard_history_update(void) { + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; +} + +void zfg_forget_targets(void) { + g_pair_pending = false; + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; + g_history_valid = false; + g_history_sequence = 0; + reset_pacing(); +} +} // extern "C" diff --git a/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h new file mode 100644 index 0000000000..83c9c39e24 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h @@ -0,0 +1,38 @@ +#ifndef FRAMEGEN_ZEROFG_H +#define FRAMEGEN_ZEROFG_H +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +void zfg_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, + VkPhysicalDevice physical_device, VkDevice device, + uint32_t api_version, int synchronization2_enabled, + int extended_storage_formats_enabled); +void zfg_device_lost(void); +int zfg_caps_ok(void); +const char *zfg_caps_reason(void); +int zfg_start(void); +void zfg_stop(void); +int zfg_unavailable(void); +int zfg_format_ok(VkFormat format); +int zfg_prepare(uint32_t width, uint32_t height, VkFormat format); +void zfg_configure(uint32_t multiplier, float refresh_hz); +void zfg_set_layer_timing(int layer); +void zfg_set_phases(const float *phases, uint32_t count); +float zfg_phase(uint32_t index, uint32_t count); +uint32_t zfg_plan(uint32_t capacity, uint64_t sequence); +void zfg_telemetry(float *generated, float *source_rate); +void zfg_process(VkCommandBuffer command_buffer, VkImage source, VkImageView source_view, + uint32_t width, uint32_t height, VkFormat format, + uint64_t sequence, uint32_t generations); +void zfg_generate(VkCommandBuffer command_buffer, uint32_t index, uint32_t count, + VkImage output, VkImageView output_view, + uint32_t width, uint32_t height); +void zfg_forget_targets(void); +void zfg_commit_history_update(void); +void zfg_discard_history_update(void); +#ifdef __cplusplus +} +#endif +#endif diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index 018664f9c3..d38cc7ede5 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -58,6 +58,7 @@ static struct { void (*reparent)(ASurfaceTransaction *, ASurfaceControl *, ASurfaceControl *); void (*setOnComplete)(ASurfaceTransaction *, void *, sc_complete_fn); int (*prevReleaseFence)(ASurfaceTransactionStats *, ASurfaceControl *); + int (*presentFence)(ASurfaceTransactionStats *); void (*setFrameRate)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t); void (*setFrameRateStrategy)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t, int8_t); void (*setBufferDataSpace)(ASurfaceTransaction *, ASurfaceControl *, int32_t); @@ -102,6 +103,7 @@ static int load_api(void) { SYM(reparent, "ASurfaceTransaction_reparent"); SYM(setOnComplete, "ASurfaceTransaction_setOnComplete"); SYM(prevReleaseFence, "ASurfaceTransactionStats_getPreviousReleaseFenceFd"); + SYM(presentFence, "ASurfaceTransactionStats_getPresentFenceFd"); SYM(setFrameRate, "ASurfaceTransaction_setFrameRate"); SYM(setFrameRateStrategy, "ASurfaceTransaction_setFrameRateWithChangeStrategy"); SYM(setBufferDataSpace, "ASurfaceTransaction_setBufferDataSpace"); @@ -187,6 +189,8 @@ struct layer { static struct layer g_layers[SC_LAYER_COUNT]; static void apply_frame_rate(ASurfaceTransaction *tx, struct layer *l); static void coverage_text(const struct layer *l, char *out, size_t n); +static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd); +static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent); static int g_layers_ready; static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static int g_pending_cb; @@ -263,7 +267,33 @@ static int64_t cadence_target(int64_t now, int64_t earliest, int64_t period) { return target; } +static int64_t g_planned_next_ns; + +void sc_layer_set_planned(int64_t present_ns) { + pthread_mutex_lock(&g_lock); + g_planned_next_ns = present_ns; + pthread_mutex_unlock(&g_lock); +} + +void sc_layer_timeline(int64_t *present_ns, int64_t *period_ns) { + pthread_mutex_lock(&g_timeline_lock); + *present_ns = g_timeline_present_ns; + *period_ns = g_timeline_period_ns; + pthread_mutex_unlock(&g_timeline_lock); +} + +void sc_layer_cadence_info(int64_t *gap_ns, int *group_frames) { + if (gap_ns) *gap_ns = g_cadence_gap_ns; + if (group_frames) *group_frames = g_group_frames; +} + static void apply_present_time(ASurfaceTransaction *tx, int game) { + pthread_mutex_lock(&g_lock); + const int64_t planned = game ? g_planned_next_ns : 0; + if (game) { + g_planned_next_ns = 0; + } + pthread_mutex_unlock(&g_lock); if (!api.setDesiredPresentTime) return; pthread_mutex_lock(&g_timeline_lock); const int64_t present = g_timeline_present_ns, deadline = g_timeline_deadline_ns, period = g_timeline_period_ns; @@ -283,6 +313,9 @@ static void apply_present_time(ASurfaceTransaction *tx, int game) { target = cadence_target(now, target, period); } if (game && g_group_frames > 1 && ++g_group_index >= g_group_frames) { g_group_index = 0; g_group_frames = 1; } + if (planned > 0) { + target = planned; + } api.setDesiredPresentTime(tx, target - period / 2); } @@ -721,9 +754,15 @@ static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct v static ARect g_game_src, g_game_dst; static int g_game_geo_known; +static void note_game_geometry(const int r[8]) { + g_game_src = (ARect){r[0], r[1], r[2], r[3]}; + g_game_dst = (ARect){r[4], r[5], r[6], r[7]}; + g_game_geo_known = 1; +} + static void apply_geometry(ASurfaceTransaction *tx, struct layer *l, const int r[8]) { ARect srcR = {r[0], r[1], r[2], r[3]}, dstR = {r[4], r[5], r[6], r[7]}; - if (l == &g_layers[SC_LAYER_GAME]) { g_game_src = srcR; g_game_dst = dstR; g_game_geo_known = 1; } + if (l == &g_layers[SC_LAYER_GAME]) note_game_geometry(r); if (!l->geo_valid || memcmp(&srcR, &l->geo_src, sizeof(srcR)) || memcmp(&dstR, &l->geo_dst, sizeof(dstR))) { api.setGeometry(tx, l->sc, &srcR, &dstR, 0 ); l->geo_src = srcR; l->geo_dst = dstR; l->geo_valid = 1; @@ -885,7 +924,9 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d int translucent) { struct slot *s = &l->slots[idx]; ASurfaceTransaction *tx = api.txCreate(); - if (!tx) return -1; + if (!tx) { + return -1; + } const int was_shown = l->shown; const int32_t ds_applied = l->ds_applied; const uint32_t md_applied = l->md_applied; @@ -998,19 +1039,40 @@ unavailable: } int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw, - const struct droiddeck_color *color) { + const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown) { struct layer *l = layer_of(SC_LAYER_GAME); + *over_shown = 0; if (!src || ensure_sc(l) != 0) return -1; int sw = vkp_image_width(src), sh = vkp_image_height(src); int r[8]; int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r); if (g < 0) return -1; - if (g == 0) { sc_layer_hide(); return 0; } + int og[8]; + if (over && !vkp_map_draw(over, og)) over = NULL; + if (g == 0) { + sc_layer_hide(); + if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1; + return 0; + } - int wait_fd; - int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd); - if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; } - if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1; + struct vkp_blit blits[2] = {{.src = src, .wait_fd = -1}, {.src = over ? over->img : NULL, .wait_fd = -1}}; + int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &blits[0].wait_fd); + if (idx < 0) { + log_drop(l); + if (g_alloc_failed) return -1; + if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1; + return 0; + } + blits[0].dst = l->slots[idx].img; + struct layer *ol = layer_of(SC_LAYER_OVERLAY); + int over_idx = -1; + if (over) { + note_game_geometry(r); + const int taken = overlay_slot(ol, over->img, &over_idx, &blits[1].wait_fd); + *over_shown = taken < 0 ? -1 : 1; + if (taken > 0) blits[1].dst = ol->slots[over_idx].img; + } + if (vkp_blit_images(blits, over_idx >= 0 ? 2 : 1) != 0) return -1; if (present_slot(l, idx, r, color, 0) != 0) return -1; if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8); if (!l->first_logged) { @@ -1020,6 +1082,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru pool_kind(l->pool_modifier), l->pool_n); } vkp_signal_first_frame(); + if (over_idx >= 0 && overlay_shown(ol, over_idx, og, over->blend) != 0) *over_shown = -1; return 0; } @@ -1084,7 +1147,7 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const if (!mapped) { vkp_pass_abort(); sc_layer_hide(); return 0; } idx[VKP_FG_MAX_GENERATIONS] = deep ? take_hdr_slot(l, rw, rh, &first_fd) : take_free_slot(l, rw, rh, AHB_RGBA8, &first_fd); - if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } + if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); vkp_framegen_pacer_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } pthread_mutex_lock(&g_lock); l->slots[idx[VKP_FG_MAX_GENERATIONS]].busy = 1; pthread_mutex_unlock(&g_lock); @@ -1106,13 +1169,18 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const if (!have_fd) { first_fd = fd; have_fd = 1; } } if (vkp_pass_copy_generated(dst, m, real, first_fd) != 0) { + vkp_framegen_pacer_abort(); slots_idle(l, idx, 0, m); if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); return -1; } g_group_frames = m + 1; for (int k = 0; k < m; k++) { + int64_t planned; + vkp_framegen_output_planned(k, m, &planned); + sc_layer_set_planned(planned); if (present_slot(l, idx[k], r, color, 0) == 0) continue; + vkp_framegen_pacer_abort(); slots_idle(l, idx, k, m); if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); g_group_index = 0; @@ -1121,7 +1189,11 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const } vkp_framegen_presented(m); if (real) { + int64_t planned; + vkp_framegen_output_planned(m, m, &planned); + sc_layer_set_planned(planned); if (present_slot(l, idx[VKP_FG_MAX_GENERATIONS], r, color, 0) != 0) { + vkp_framegen_pacer_abort(); slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); g_group_index = 0; g_group_frames = 1; @@ -1209,17 +1281,19 @@ int sc_layer_overlay_affordable(void) { return ok; } -int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) { - struct layer *l = layer_of(SC_LAYER_OVERLAY); - if (!src || !geo) return -1; +static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd) { + *wait_fd = -1; + if (!src) return -1; if (!sc_layer_overlay_affordable()) return -1; if (ensure_sc(l) != 0) return -1; int sw = vkp_image_width(src), sh = vkp_image_height(src); if (sw <= 0 || sh <= 0) return -1; - int wait_fd; - int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd); - if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; } - if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1; + *idx = take_free_slot(l, sw, sh, AHB_RGBA8, wait_fd); + if (*idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; } + return 1; +} + +static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent) { if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1; if (!l->first_logged) { l->first_logged = 1; @@ -1228,6 +1302,18 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl return 0; } +int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) { + struct layer *l = layer_of(SC_LAYER_OVERLAY); + if (!geo) return -1; + int idx; + struct vkp_blit blit = {.src = src, .wait_fd = -1}; + const int taken = overlay_slot(l, src, &idx, &blit.wait_fd); + if (taken <= 0) return taken; + blit.dst = l->slots[idx].img; + if (vkp_blit_images(&blit, 1) != 0) return -1; + return overlay_shown(l, idx, geo, translucent); +} + static int hide_layer(struct layer *l) { if (!l->sc || !l->shown || api.state != 1) return 0; ASurfaceTransaction *tx = api.txCreate(); diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.h b/app/src/main/cpp/waylandcomp/src/sc_layer.h index 24a24fc25e..a7977378fa 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.h +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.h @@ -4,6 +4,10 @@ #include #include +#ifdef __cplusplus +extern "C" { +#endif + struct vkp_image; struct vkp_draw; struct droiddeck_color; @@ -22,7 +26,7 @@ void sc_layer_hdr_symbols(char *out, size_t size); int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw, - const struct droiddeck_color *color); + const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown); int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h); int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf, @@ -51,7 +55,16 @@ void sc_layer_window_gone(void); void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even); +/* The refresh the next game-layer frame is timed for, instead of the layer's own spacing (0: the layer's). */ +void sc_layer_set_planned(int64_t present_ns); +/* The display's frame timeline: the next expected present and the refresh period (0 until known). */ +void sc_layer_timeline(int64_t *present_ns, int64_t *period_ns); +void sc_layer_cadence_info(int64_t *gap_ns, int *group_frames); unsigned sc_layer_frames_take(void); unsigned sc_layer_drops_take(void); +#ifdef __cplusplus +} +#endif + #endif diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index faa89e89b5..ab0d50bea6 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -7,6 +7,7 @@ #include "effects_chain.h" #include "cardboard.h" #include "framegen_bridge.h" +#include "framegen_zerofg.h" #include "hdr_compose.h" #include "blend_pass.h" #include "gpu_busy.h" @@ -20,6 +21,8 @@ #include #include #include +#include +#include #include #include #include @@ -602,6 +605,10 @@ static void update_map(int scene_w, int scene_h) { float min_y = (float)g_map.ry + g_map.rh - image_h; if (g_map.off_y < min_y) g_map.off_y = min_y; if (g_map.off_y > g_map.ry) g_map.off_y = (float)g_map.ry; + } else if (align == VKP_ALIGN_PICTURE_TOP) { + g_map.off_y = 0; + } else if (align == VKP_ALIGN_PICTURE_BOTTOM) { + g_map.off_y = H - image_h; } else { g_map.off_y = (float)g_map.ry + (g_map.rh - image_h) * 0.5f; } @@ -2759,6 +2766,21 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i pass_n = 1; overlay_start = source_end; } + const int upscale_w = (int)(scene_w * g_map.kx + 0.5f); + const int upscale_h = (int)(scene_h * g_map.ky + 0.5f); + const int post_upscale = fx && fg && !hf && !cb && vkp_effects_upscaling() && + vkp_effects_prepare_generated() && + (upscale_w > input_w || upscale_h > input_h); + if (post_upscale) { + static int last_input_w, last_input_h, last_output_w, last_output_h; + if (input_w != last_input_w || input_h != last_input_h || + upscale_w != last_output_w || upscale_h != last_output_h) { + droiddeck_log("framegen", "post-upscale: interpolate %dx%d, spatial filter each present to %dx%d", + input_w, input_h, upscale_w, upscale_h); + last_input_w = input_w; last_input_h = input_h; + last_output_w = upscale_w; last_output_h = upscale_h; + } + } const int deep = hf && n > 0 && fg && g_swap_is_hdr && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) && ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | @@ -2878,6 +2900,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (!(pass && fx)) release_external_client_draws(cmd, draws, n); int ngen = 0; + int history_staged = 0; VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE}; VkImage result = scene_img; int rw = input_w, rh = input_h; @@ -2894,8 +2917,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (fx) { int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); if (fg && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } + if (post_upscale) { mapped_w = input_w; mapped_h = input_h; } vkp_effects_set_formats(scene_fmt, scene_fmt, hdr_how == 1 || hdr_unconverted); - result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh); + result = post_upscale + ? vkp_effects_run_before_generated(cmd, scene_img, input_w, input_h, &rw, &rh) + : vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh); effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h, draws ? draws + overlay_start : NULL, n - overlay_start); release_external_client_draws(cmd, draws, n); @@ -2913,12 +2939,19 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i 0, 0, NULL, 0, NULL, 1, &b_general); if (fg) { + vkp_framegen_set_layer_timing(0); + history_staged = 1; ngen = vkp_framegen_run(cmd, result, VK_NULL_HANDLE, rw, rh, scene_fmt, gens); if (ngen < 0) ngen = 0; if (ngen > VKP_FG_MAX_GENERATIONS) ngen = VKP_FG_MAX_GENERATIONS; } - record_screen_blit(cmd, ngen ? gens[0] : result, rw, rh, scene_w, scene_h, img, blit_filter, cb); + VkImage screen = ngen ? gens[0] : result; + int screen_w = rw, screen_h = rh; + if (post_upscale) + screen = vkp_effects_run_generated(cmd, screen, rw, rh, upscale_w, upscale_h, + 0, &screen_w, &screen_h); + record_screen_blit(cmd, screen, screen_w, screen_h, scene_w, scene_h, img, blit_filter, cb); } g_vk.EndCommandBuffer(cmd); @@ -2933,7 +2966,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i /* Teardown may have retained this frame's pending work, or * acquire may have reported real device loss. Neither permits * a completion-marker submit or another fence wait. */ - if (g_dev_state != 1) return -1; + if (g_dev_state != 1) { + if (history_staged) zfg_discard_history_update(); + return -1; + } droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents); pr = VK_ERROR_OUT_OF_DATE_KHR; break; @@ -2942,7 +2978,12 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i VkCommandBuffer ck = g_cmds[k]; g_vk.ResetCommandBuffer(ck, 0); g_vk.BeginCommandBuffer(ck, &bi); - record_screen_blit(ck, k < ngen ? gens[k] : result, rw, rh, scene_w, scene_h, img, blit_filter, cb); + VkImage screen = k < ngen ? gens[k] : result; + int screen_w = rw, screen_h = rh; + if (post_upscale) + screen = vkp_effects_run_generated(ck, screen, rw, rh, upscale_w, upscale_h, + k, &screen_w, &screen_h); + record_screen_blit(ck, screen, screen_w, screen_h, scene_w, scene_h, img, blit_filter, cb); g_vk.EndCommandBuffer(ck); } const int last = (k + 1 == presents); @@ -2952,6 +2993,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (img >= g_rnd_count || !g_rnds[img]) { droiddeck_log("error", "present: image index %u exceeds semaphore count %u", img, g_rnd_count); + if (history_staged) zfg_discard_history_update(); destroy_swapchain(); return -1; } @@ -2960,12 +3002,17 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i .pCommandBuffers = &g_cmds[k], .signalSemaphoreCount = 1, .pSignalSemaphores = &g_rnds[img]}; VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, last ? g_fence : VK_NULL_HANDLE); if (qr != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); if (qr == VK_ERROR_DEVICE_LOST) device_lost("submit"); else LOGE("present: submit %d/%d failed (%d)", k + 1, presents, (int)qr); if (g_dev_state != -2) destroy_swapchain(); return -1; } fence_submitted = last; + if (k == 0 && history_staged) { + zfg_commit_history_update(); + history_staged = 0; + } VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .waitSemaphoreCount = 1, .pWaitSemaphores = &g_rnds[img], .swapchainCount = 1, .pSwapchains = &g_swapchain, .pImageIndices = &img}; @@ -2973,21 +3020,38 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i pr = g_vk.QueuePresentKHR(g_queue, &pi); perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres); if (k < ngen) presented_gen++; - if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; } + if (pr == VK_ERROR_DEVICE_LOST) { + if (history_staged) zfg_discard_history_update(); + device_lost("present"); + return -1; + } if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break; } if (!fence_submitted) { VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO}; VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence); if (marker != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit"); else quarantine_pending_work(marker, "frame completion submit"); return -1; /* no fence was submitted; never wait on its unsignalled state */ } + if (history_staged) { + zfg_discard_history_update(); + history_staged = 0; + } } VkResult fr = timed_wait(g_fence, UINT64_MAX); - if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; } - if (fr != VK_SUCCESS) return -1; + if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { + if (history_staged) zfg_discard_history_update(); + device_lost("present"); + return -1; + } + if (fr != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); + return -1; + } + vkp_effects_release_generated_sources(); if (fg) vkp_framegen_presented(presented_gen); if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) { droiddeck_log("gpu", "screen surface %s on present: rebuilding the swapchain", vk_result_name(pr)); @@ -3133,8 +3197,38 @@ static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_la 0, 0, NULL, 0, NULL, 1, &release); } -int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { - if (!src || src->blit_dst || !dst || !dst->blit_dst || dev_init() != 0) { +static int merge_wait_fds(int a, int b) { + if (a < 0) return b; + if (b < 0) return a; + struct sync_merge_data m = {.name = "droiddeck-layer-copy", .fd2 = b}; + if (ioctl(a, SYNC_IOC_MERGE, &m) == 0) { + close(a); + close(b); + return m.fence; + } + struct pollfd p = {.fd = b, .events = POLLIN}; + int r; + do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); + close(b); + if (r != 0) return a; + p.fd = a; + do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); + close(a); + return -2; +} + +int vkp_blit_images(const struct vkp_blit *blits, int n) { + int wait_fd = -1; + for (int i = 0; i < n; i++) { + if (wait_fd == -2) { if (blits[i].wait_fd >= 0) close(blits[i].wait_fd); continue; } + wait_fd = merge_wait_fds(wait_fd, blits[i].wait_fd); + } + int valid = n > 0 && wait_fd != -2; + for (int i = 0; valid && i < n; i++) { + const struct vkp_image *src = blits[i].src, *dst = blits[i].dst; + if (!src || src->blit_dst || !dst || !dst->blit_dst) valid = 0; + } + if (!valid || dev_init() != 0) { if (wait_fd >= 0) close(wait_fd); return -1; } @@ -3147,32 +3241,35 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(g_cmd, &bi); - stage_linear_dmabuf(g_cmd, src); - struct vkp_external_client_barrier_pair src_pair; - const int src_external = vkp_external_client_barrier_pair( - src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair); - VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){ - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}; - if (!src_external) { - acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED; - acq.newLayout = VK_IMAGE_LAYOUT_GENERAL; - acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - src->in_general = 1; + for (int i = 0; i < n; i++) { + struct vkp_image *src = blits[i].src, *dst = blits[i].dst; + stage_linear_dmabuf(g_cmd, src); + struct vkp_external_client_barrier_pair src_pair; + const int src_external = vkp_external_client_barrier_pair( + src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair); + VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}; + if (!src_external) { + acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED; + acq.newLayout = VK_IMAGE_LAYOUT_GENERAL; + acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + src->in_general = 1; + } + g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq); + int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h; + VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .srcOffsets = {{0, 0, 0}, {bw, bh, 1}}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .dstOffsets = {{0, 0, 0}, {bw, bh, 1}}}; + blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, + dst, &blit, VK_FILTER_NEAREST); + release_external_client_image(g_cmd, src); } - g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq); - int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h; - VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {bw, bh, 1}}, - .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .dstOffsets = {{0, 0, 0}, {bw, bh, 1}}}; - blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, - dst, &blit, VK_FILTER_NEAREST); - release_external_client_image(g_cmd, src); g_vk.EndCommandBuffer(g_cmd); VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; @@ -3305,6 +3402,9 @@ static struct { int active; VkImage result; int rw, rh; + /* The layer buffers' size: rw x rh, or the spatial filter's output when it runs on each frame after generation. */ + int ow, oh; + int post_upscale; int ngen; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; @@ -3444,10 +3544,29 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw } int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); + g_pass.post_upscale = generate && !hf && vkp_effects_active() && vkp_effects_upscaling() && + vkp_effects_prepare_generated() && (mapped_w > input_w || mapped_h > input_h); + if (g_pass.post_upscale) { + static int last_input_w, last_input_h, last_output_w, last_output_h; + if (input_w != last_input_w || input_h != last_input_h || mapped_w != last_output_w || mapped_h != last_output_h) { + droiddeck_log("framegen", "post-upscale on the display layer: interpolate %dx%d, spatial filter each " + "frame to %dx%d", input_w, input_h, mapped_w, mapped_h); + last_input_w = input_w; last_input_h = input_h; + last_output_w = mapped_w; last_output_h = mapped_h; + } + } if (generate && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } g_pass.rw = input_w; g_pass.rh = input_h; - g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, - &g_pass.rw, &g_pass.rh); + if (g_pass.post_upscale) { + g_pass.ow = (int)(scene_w * g_map.kx + 0.5f); + g_pass.oh = (int)(scene_h * g_map.ky + 0.5f); + g_pass.result = vkp_effects_run_before_generated(cmd, scene_img, input_w, input_h, &g_pass.rw, &g_pass.rh); + } else { + g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, + &g_pass.rw, &g_pass.rh); + g_pass.ow = g_pass.rw; + g_pass.oh = g_pass.rh; + } effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h, draws ? draws + overlay_start : NULL, n - overlay_start); release_external_client_draws(cmd, draws, n); @@ -3462,38 +3581,45 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, NULL, 0, NULL, 1, &b); + vkp_framegen_set_layer_timing(1); int ngen = vkp_framegen_run(cmd, g_pass.result, VK_NULL_HANDLE, g_pass.rw, g_pass.rh, scene_fmt, g_pass.gens); if (ngen < 0) ngen = 0; g_pass.ngen = ngen > VKP_FG_MAX_GENERATIONS ? VKP_FG_MAX_GENERATIONS : ngen; } g_pass.active = 1; - if (rw) *rw = g_pass.rw; - if (rh) *rh = g_pass.rh; + if (rw) *rw = g_pass.ow; + if (rh) *rh = g_pass.oh; return 0; } static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp_image *const *dsts, int n, int wait_fd) { - if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; } + if (!g_pass.active) { zfg_discard_history_update(); if (wait_fd >= 0) close(wait_fd); return -1; } g_pass.active = 0; - if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; } + if (g_dev_state != 1) { zfg_discard_history_update(); if (wait_fd >= 0) close(wait_fd); return -1; } VkCommandBuffer cmd = g_cmds[0]; for (int i = 0; i < n; i++) { if (dsts[i] && dsts[i]->blit_dst) continue; if (wait_fd >= 0) close(wait_fd); g_vk.EndCommandBuffer(cmd); + zfg_discard_history_update(); return -1; } const int gpu_wait = take_wait_fd(wait_fd); - if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; } + if (gpu_wait < 0) { zfg_discard_history_update(); g_vk.EndCommandBuffer(cmd); return -1; } + const int post_upscale = g_pass.post_upscale && src_layout == VK_IMAGE_LAYOUT_GENERAL; for (int i = 0; i < n; i++) { struct vkp_image *dst = dsts[i]; + VkImage src = srcs[i]; + int sw = g_pass.rw, sh = g_pass.rh; + if (post_upscale) + src = vkp_effects_run_generated(cmd, src, g_pass.rw, g_pass.rh, g_pass.ow, g_pass.oh, i, &sw, &sh); VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, + .srcOffsets = {{0, 0, 0}, {sw, sh, 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; - blit_to_layer(cmd, srcs[i], src_layout, dst, &blit, - (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); + blit_to_layer(cmd, src, src_layout, dst, &blit, + (sw == dst->w && sh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); } g_vk.EndCommandBuffer(cmd); @@ -3504,13 +3630,17 @@ static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp g_vk.ResetFences(g_dev, 1, &g_fence); VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence); if (qr != VK_SUCCESS) { + zfg_discard_history_update(); if (qr == VK_ERROR_DEVICE_LOST) device_lost("layer pass"); else LOGE("layer: effects pass submit failed (%d)", (int)qr); return -1; } + zfg_commit_history_update(); VkResult fr = timed_wait(g_fence, 1000000000ULL); if (fr == VK_ERROR_DEVICE_LOST) { device_lost("layer pass"); return -1; } if (fr != VK_SUCCESS) { LOGE("layer: effects pass fence wait -> %s", vk_result_name(fr)); return -1; } + if (post_upscale) vkp_effects_release_generated_sources(); + vkp_framegen_completed(); return 0; } @@ -3528,6 +3658,7 @@ int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_ima } void vkp_pass_abort(void) { + zfg_discard_history_update(); if (!g_pass.active) return; g_pass.active = 0; if (g_dev_state == 1) diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.h b/app/src/main/cpp/waylandcomp/src/vk_present.h index bc35ac8b49..f7bfaf781f 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.h +++ b/app/src/main/cpp/waylandcomp/src/vk_present.h @@ -105,7 +105,11 @@ int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int *rw, int *rh); -int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd); +struct vkp_blit { + struct vkp_image *src, *dst; + int wait_fd; +}; +int vkp_blit_images(const struct vkp_blit *blits, int n); int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px); int vkp_update_map(int scene_w, int scene_h); int vkp_map_draw(const struct vkp_draw *d, int out[8]); diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index d070b8fd6f..6d8754e4e5 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -68,6 +68,7 @@ static jmethodID g_on_compositor_frame; static jmethodID g_on_game_program; static jmethodID g_on_pointer_lock; static jmethodID g_on_clipboard; +static jmethodID g_on_text_input_fallback; static jmethodID g_on_text_input; static jmethodID g_on_overlay_planes; static jmethodID g_on_refresh_target; @@ -92,6 +93,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; } g_on_pointer_lock = (*env)->GetStaticMethodID(env, g_compositor_cls, "onPointerLock", "(ZII)V"); g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V"); + g_on_text_input_fallback = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInputFallback", + "([BI)Z"); g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput", "(ZLjava/lang/String;IIII)V"); g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V"); @@ -203,6 +206,20 @@ void droiddeck_on_clipboard_text(const char *utf8, int len) { (*env)->DeleteLocalRef(env, arr); } +int droiddeck_on_text_input_fallback(const char *utf8, int len, int token) { + JNIEnv *env; + if (len <= 0 || token <= 0 || !utf8 || !g_compositor_cls || !g_on_text_input_fallback || !(env = thread_env())) + return 0; + jbyteArray arr = (*env)->NewByteArray(env, len); + if (!arr) { (*env)->ExceptionClear(env); return 0; } + (*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte *)utf8); + jboolean accepted = (*env)->CallStaticBooleanMethod(env, g_compositor_cls, g_on_text_input_fallback, arr, + (jint)token); + if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); accepted = JNI_FALSE; } + (*env)->DeleteLocalRef(env, arr); + return accepted == JNI_TRUE ? 1 : 0; +} + void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h) { JNIEnv *env; if (!g_compositor_cls || !g_on_text_input || !(env = thread_env())) return; @@ -376,6 +393,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey( droiddeck_wayland_send_key(evdev, state); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKeyOrdered( + JNIEnv *env, jclass clazz, jint evdev, jint state) { + droiddeck_host_key(evdev, state); +} + +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSelectGameField( + JNIEnv *env, jclass clazz, jboolean copy) { + droiddeck_host_select_game_field(copy); +} + JNIEXPORT jboolean JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFocusTakesTouch( JNIEnv *env, jclass clazz) { @@ -807,6 +836,15 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommit(JNIE free(buf); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommitAndSubmit( + JNIEnv *env, jclass clazz, jbyteArray utf8) { + int len; + char *buf = dup_bytes(env, utf8, &len); + if (buf && len) droiddeck_host_text_commit_and_submit(buf, len); + free(buf); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputPreedit(JNIEnv *env, jclass clazz, jbyteArray utf8, jint cursorBegin, jint cursorEnd) { @@ -821,6 +859,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE droiddeck_host_text_delete(before, after); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompleteTextInputFallback( + JNIEnv *env, jclass clazz, jint token, jint result) { + droiddeck_host_text_input_fallback_complete(token, result); +} + extern void adrenotools_set_turbo(bool turbo); JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) { @@ -872,3 +916,42 @@ JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) { return (jint)droiddeck_stream_frames(); } + + +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE +extern int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path, + uint64_t dev, uint64_t ino, uint64_t receipt); +extern void droiddeck_frame_worker_revoke(int owner, int pid); +#endif + +JNIEXPORT jboolean JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeEnabled(JNIEnv *env, jclass c) { +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + return JNI_TRUE; +#else + return JNI_FALSE; +#endif +} + +JNIEXPORT jboolean JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeGrant(JNIEnv *env, jclass c, + jint owner, jint pid, jlong expires, jstring path, jlong dev, jlong ino, jlong start_ticks) { +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + if (!path || expires <= 0 || ino <= 0 || start_ticks <= 0) return JNI_FALSE; + const char *name = (*env)->GetStringUTFChars(env, path, NULL); + if (!name) return JNI_FALSE; + int granted = droiddeck_frame_worker_grant(owner, pid, (uint64_t)expires, name, (uint64_t)dev, (uint64_t)ino, (uint64_t)start_ticks); + (*env)->ReleaseStringUTFChars(env, path, name); + return granted ? JNI_TRUE : JNI_FALSE; +#else + return JNI_FALSE; +#endif +} + +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeRevoke(JNIEnv *env, jclass c, + jint owner, jint pid) { +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + droiddeck_frame_worker_revoke(owner, pid); +#endif +} diff --git a/app/src/main/cpp/waylandcomp/src/wl_text_input.c b/app/src/main/cpp/waylandcomp/src/wl_text_input.c index 8b0ade227d..aaeff2de99 100644 --- a/app/src/main/cpp/waylandcomp/src/wl_text_input.c +++ b/app/src/main/cpp/waylandcomp/src/wl_text_input.c @@ -10,6 +10,12 @@ #ifndef KEY_DELETE #define KEY_DELETE 111 #endif +#ifndef KEY_ENTER +#define KEY_ENTER 28 +#endif +#ifndef KEY_TAB +#define KEY_TAB 15 +#endif static struct wl_display *g_disp; @@ -203,16 +209,43 @@ static int32_t utf8_offset(const char *s, size_t len, int chars) { return (int32_t)i; } -void text_input_host_commit(const char *utf8, size_t len) { +static int control_evdev(unsigned char c) { + switch (c) { + case '\r': case '\n': return KEY_ENTER; + case '\b': return KEY_BACKSPACE; + case 0x7f: return KEY_DELETE; + case '\t': return KEY_TAB; + default: return -1; + } +} + +static int all_controls(const char *utf8, size_t len) { + for (size_t i = 0; i < len; i++) + if (control_evdev((unsigned char)utf8[i]) < 0) return 0; + return 1; +} + +int text_input_host_commit(const char *utf8, size_t len) { struct text_input *ti = active_input(); if (!ti) { - droiddeck_log("text-input", "typed text (%zu chars) dropped: no program accepts text input", utf8_chars(utf8, len)); - return; + droiddeck_log("text-input", "typed text (%zu chars): no program accepts Wayland text input", utf8_chars(utf8, len)); + return 0; + } + if (len > 0 && all_controls(utf8, len)) { + /* Keep editing keys on the compositor queue so they cannot overtake text commits. */ + for (size_t i = 0; i < len; i++) { + int code = control_evdev((unsigned char)utf8[i]); + droiddeck_inject_key(code, 1); + droiddeck_inject_key(code, 0); + } + droiddeck_log("text-input", "injected %zu soft control(s) to %s", len, ti_program(ti)); + return 1; } if (ti->has_preedit) { zwp_text_input_v3_send_preedit_string(ti->res, "", 0, 0); ti->has_preedit = 0; } zwp_text_input_v3_send_commit_string(ti->res, utf8); zwp_text_input_v3_send_done(ti->res, ti->serial); droiddeck_log("text-input", "committed %zu chars to %s", utf8_chars(utf8, len), ti_program(ti)); + return 1; } void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end) { diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 53a0c89298..f91157dd41 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -20,6 +20,10 @@ class App : Application() { override fun onCreate() { super.onCreate() + if (android.os.Build.VERSION.SDK_INT >= 28 && + com.droiddeck.launcher.runtime.GuestWorker.isWorkerProcess(this, Application.getProcessName())) return + if (android.os.Build.VERSION.SDK_INT >= 28 && Application.getProcessName() == packageName) + com.droiddeck.launcher.runtime.GuestWorkers.attach(this) com.droiddeck.launcher.runtime.NativeGuest.init(this) com.droiddeck.launcher.session.Onboarding.attach(this) Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start() diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 293b75fea8..8c9657f1f5 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -25,6 +25,7 @@ import android.widget.EditText import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @@ -192,13 +193,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var prootNoSeccomp by mutableStateOf(false) private var prootFastPath by mutableStateOf(true) private var nativeUserland by mutableStateOf(true) + private var desktopAsUser by mutableStateOf(false) private var cursorComposite by mutableStateOf(true) private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME) private var phantomWarning by mutableStateOf(null) private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE) private var showPhantomGate by mutableStateOf(false) private var directAudio by mutableStateOf(false) - private var picturePosition by mutableStateOf("center") + private var picturePositionLandscape by mutableStateOf("center") + private var picturePositionPortrait by mutableStateOf("top") private var integerScaling by mutableStateOf(false) private var stretch16x9 by mutableStateOf(false) private var avoidNotch by mutableStateOf(false) @@ -206,6 +209,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) private var launcherFullscreen by mutableStateOf(true) + private var launcherFrost by mutableStateOf(false) + private var frostWallpaper by mutableStateOf(true) + private var frostCards by mutableStateOf(true) + private var frostTransparency by mutableStateOf(com.droiddeck.launcher.ui.FROST_WALLPAPER_DEFAULT) + private var frostCardTransparency by mutableStateOf(com.droiddeck.launcher.ui.FROST_DEFAULT) + private val frost = com.droiddeck.launcher.ui.LauncherFrost(this) private var controllerHaptics by mutableStateOf(true) private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO) private var downloadMirror by mutableStateOf("") @@ -296,9 +305,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet protons.installExperimental { progress -> com.droiddeck.launcher.session.ExperimentalProtons.installFromFile(this, zip, progress) } } } - private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> - if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } - } private val pickSaveZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then) @@ -509,17 +515,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet bootMovieCustomName = com.droiddeck.launcher.session.BootMovie.customName(this) } - private fun importLossless(dll: File) { - Thread({ - val message = Lossless.message(this, Lossless.import(this, dll)) - val state = Lossless.state(this) - ui.post { - lossless = state - android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show() - } - }, "lossless-import").start() - } - private fun importSaves(name: String, game: () -> GameSaves.Game) { if (SessionState.running) { android.widget.Toast.makeText(this, R.string.main_saves_close_session, android.widget.Toast.LENGTH_LONG).show() @@ -617,6 +612,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) private var hdrOn by mutableStateOf(false) private var zeroCopyOn by mutableStateOf(true) + private var producerAcquireFences by mutableStateOf(false) private var upscaler by mutableStateOf(0) private var upscaleSharpness by mutableStateOf(75) private var hdrReason by mutableStateOf(null) @@ -1092,6 +1088,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } else { putExtra(SessionService.EXTRA_STEAM_URL, com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString)) + putExtra(SessionService.EXTRA_FRONTEND_STEAM_GAME, true) } } .playing(game), steamSession = true) @@ -1371,6 +1368,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet requestedOrientation = launcherOrientation homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) launcherFullscreen = SessionPrefs.launcherFullscreen(this) + launcherFrost = SessionPrefs.launcherFrost(this) + frostWallpaper = SessionPrefs.frostWallpaper(this) + frostCards = SessionPrefs.frostCards(this) + frostTransparency = SessionPrefs.frostTransparency(this) + frostCardTransparency = SessionPrefs.frostCardTransparency(this) + frost.start() + frost.prepare(launcherFrost && frostWallpaper) + frost.show(frostShown()) controllerHaptics = SessionPrefs.controllerHaptics(this) downloadSource = DownloadSource.mode(this) downloadMirror = DownloadSource.mirror(this) @@ -1395,8 +1400,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } val appsTabShown = "android-apps" !in com.droiddeck.launcher.ui.NavTabs.hidden androidx.compose.runtime.LaunchedEffect(appsTabShown) { if (appsTabShown && androidApps.isEmpty()) refreshAndroidApps() } - DroidDeckTheme(theme, appScale = appScale) { - com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) { + val frostShown = frostShown() + androidx.compose.runtime.LaunchedEffect(frostShown) { frost.show(frostShown) } + val frostChoice = if (frostShown) com.droiddeck.launcher.ui.FrostChoice(frostTransparency, frostCards, frostCardTransparency) else null + DroidDeckTheme(theme, appScale = appScale, frost = frostChoice) { + val palette = com.droiddeck.launcher.ui.LocalPalette.current + val veil = com.droiddeck.launcher.ui.LocalFrost.current + val ground = if (frost.prepared) androidx.compose.ui.Modifier.background(veil ?: palette.background) else androidx.compose.ui.Modifier + com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().then(ground).exposeTestTags()) { if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog( onConfirm = { decky.confirmPluginZip() }, onCancel = { decky.cancelPluginZip() }, ) @@ -1472,6 +1483,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launcherOrientation = launcherOrientation, homePage = homePage, launcherFullscreen = launcherFullscreen, + launcherFrost = launcherFrost, + frostWallpaper = frostWallpaper, + frostCards = frostCards, + frostTransparency = frostTransparency, + frostCardTransparency = frostCardTransparency, + frostSupported = frost.supported, controllerHaptics = controllerHaptics, downloadSource = downloadSource, downloadMirror = downloadMirror, @@ -1630,9 +1647,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet FrameGen.set(this, mode) frameGenLabel = FrameGen.label(this) }, - onImportLossless = { - pickLossless.launch(InAppFilePicker.buildIntent(this, listOf("dll"), getString(R.string.lsfg_pick_title))) - }, onProtons = { openProtons() }, onComponents = { focusContent -> openComponents(focusContent) }, onGameComponents = { game -> openComponents(gameKey = game.profileKey) }, @@ -1807,6 +1821,28 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launcherFullscreen = on applyLauncherFullscreen() }, + onLauncherFrost = { on -> + SessionPrefs.setLauncherFrost(this, on) + launcherFrost = on + if (on && frostWallpaper && !frost.prepared) restartLauncher() + }, + onFrostWallpaper = { on -> + SessionPrefs.setFrostWallpaper(this, on) + frostWallpaper = on + if (on && !frost.prepared) restartLauncher() + }, + onFrostCards = { on -> + SessionPrefs.setFrostCards(this, on) + frostCards = on + }, + onFrostTransparency = { percent -> + SessionPrefs.setFrostTransparency(this, percent) + frostTransparency = SessionPrefs.frostTransparency(this) + }, + onFrostCardTransparency = { percent -> + SessionPrefs.setFrostCardTransparency(this, percent) + frostCardTransparency = SessionPrefs.frostCardTransparency(this) + }, onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier }, onNavigated = { navRequest = null }, onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show }, @@ -2113,6 +2149,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } + private fun frostShown(): Boolean = + launcherFrost && frostWallpaper && frost.prepared && frost.available && theme != com.droiddeck.launcher.ui.Themes.TRUE_BLACK + private fun applyLauncherFullscreen() { @Suppress("DEPRECATION") window.decorView.systemUiVisibility = if (launcherFullscreen) { @@ -2194,7 +2233,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet return true } return try { - super.dispatchKeyEvent(event) + super.dispatchKeyEvent(event) || com.droiddeck.launcher.ui.PageBumpers.handle(event) } catch (e: IllegalStateException) { if (e.message?.contains("active focus target") != true) throw e android.util.Log.w("MainActivity", "key ${event.keyCode} dropped: ${e.message}") @@ -2203,6 +2242,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) } + + internal fun onMenuMotion(event: MotionEvent) = triggerKeys.onMotion(event) + private val rightStickLayouts = HashMap() private val rightStickScrollHandler = android.os.Handler(android.os.Looper.getMainLooper()) private var rightStickScrollDeviceId = -1 @@ -2264,7 +2306,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet !com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return val device = event.device ?: return val rxRy = com.droiddeck.launcher.input.PadBridge.rightStickUsesRxRy(event, device, rightStickLayouts) - ?: return + ?: run { + if (rightStickScrollDeviceId == event.deviceId) stopRightStickScroll() + return + } val axis = if (rxRy) android.view.MotionEvent.AXIS_RY else android.view.MotionEvent.AXIS_RZ val value = event.getAxisValue(axis) if (kotlin.math.abs(value) < 0.55f) { @@ -2321,7 +2366,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet refreshHomeAppState() } if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries() - settingsMode?.let { hdrOn = SessionPrefs.hdr(this, it) } + settingsMode?.let { mode -> + hdrOn = SessionPrefs.hdr(this, mode) + if (mode == SessionService.MODE_STEAM) loadPicturePositions() + } compatLaunchVisible = true com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false) @@ -2457,6 +2505,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launchCoordinator.cancelAll() cancelCompatLaunch() updates.unregister() + frost.stop() runCatching { unregisterReceiver(shortcutsInstallStatus) } super.onDestroy() } @@ -2861,6 +2910,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait, panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn, + producerAcquireFences = producerAcquireFences.takeIf { + mode == SessionService.MODE_STEAM && + com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe.available(this) + }, upscaler = upscaler, upscaleSharpness = upscaleSharpness, gpuDrivers = drivers.summary(), touchMode = touchMode, @@ -2875,7 +2928,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet backHold = backHold, backActionsInverted = backActionsInverted, directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null, - picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null, + picturePositionLandscape = picturePositionLandscape.takeIf { mode == SessionService.MODE_STEAM }, + picturePositionPortrait = picturePositionPortrait.takeIf { mode == SessionService.MODE_STEAM }, integerScaling = if (mode == SessionService.MODE_STEAM) integerScaling else null, stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null, avoidNotch = if (mode == SessionService.MODE_STEAM) avoidNotch else null, @@ -2925,6 +2979,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode)) com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on) }, + onProducerAcquireFences = { + SessionPrefs.setProducerAcquireFences(this, it) + producerAcquireFences = it + }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct }, @@ -2948,7 +3006,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet backActionsInverted = inverted }, onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on }, - onPicturePosition = { value -> SessionPrefs.setPicturePosition(this, value); picturePosition = value }, + onPicturePosition = { portrait, value -> + SessionPrefs.setPicturePosition(this, portrait, value) + if (portrait) picturePositionPortrait = value else picturePositionLandscape = value + }, onIntegerScaling = { on -> SessionPrefs.setIntegerScaling(this, on); integerScaling = on }, onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on }, onAvoidNotch = { on -> SessionPrefs.setAvoidNotch(this, on); avoidNotch = on }, @@ -3046,7 +3107,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet fsyncFirst = fsyncFirst, gamescopeRealtime = gamescopeRealtime, gpuClockPin = gpuClockPin, - prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite, + prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite, guestHostname = guestHostname, phantomWarning = phantomWarning, onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on }, onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on }, @@ -3063,6 +3124,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on }, onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on }, onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on }, + onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on }, onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on }, onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) }, onClientCore = { core, on -> @@ -3264,6 +3326,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet resolutionPortrait = SessionPrefs.resolutionStored(this, mode, panel, true) } + private fun loadPicturePositions() { + picturePositionLandscape = SessionPrefs.picturePosition(this, portrait = false) + picturePositionPortrait = SessionPrefs.picturePosition(this, portrait = true) + } + private fun loadModeSettings(mode: String) { pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) @@ -3285,6 +3352,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet loadBootMovie() hdrOn = SessionPrefs.hdr(this, mode) zeroCopyOn = SessionPrefs.zeroCopy(this, mode) + producerAcquireFences = SessionPrefs.producerAcquireFences(this) upscaler = SessionPrefs.upscaler(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this) hdrReason = com.droiddeck.launcher.wayland.HdrSupport.blocked(this) @@ -3298,7 +3366,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet backHold = SessionPrefs.backHold(this) backActionsInverted = SessionPrefs.backActionsInverted(this) directAudio = SessionPrefs.directAudio(this) - picturePosition = SessionPrefs.picturePosition(this) + loadPicturePositions() integerScaling = SessionPrefs.integerScaling(this) stretch16x9 = SessionPrefs.stretch16x9(this) avoidNotch = SessionPrefs.avoidNotch(this) @@ -3381,6 +3449,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet prootNoSeccomp = SessionPrefs.prootNoSeccomp(this) prootFastPath = SessionPrefs.prootFastPath(this) nativeUserland = SessionPrefs.nativeUserland(this) + desktopAsUser = SessionPrefs.desktopAsUser(this) cursorComposite = SessionPrefs.cursorComposite(this) guestHostname = SessionPrefs.guestHostname(this) refreshPhantomStatus() diff --git a/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt b/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt index 5bde3ef872..9a6db04cc5 100644 --- a/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt @@ -4,25 +4,32 @@ import android.app.NativeActivity import android.os.Bundle import android.os.SystemClock import android.util.Log +import android.view.Surface import android.widget.Toast import com.droiddeck.launcher.gpu.SteamVr import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.session.xr.XrLayerSource +import com.droiddeck.launcher.session.xr.XrPanels import com.droiddeck.launcher.wayland.CompositorHost import com.droiddeck.launcher.wayland.WaylandCompositor -class QuestXrActivity : NativeActivity() { +class QuestXrActivity : NativeActivity(), XrLayerSource { private var steamVrStarted = false @Volatile private var closing = false @Volatile private var steamVrStatus = SteamVr.Status.UNAVAILABLE private var sessionId: String? = null override fun onCreate(savedInstanceState: Bundle?) { + // NativeActivity opens the library itself, but the layer host's JNI methods resolve only + // through a System.loadLibrary. + System.loadLibrary("droiddeckxr") sessionId = SessionState.sessionId SessionService.setXrActivityVisible(this, true) super.onCreate(savedInstanceState) } fun onXrActive(active: Boolean) { + XrPanels.setDrawing(active) if (active) { check(CompositorHost.isStarted) { "DroidDeck compositor is not running" } SessionService.resume(this) @@ -100,8 +107,30 @@ class QuestXrActivity : NativeActivity() { fun onXrStatus(): Int = steamVrStatus.ordinal + fun onXrHostBuffers(state: java.nio.ByteBuffer, control: java.nio.ByteBuffer) { + runOnUiThread { if (!closing) XrPanels.attach(this, state, control) } + } + + fun onXrHostFrame() = XrPanels.frame() + + override val context: android.content.Context get() = this + override fun createLayer(width: Int, height: Int) = nativeCreateLayer(width, height) + override fun layerSurface(id: Int) = nativeLayerSurface(id) + override fun destroyLayer(id: Int) = nativeDestroyLayer(id) + override fun setOrbImage(image: android.graphics.Bitmap) = nativeSetOrbImage(image) + override fun leave() { + closing = true + finish() + } + + private external fun nativeCreateLayer(width: Int, height: Int): Int + private external fun nativeLayerSurface(id: Int): Surface? + private external fun nativeDestroyLayer(id: Int) + private external fun nativeSetOrbImage(image: android.graphics.Bitmap) + override fun onDestroy() { closing = true + XrPanels.detach() SessionService.setXrActivityVisible(this, false) super.onDestroy() } diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 8473957bcd..6cf2f43a9f 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -76,6 +76,7 @@ import com.droiddeck.launcher.input.InputSpace import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.SessionClipboard +import com.droiddeck.launcher.input.SessionTextInput import com.droiddeck.launcher.input.OnScreenControls import com.droiddeck.launcher.input.OnScreenLayout import com.droiddeck.launcher.input.InputRouter @@ -162,7 +163,8 @@ import kotlin.math.abs private const val SCREEN_EFFECTS_TARGET_AUTO = "auto" private const val SCREEN_EFFECTS_TARGET_GLOBAL = "global" -class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost { +class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost, + com.droiddeck.launcher.session.xr.XrMenuHost { override fun attachBaseContext(newBase: android.content.Context) { super.attachBaseContext(newBase) com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase) @@ -178,6 +180,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var adaptiveSticks by mutableStateOf(null) private var quickButtons by mutableStateOf>(emptyMap()) private var picturePosition by mutableStateOf("center") + + private fun picturePortrait(config: android.content.res.Configuration = resources.configuration): Boolean = + config.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT private var integerScaling by mutableStateOf(false) private var gameZoom by mutableStateOf(SessionState.gameZoom) private var avoidNotch = false @@ -228,6 +233,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private var unfoldedPanel by mutableStateOf(null) private var unfoldedColumn: android.widget.LinearLayout? = null + private var unfoldedKeys: View? = null private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null private var unfoldedDeckPanel by mutableStateOf(null) @@ -348,6 +354,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true } } + private val sessionTextInput by lazy { + SessionTextInput(this) { + window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true + } + } private var watching = true private lateinit var touchpad: TouchpadGestures private lateinit var directTouchHold: DirectTouchHold @@ -546,6 +557,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var drawerOpenState by mutableStateOf(false) private var typingReturnMode: SecondScreenMode? = null private var drawerDocked by mutableStateOf(false) + /** The menu is open as a floating panel in the immersive Quest view instead of over this window. */ + private var drawerXr by mutableStateOf(false) private var drawerPinned by mutableStateOf(false) private var drawerLayerOpen = false private var drawerBackRequests by mutableIntStateOf(0) @@ -563,9 +576,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde drawerPinned = false if (value) { releaseHeldKeys() - drawerDocked = dockDrawer() && openDockedMenu() + drawerXr = com.droiddeck.launcher.session.xr.XrPanels.showMenu() + drawerDocked = !drawerXr && dockDrawer() && openDockedMenu() } drawerOpenState = value + if (!value && drawerXr) { + drawerXr = false + com.droiddeck.launcher.session.xr.XrPanels.hideMenu() + } if (!value && drawerDocked) closeDockedMenu() } private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController) @@ -703,9 +721,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var drawerTextureAnisotropy by mutableStateOf(null) private var drawerTextureLodBias by mutableStateOf(null) private var lossless by mutableStateOf(Lossless.State.NONE) - private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> - if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } - } private var frameGen by mutableStateOf(FrameGen.Mode.OFF) private var frameGenActiveGameId by mutableStateOf(null) private var frameGenActiveGameName by mutableStateOf(null) @@ -807,6 +822,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private var isHomeApp by mutableStateOf(false) private var androidApps by mutableStateOf>(emptyList()) + private var padConnected by mutableStateOf(false) private val deviceListener = object : InputManager.InputDeviceListener { override fun onInputDeviceAdded(deviceId: Int) { @@ -849,6 +865,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + com.droiddeck.launcher.session.xr.XrPanels.setMenuHost(this) AgentGuest.readyListener = agentReadyListener com.droiddeck.launcher.agent.AgentAttachments.gameFrame = gameFrame if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() || @@ -979,6 +996,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde openDeckRing("activity created") bridge.setOnPlayerInput(::onPadInput) onScreenControls = OnScreenControls(this, bridge).also { controls -> + controls.alpha = onScreenOpacityAlpha() controls.updateLayout(primaryInputLayout) controls.onTouchMiss = miss@{ event -> if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss @@ -987,7 +1005,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } root.addView(controls) } - keyboard = KeyboardHost(this).also { host -> + keyboard = KeyboardHost(this, sendKeyEvent = ::dispatchImeKeyEvent, sendText = WaylandCompositor::textInputCommit).also { host -> host.onImeChanged = ::onPrimaryImeChanged root.addView(host) } @@ -1192,7 +1210,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val cursorHidden = cursorHiddenByUi() androidx.compose.runtime.SideEffect { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, - (drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING) + (drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && !drawerXr && steamVrStatus != SteamVr.Status.RUNNING) } androidx.compose.runtime.SideEffect { applyPlatformPointer(uiPointer) } androidx.compose.runtime.DisposableEffect(Unit) { @@ -1262,14 +1280,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde glasses.usesSpatialControllers(glassesSettings) && glassesSettings.joyConTracking) joyConVr?.let { { it.recenter() } } else null, ) { headTracker?.recenter() } - if (!phonePanel && glasses.present && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot, + val showGlassesShortcut = com.droiddeck.launcher.ui.rememberShowGlassesShortcut() + if (!phonePanel && glasses.present && showGlassesShortcut && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot, controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) { - drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES + drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.VR drawerOpen = true } if (!drawerOpen && !pcKeyboardOpen && !loading.visible) { com.droiddeck.launcher.ui.DrawerEntryHint(SessionState.mode == SessionService.MODE_STEAM, backActionsInverted) { drawerOpen = true } if (cornerTap) com.droiddeck.launcher.ui.DrawerCornerTap { drawerOpen = true } + if (com.droiddeck.launcher.session.QuestExperimental.isSupported()) + com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() } } if (loading.visible) LoadingOverlay( loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended, @@ -1451,7 +1472,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } LaunchedEffect(drawerOpen, achievementsOpen, AgentGuest.focusRevision, StoreAchievements.revision) { - if (!drawerOpen && !achievementsOpen) return@LaunchedEffect + if (!drawerOpen && !achievementsOpen) { + achievementsInFront = null + return@LaunchedEffect + } val found = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { runCatching { resolveAchievementsInFront() } .onFailure { Log.w(TAG, "achievements in front: ${it.javaClass.simpleName}") }.getOrNull() @@ -1470,11 +1494,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() }, onClose = { pcKeyboardOpen = false }, ) - if (!drawerDocked) SessionMenu( + if (!drawerDocked && !drawerXr) SessionMenu( docked = false, effectsEditorProfileId = effectsEditorProfileId, effectsEditorTarget = effectsEditorTarget, ) + if (drawerOpen && !drawerDocked && !drawerXr && com.droiddeck.launcher.session.QuestExperimental.isSupported()) + com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() } LaunchedEffect(achievementsOpen) { if (achievementsOpen) { releasePads() @@ -1523,6 +1549,74 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } + @androidx.compose.runtime.Composable + override fun XrMenuContent() { + val activeEffectsProfileId = currentScreenEffectsProfileId() + val effectsEditorTarget = if (drawerOpen) screenEffectsTarget else null + val effectsEditorProfileId = activeEffectsProfileId.takeIf { effectsEditorTarget == SCREEN_EFFECTS_TARGET_AUTO } + androidx.compose.runtime.LaunchedEffect(effectsEditorTarget, effectsEditorProfileId) { + when (effectsEditorTarget) { + SCREEN_EFFECTS_TARGET_AUTO -> syncActiveScreenEffectsProfile() + null -> Unit + else -> syncScreenEffectsTarget(effectsEditorTarget) + } + } + SessionMenu(docked = true, effectsEditorProfileId = effectsEditorProfileId, effectsEditorTarget = effectsEditorTarget) + } + + override fun xrSetMenuOpen(open: Boolean) { + if (open != drawerOpen) drawerOpen = open + } + + /** + * In the immersive Quest view, Stop takes the user back to this window with the session still + * running, and Stop SteamVR leaves at once instead of after the stop is noticed. + */ + private fun leaveXrMenu() { + if (!drawerXr) return + drawerOpen = false + com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive() + } + + override fun xrMenuBack() { + if (drawerLayerOpen) drawerBackRequests++ else drawerOpen = false + } + + override fun xrSendKey(code: Int, down: Boolean) { + if (CompositorHost.isStarted) sendGuestKey(code, down, 32) + } + + override fun xrTypeText(text: String) = xrKeys.type(text) + + override fun xrImmersiveChanged(active: Boolean) { + if (active) { + if (immersiveFlatSize == null) immersiveFlatSize = SessionState.outputSize + resizeOutputForWindow(surfaceW, surfaceH) + return + } + val flat = immersiveFlatSize + immersiveFlatSize = null + if (windowOutputSize(surfaceW, surfaceH) == null && flat != null) applyOutputSize(flat) + else resizeOutputForWindow(surfaceW, surfaceH) + } + + /** The output's size when the immersive view opened; this window may have no surface while it is up. */ + private var immersiveFlatSize: Pair? = null + + override fun xrTapKey(keyCode: Int) = xrKeys.tap(keyCode) + + /** The VR keyboard's keys go straight to the game, past the menu and pad handling a real key passes through. */ + private val xrKeys by lazy { + KeyboardHost( + this, + sendKeyEvent = { event -> + CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) && + com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) } + }, + sendText = { text -> if (CompositorHost.isStarted) WaylandCompositor.textInputCommit(text) }, + ) + } + @androidx.compose.runtime.Composable private fun SessionMenu( docked: Boolean, @@ -1626,6 +1720,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionState.gameZoom = gameZoom runCatching { WaylandCompositor.nativeSetZoom(gameZoom) } }, + picturePosition = picturePosition, + onPicturePosition = { position -> + SessionPrefs.setPicturePosition(this@SessionActivity, picturePortrait(), position) + picturePosition = position + }, integerScaling = integerScaling, onIntegerScaling = { enabled -> SessionPrefs.setIntegerScaling(this@SessionActivity, enabled) @@ -1787,7 +1886,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onBlackFrameInsertion = { on -> SessionPrefs.setBlackFrameInsertion(this@SessionActivity, on) blackFrameInsertion = on - CompositorHost.setBlackFrameInsertion(on, refreshHz(), outputFpsLimit()) + CompositorHost.setBlackFrameInsertion(on, refreshHz(), compositorFpsLimit()) }, hdr = hdrWanted, hdrAvailable = hdrAvailable, @@ -1810,10 +1909,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde readPrefs() applyFrameGen(force = true) }, - onImportLossless = { - pickLossless.launch(InAppFilePicker.buildIntent( - this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title))) - }, onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; togglePrimaryKeyboard() }, onHardwareKeyboard = ::togglePcKeyboard, wowChatShown = com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram), @@ -1821,10 +1916,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onWowChat = wowChat::choose, controller = controllerSettings, onControllerSize = { percent -> updateControllerPrefs { ControllerPrefs.setSize(this@SessionActivity, percent) } }, + onControllerOpacity = { percent -> + ControllerPrefs.setOnScreenOpacity(this@SessionActivity, percent) + controllerSettings = ControllerPrefs.read(this@SessionActivity) + applyOnScreenOpacity() + }, onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } }, onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null, onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null, - onAchievements = achievementsInFront?.let { { drawerOpen = false; achievementsOpen = true } }, + controllerConnected = padConnected, + achievementsGame = achievementsInFront?.game, + achievementsTitle = achievementsInFront?.title, achievementsProgress = achievementsInFront?.progress, padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null, onPadType = { id -> @@ -1899,9 +2001,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionService.suspendPolicyChanged(this@SessionActivity) }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, - onInputSettings = { releasePads(); drawerOpen = false; inputSettingsOpen = true }, + onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputSettingsOpen = true }, onInputSelection = { releasePads(); refreshInputProfile() }, - onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true }, + onGestureSettings = { leaveImmersiveForDialog(); drawerOpen = false; gestureSettingsOpen = true }, touchActive = drawerTouchMode(), directHoldBehavior = directHoldBehavior, onDirectHoldBehavior = { value -> @@ -1945,7 +2047,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onResume = { SessionService.resume(this@SessionActivity) }, orientation = sessionOrientation, onOrientation = { value -> - SessionPrefs.setOrientation(this@SessionActivity, value) + when (SessionState.mode) { + SessionService.MODE_STEAM, SessionService.MODE_RUN -> + SessionPrefs.setOrientation(this@SessionActivity, "steam", value) + SessionService.MODE_DESKTOP -> + SessionPrefs.setOrientation(this@SessionActivity, "desktop", value) + else -> SessionPrefs.setOrientation(this@SessionActivity, value) + } sessionOrientation = value applyFollowOrientation(resources.configuration) }, @@ -1956,6 +2064,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }, unfoldedControls = unfoldedControls, onUnfoldedControls = ::chooseUnfoldedControls, + deckPanel = unfoldedDeckPanel, + onDeckPanel = ::selectDeckPanel, adaptiveSticks = adaptiveSticks.takeIf { unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && oscMode != SessionPrefs.OSC_STEAM_QAM && !steamTouchInUse }, @@ -1992,18 +2102,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController, onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) }, onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() }, - onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() }, + onStop = { + if (drawerXr) leaveXrMenu() else { + drawerOpen = false + SessionService.stop(this@SessionActivity) + finish() + } + }, onStopFrom = { onScreen -> - drawerOpen = false - if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) { - if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() } - } else { - val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) } - quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat()) + if (drawerXr) leaveXrMenu() else { + drawerOpen = false + if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) { + if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() } + } else { + val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) } + quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat()) + } } }, onClose = { drawerOpen = false }, - onDismissScreen = if (docked) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null, + onDismissScreen = if (docked && !drawerXr) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null, components = drawerComponents, onComponentsRefresh = { refreshDrawerComponents() @@ -2081,7 +2199,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }) else null, onKeyboard = { togglePrimaryKeyboard() }, onSessionMenu = { drawerOpen = true }, - onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null, + onStopSteamVr = if (vr) ({ leaveXrMenu(); steamVrAction("stop") }) else null, brightness = glasses.brightness, brightnessMax = glasses.brightnessMax, onBrightness = if (glasses.canControl && glasses.hardwareControls) Glasses::setBrightness else null, @@ -2120,6 +2238,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun togglePcKeyboard() { drawerOpen = false + if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = true)) return hidePrimaryKeyboard() onScreenControls?.releaseAll() bottomInputControls?.releaseAll() @@ -2129,12 +2248,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun showPrimaryKeyboard() { pendingFieldKeyboard = false fieldKeyboardOnPrimary = false + if (com.droiddeck.launcher.session.xr.XrPanels.showGameKeyboard(pc = false)) return keyboard?.show() } private fun togglePrimaryKeyboard() { pendingFieldKeyboard = false fieldKeyboardOnPrimary = false + if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = false)) return keyboard?.toggle() } @@ -2158,6 +2279,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (fieldKeyboardOnPrimary) hidePrimaryKeyboard() } + private fun onScreenOpacityAlpha() = ControllerPrefs.onScreenOpacity(this) / 100f + + private fun applyOnScreenOpacity() { + val alpha = onScreenOpacityAlpha() + onScreenControls?.alpha = alpha + bottomInputControls?.alpha = alpha + unfoldedColumn?.alpha = alpha + swappedInputSurface?.alpha = alpha + secondScreenPresentation?.controlsView?.alpha = alpha + steamTouchControls?.let { it.alpha = if (it.isEditing) 1f else alpha } + } + private fun updateControllerPrefs(change: () -> Unit) { change() controllerSettings = ControllerPrefs.read(this) @@ -2668,7 +2801,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) - picturePosition = SessionPrefs.picturePosition(this) + picturePosition = SessionPrefs.picturePosition(this, picturePortrait()) integerScaling = SessionPrefs.integerScaling(this) avoidNotch = SessionPrefs.avoidNotch(this) applyNotchInset() @@ -2724,7 +2857,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde oscTrackpads = SessionPrefs.oscTrackpads(this) backHold = SessionPrefs.backHold(this) dockedMenuController = SessionPrefs.dockedMenuController(this) - sessionOrientation = SessionPrefs.orientation(this) + sessionOrientation = SessionPrefs.orientation(this, SessionState.mode) dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this) backActionsInverted = SessionPrefs.backActionsInverted(this) physicalShortcuts.bindings = PhysicalShortcuts.read(this) @@ -2990,7 +3123,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde CompositorHost.startOrAttach( this, holder.surface, runtimeDir.path, driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, - applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(), + applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), compositorFpsLimit(), ) onOutputAttached(holder) if (SessionState.running && size != previous) { @@ -3008,6 +3141,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS), intent.getStringExtra(SessionService.EXTRA_GAME_ID), sessionActivityDisplayId, + frontendSteamGame = intent.getBooleanExtra(SessionService.EXTRA_FRONTEND_STEAM_GAME, false), ) intent.getStringExtra(EXTRA_PLAYED_GAME)?.let { com.droiddeck.launcher.frontend.Library.recordPlayed(this, it) } } @@ -3032,6 +3166,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun windowOutputSize(width: Int, height: Int): Pair? { + if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) { + val flat = immersiveFlatSize ?: SessionState.outputSize + return if (steamScreenShown()) vrOutputSize(flat) else flat + } if (width <= 0 || height <= 0 || isInPictureInPictureMode) return null if (bottomGame != null) return when { SessionState.followScreen -> @@ -3045,9 +3183,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde else if (glassesScreen == null) outputSize() else null } + /** These editors draw in this window, which the immersive view hides, so they open after leaving it. */ + private fun leaveImmersiveForDialog() { + if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive() + } + + /** Steam's own screen is up with no game holding a window; with no focus report, a game may be running. */ + private fun steamScreenShown(): Boolean { + if (SessionState.mode != SessionService.MODE_STEAM) return false + val focus = com.droiddeck.launcher.agent.AgentGuest.focus(this) ?: return false + return com.droiddeck.launcher.session.xr.XrSteamScreen.shown( + focus.takeUnless { it.isNull("focusedApp") }?.optLong("focusedApp"), + focus.optJSONArray("focusableApps")?.let { list -> (0 until list.length()).map { list.optLong(it) } }, + ) + } + + /** + * SteamVR shows Steam's own screen as its floating Steam window, so in the headset that screen is drawn + * tall enough for the window to stay sharp. A flat game keeps the flat size, so the output keeps it + * while one is running. + */ + private fun vrOutputSize(flat: Pair): Pair { + if (flat.second >= VR_OUTPUT_HEIGHT) return flat + val width = (flat.first.toLong() * VR_OUTPUT_HEIGHT / flat.second.coerceAtLeast(1)).toInt() and 1.inv() + return width to VR_OUTPUT_HEIGHT + } + private fun resizeOutputForWindow(width: Int, height: Int) { + applyOutputSize(windowOutputSize(width, height) ?: return) + } + + private fun applyOutputSize(size: Pair) { if (!CompositorHost.isStarted) return - val size = windowOutputSize(width, height) ?: return if (size == SessionState.outputSize) return Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}") SessionState.outputSize = size @@ -3056,7 +3223,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde WaylandCompositor.nativeResizeOutput(size.first, size.second) } - private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this) + private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this, SessionState.mode) private fun applyFollowChoice() { val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first } @@ -3065,12 +3232,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun applyFollowOrientation(config: android.content.res.Configuration) { - val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp) + val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp, SessionState.mode) if (requestedOrientation != wanted) requestedOrientation = wanted } override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { super.onConfigurationChanged(newConfig) + picturePosition = SessionPrefs.picturePosition(this, picturePortrait(newConfig)) if (refreshActivityDisplayId() && started) { SessionService.setActivityDisplay(this, sessionActivityDisplayId) } @@ -3128,13 +3296,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun displayMode(): String = SessionPrefs.displayMode(this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM)) - private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted() + private fun portraitOutput(): Boolean = SessionPrefs.portrait(this, SessionState.mode) && !controlsBelowWanted() private fun outputSize(): Pair = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this), resolutionChoice(), portraitOutput()) - private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String { + private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this, SessionState.mode)): String { val mode = displayMode() val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN && @@ -3181,6 +3349,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun outputFpsLimit(): Int = outputFpsLimit(pipUi) + // Android holds the window to the Game Mode override while the panel runs faster; the guest paces to the panel, + // so without this cap every frame past the override is drawn and dropped. + private fun hostFrameCap(): Int { + if (glassesScreen != null || bottomOutputActive) return 0 + val display = (if (Build.VERSION.SDK_INT >= 30) display else @Suppress("DEPRECATION") windowManager.defaultDisplay) ?: return 0 + return SessionPrefs.hostFrameCap(display.refreshRate, display.mode.refreshRate) + } + + private fun compositorFpsLimit(): Int = SessionPrefs.compositorFpsLimit( + mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pipUi, hostFrameCap(), + ) + private fun outputFpsLimit(pip: Boolean): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip) @@ -3218,7 +3398,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) val hz = refreshHz() val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f - CompositorHost.updatePacing(hz, outputFpsLimit()) + CompositorHost.updatePacing(hz, compositorFpsLimit()) pushCardboard(activeCardboard) if (changed && ::surfaceView.isInitialized) applyFrameGen() } @@ -3431,19 +3611,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }, "lossless-sync").start() } - private fun importLossless(dll: File) { - Thread({ - val result = Lossless.import(this, dll) - val message = Lossless.message(this, result) - val state = Lossless.state(this) - runOnUiThread { - lossless = state - Toast.makeText(this, message, Toast.LENGTH_LONG).show() - applyFrameGen(force = result == Lossless.ImportResult.UPDATED) - } - }, "lossless-import").start() - } - private fun watchSession() { val handler = Handler(Looper.getMainLooper()) @@ -3655,16 +3822,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } - override fun dispatchKeyEvent(event: KeyEvent): Boolean { + internal fun dispatchImeKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = true) + + override fun dispatchKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = false) + + private fun dispatchKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean { val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event) - if (normalized === event) return dispatchSessionKeyEvent(event) + if (normalized === event) return dispatchSessionKeyEvent(event, orderedImeKey) if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}") } - return dispatchSessionKeyEvent(normalized) + return dispatchSessionKeyEvent(normalized, orderedImeKey) } - private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean { + private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean { if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> { @@ -3747,7 +3918,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde return true } val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) - if (pad !== event) return dispatchKeyEvent(pad) + if (pad !== event) return dispatchKeyEvent(pad, orderedImeKey) val fromController = PadBridge.isControllerKeyEvent(event) if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { padBridge?.setInputEnabled(false) @@ -3789,7 +3960,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { // The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab. - val pages = sessionDrawerPages(glasses.present) + val pages = sessionDrawerPages(achievementsInFront != null) drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) releaseDrawerDirection() } @@ -3830,7 +4001,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val down = event.action == KeyEvent.ACTION_DOWN if (down && event.repeatCount > 0) return true val owner = if (event.deviceId <= 0) 16 else 8 - if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner) }) return true + if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner, orderedImeKey) }) return true } return super.dispatchKeyEvent(event) } @@ -3917,7 +4088,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde steamTouchControls?.let { takes(it, it::takesTouchAt) } == true || unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true || unfoldedDeckSurface?.let { takes(it, it::takesTouchAt) } == true || - unfoldedColumn?.getChildAt(0)?.let { takes(it) { _, _ -> true } } == true + unfoldedKeys?.let { takes(it) { _, _ -> true } } == true } override fun dispatchTouchEvent(event: MotionEvent): Boolean { @@ -4945,6 +5116,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun refreshControls() { + padConnected = controllerConnected() applyUnfoldedControls() updateOnScreenControls() } @@ -4960,12 +5132,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val width = rootContentWidth() val height = rootContentHeight() val wanted = controlsBelowWanted() - val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let { - it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt() - } ?: 0 val outputAspect = if (!wanted || SessionState.followScreen) 0f else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) } - val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect) + val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, aspect = outputAspect) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams if (params.height != gameHeight) { @@ -4982,6 +5151,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (panel != null && (!wanted || panel.dock != dock)) { sessionRoot.removeView(unfoldedColumn) unfoldedColumn = null + unfoldedKeys = null unfoldedDeckSurface = null unfoldedDeckPanel = null unfoldedPanel = null @@ -4992,14 +5162,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (panel == null) { panel = OnScreenControls(this, padBridge, dock).also { it.updateLayout(primaryInputLayout) } val column = android.widget.LinearLayout(this).apply { + alpha = onScreenOpacityAlpha() orientation = android.widget.LinearLayout.VERTICAL - addView(unfoldedBar().apply { - addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom -> - if (bottom - top != oldBottom - oldTop) post { applyUnfoldedControls() } - } - }, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, - android.widget.LinearLayout.LayoutParams.WRAP_CONTENT)) addView(panel, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) + unfoldedKeys = com.droiddeck.launcher.ui.padKeysView( + this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM, + { releasePads(); drawerOpen = true }, ::tapSteamButton, ::tapQam, + ).also { + addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, + android.widget.LinearLayout.LayoutParams.WRAP_CONTENT)) + } } sessionRoot.addView(column, sessionRoot.indexOfChild(surfaceView) + 1) unfoldedColumn = column @@ -5010,13 +5182,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde unfoldedColumn?.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM) } - private fun unfoldedBar(): View = com.droiddeck.launcher.ui.bottomScreenBarView(this) { - val deck = unfoldedDeckPanel - com.droiddeck.launcher.ui.sessionBarModel(getString(if (deck != null) R.string.second_mode_deck_controls else R.string.deck_tab_gamepad), - { chooseUnfoldedControls(false) }, { drawerOpen = true }, ::tapSteamButton, ::tapQam, - tabs = deck?.let { com.droiddeck.launcher.ui.deckPanelTabs(this, it, ::selectDeckPanel) }) - } - private fun showUnfoldedDeckPanel() { val column = unfoldedColumn val panel = unfoldedPanel @@ -5032,7 +5197,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde panel.visibility = View.GONE unfoldedDeckSurface = com.droiddeck.launcher.ui.InputSurfaceView(this, padBridge, layout.elements, InputRole.PRIMARY, layout.style, haptics = true).also { it.tag = layout - column.addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) + column.addView(it, column.indexOfChild(panel) + 1, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) } } @@ -5123,27 +5288,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } else { endGameField() } - host.type(text) - host.tap(KeyEvent.KEYCODE_ENTER) + if (text.isEmpty()) host.tap(KeyEvent.KEYCODE_ENTER) + else WaylandCompositor.textInputCommitAndSubmit(text) uiHandler.postDelayed({ if (AgentGuest.gameTextField && com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) endGameField() }, FIELD_SETTLE_MS) } private fun endGameField() { - WaylandCompositor.nativeSendKey(KEY_END, 1) - WaylandCompositor.nativeSendKey(KEY_END, 0) + orderedImeKeySender(KEY_END, true) + orderedImeKeySender(KEY_END, false) } - private fun selectGameField(vararg then: Int) { - heldKeys.set(256, KEY_LEFTCTRL, true) - try { - for (key in intArrayOf(KEY_A) + then) { - heldKeys.set(256, key, true) - heldKeys.set(256, key, false) - } - } finally { heldKeys.release(256) } - } + private fun selectGameField(copy: Boolean = false) { WaylandCompositor.nativeSelectGameField(copy) } private fun readGameField(done: (String?) -> Unit) { val opened = wowChat.request @@ -5152,7 +5309,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (text != null && stillOpen()) endGameField() done(text) } - selectGameField(KEY_C) + selectGameField(copy = true) } private fun cancelWowChat() { @@ -5851,7 +6008,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val view = com.droiddeck.launcher.input.SteamTouchControls(this, device, onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard) view.visibility = View.GONE - view.onEditingChanged = { touchEditorChanged() } + view.alpha = onScreenOpacityAlpha() + view.onEditingChanged = { editing -> + view.alpha = if (editing) 1f else onScreenOpacityAlpha() + touchEditorChanged() + } view.onOptions = { options -> steamTouchOptions = options applyTouchRouting() @@ -5956,6 +6117,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (bottom?.parent !== bottomRoot) { (bottom?.parent as? android.view.ViewGroup)?.removeView(bottom) bottom = OnScreenControls(bottomRoot.context, padBridge).also { view -> + view.alpha = onScreenOpacityAlpha() view.onTouchMiss = { event -> onBottomGameTouch(event) } bottomRoot.addView(view, android.view.ViewGroup.LayoutParams(-1, -1)) } @@ -6055,11 +6217,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde releaseHeldKeys() } - private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) { + private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1, orderedImeKey: Boolean = false) { if (down && pipUi) return val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key if (owner == 1) { if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) } - heldKeys.set(owner, code, down) + val orderedSender = if (orderedImeKey) orderedImeKeySender else null + heldKeys.set(owner, code, down, orderedSender) + } + + private val orderedImeKeySender: (Int, Boolean) -> Unit = { code, down -> + WaylandCompositor.nativeSendKeyOrdered(code, if (down) 1 else 0) } private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) { @@ -6127,7 +6294,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val back = { if (restore.compareAndSet(false, true)) { pauseCaptures-- - if (!isDestroyed) WaylandCompositor.nativeSetZeroCopy(composedOutputFree()) + if (!isDestroyed && zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree()) } } uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS) @@ -6242,6 +6409,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldButtons.clear() hidePrimaryKeyboard() sessionClipboard.stop() + sessionTextInput.stop() padMotion?.stop() cursorVisible = false closeSecondScreen(reset = false) @@ -6257,7 +6425,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } else if (!isFinishing && !isDestroyed) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) updateOnScreenControls() - if (resumed) { sessionClipboard.start(); updatePadMotion() } + if (resumed) { sessionClipboard.start(); sessionTextInput.start(); updatePadMotion() } if (started) { settleDualScreenControls() refreshSecondScreenDisplays() @@ -6328,6 +6496,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener) contentResolver.unregisterContentObserver(refreshSettingObserver) if (!screenIsOff()) closeSecondScreen(reset = false) + sessionTextInput.stop() startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() updateBottomGame() @@ -6385,12 +6554,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } (getSystemService(INPUT_SERVICE) as? InputManager) ?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper())) + padConnected = controllerConnected() padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this)) refreshSecondScreenDisplays() if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers() joyConVr?.refresh() onScreenControls?.reload() controllerSettings = ControllerPrefs.read(this) + applyOnScreenOpacity() resumed = true boostGpuClock(panelOverGame) updateKeyboardRoute() @@ -6406,7 +6577,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onCancel = { padBridge?.cancelHomeGuide() }, ) updatePointerCapture() - if (!pipUi) sessionClipboard.start() + if (!pipUi) { sessionClipboard.start(); sessionTextInput.start() } updatePadMotion() ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener) SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener) @@ -6899,7 +7070,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde androidx.compose.runtime.key(profileLayout) { androidx.compose.ui.viewinterop.AndroidView( factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(), - surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } }, + surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { + it.alpha = onScreenOpacityAlpha() + swappedInputSurface = it + } }, modifier = Modifier.fillMaxWidth().weight(1f), onRelease = { if (swappedInputSurface === it) swappedInputSurface = null }, ) @@ -7123,6 +7297,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onDestroy() { + com.droiddeck.launcher.session.xr.XrPanels.clearMenuHost(this) + if (drawerXr) com.droiddeck.launcher.session.xr.XrPanels.hideMenu() uiHandler.removeCallbacks(panelHeldCheck) uiHandler.removeCallbacks(panelHeldRetry) synchronized(frameGenGlobalLock) { @@ -7135,6 +7311,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde gamescopeConvarRequests.shutdownNow() backQamInput.cancel() steamVrRecovery.close() + sessionTextInput.stop() uiHandler.removeCallbacks(steamTouchRetry) uiHandler.removeCallbacks(cursorResync) uiHandler.removeCallbacks(usbMouseFallback) @@ -7247,6 +7424,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde const val EXTRA_RETURN_HOME = "returnHome" private const val BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT" private const val REQUEST_BLUETOOTH = 31 + private const val VR_OUTPUT_HEIGHT = 1080 const val EXTRA_LINK_TASK = "linkTask" const val EXTRA_STEAMVR = "steamVr" const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME" diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentChatActivity.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentChatActivity.kt new file mode 100644 index 0000000000..02f1a84e86 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentChatActivity.kt @@ -0,0 +1,48 @@ +package com.droiddeck.launcher.agent + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.core.AppUiPrefs +import com.droiddeck.launcher.ui.AgentPage +import com.droiddeck.launcher.ui.DroidDeckTheme + +/** + * The agent's chat in a window of its own, for Quest's flat mode: opened in its own task, it is a + * separate Horizon panel the user can move, resize and close like any other. + */ +class AgentChatActivity : ComponentActivity() { + override fun attachBaseContext(newBase: Context) { + super.attachBaseContext(newBase) + com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { + DroidDeckTheme(appScale = AppUiPrefs.scale(this)) { + AgentPage( + Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(horizontal = 12.dp, vertical = 6.dp), + visible = true, startTyping = AgentHost.entries.isEmpty(), + ) + } + } + } + + companion object { + fun open(context: Context) { + context.startActivity( + Intent(context, AgentChatActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT), + ) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt index abe8abb3a3..c1ad86bfc3 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt @@ -19,7 +19,7 @@ import java.util.UUID object AgentGuest { private val main by lazy { Handler(Looper.getMainLooper()) } var focusRevision by mutableIntStateOf(0) - private set + @androidx.annotation.VisibleForTesting internal set var steamKeyboard by mutableStateOf(false) private set var desktopTextField by mutableStateOf(false) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt index 566cfde355..87188e34d7 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt @@ -75,7 +75,9 @@ object AgentHost { "Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " + "Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " + "To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " + - "and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message." + "and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message. " + + "To show the user an image (a screenshot, a mockup, a chart), put ![what it shows](/absolute/path.png) on a line of its own: " + + "DroidDeck draws the file in the chat." val entries = mutableStateListOf() val queue = mutableStateListOf() diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index 4a2e07b45b..ad78dd3d44 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -8,8 +8,11 @@ import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import com.droiddeck.launcher.R +import com.droiddeck.launcher.core.WirelessAdbFix import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.OrphanReaper +import com.droiddeck.launcher.session.QuestExperimental import java.io.File import java.util.concurrent.TimeUnit @@ -88,6 +91,8 @@ object AgentSetup { private fun completedKey(harness: AgentHarness) = "setup_completed_${harness.id}" private val main = Handler(Looper.getMainLooper()) + /** Advanced by every Allow, so a connection check started before it cannot overwrite what it found. */ + private var connectionGeneration = 0 private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git" private const val CHECKOUT = "/root/DroidDeck" private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl", "droiddeck-scenario") @@ -104,6 +109,7 @@ object AgentSetup { val harness = AgentHost.harness keys = harness.keys(LinuxRuntime.rootDir(app)) val probes = mutableListOf>>() + val generation = connectionGeneration for (step in Step.entries) if (status[step] != Status.WORKING) { when (step) { Step.INSTALL -> set(step, if (harness.files.all { AgentHost.guestFileExists(app, it) }) Status.DONE else Status.TODO) @@ -114,7 +120,9 @@ object AgentSetup { detail.remove(step) Thread({ val live = com.droiddeck.launcher.core.WirelessAdbFix.liveConnectAddress(app) != null - set(step, if (live) Status.DONE else Status.TODO) + main.post { + if (generation == connectionGeneration && status[step] != Status.WORKING) status[step] = if (live) Status.DONE else Status.TODO + } }, "agent-connection").start() } else probes += step to listOf("sh", "-c", "for i in 1 2 3; do adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " + @@ -123,7 +131,7 @@ object AgentSetup { Step.GITHUB -> probes += step to listOf("gh", "auth", "status") } } - Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start() + Thread({ for ((step, command) in probes) probe(app, harness, step, command, generation) }, "agent-checks").start() } /** The last failed refresh ends the script: the installs after it would run from stale indexes and could report success. */ @@ -141,6 +149,22 @@ object AgentSetup { /** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */ fun run(context: Context, step: Step) = run(context, step, null) + /** The [Step.CONNECTION] action on a Quest, which has no pairing screen; see [WirelessAdbFix.trustOnDevice]. */ + fun trustOnDevice(context: Context) { + val app = context.applicationContext + connectionGeneration++ + status[Step.CONNECTION] = Status.WORKING + detail[Step.CONNECTION] = app.getString(R.string.agent_connection_quest_waiting) + Thread({ + val ok = runCatching { WirelessAdbFix.trustOnDevice(app) }.isSuccess + main.post { + status[Step.CONNECTION] = if (ok) Status.DONE else Status.FAILED + if (ok) detail.remove(Step.CONNECTION) else detail[Step.CONNECTION] = app.getString(R.string.agent_connection_quest_failed) + if (ok) check(app) + } + }, "agent-quest-trust").start() + } + /** Opens the page where a provider's key is made, as the sign-in of a harness that takes pasted keys. */ fun openKeyPage(context: Context, page: String) = run(context, Step.SIGN_IN, listOf("/root/.local/bin/android-open", page)) @@ -202,7 +226,18 @@ object AgentSetup { /** The whole output of a step's last run; the card shows only its last line. */ fun logFile(app: Context, step: Step) = File(app.filesDir, "agent/setup-${step.name.lowercase()}.log") - fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git") + /** + * An install set up before setup wrote the Gradle init script gets the step again, but only + * once the checkout's setup writes it: the step runs that script, and an older one never would. + */ + fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git") && + (AgentHost.guestFileExists(app, GRADLE_INIT) || !setupWritesGradleInit(app)) + + private const val GRADLE_INIT = "/root/.gradle/init.d/droiddeck-device.gradle" + + private fun setupWritesGradleInit(app: Context) = runCatching { + File(LinuxRuntime.rootDir(app), "$CHECKOUT/tools/agent/setup".removePrefix("/")).readText().contains(GRADLE_INIT.substringAfterLast('/')) + }.getOrDefault(false) /** dd-lab-build compiled this install's commit, so a Lab build compiles only what changed. */ private fun prepared(app: Context) = runCatching { @@ -216,7 +251,7 @@ object AgentSetup { detail.clear() } - private fun probe(app: Context, harness: AgentHarness, step: Step, command: List) { + private fun probe(app: Context, harness: AgentHarness, step: Step, command: List, generation: Int) { var output = "" val ok = runCatching { val child = AgentHost.guest(app, command, connectAdb = step == Step.CONNECTION).start() @@ -232,11 +267,14 @@ object AgentSetup { }.onFailure { output = it.message.orEmpty() }.getOrDefault(false) main.post { if (AgentHost.harness != harness) return@post + // A running or newer Allow owns the row, including the instructions it shows while it waits. + if (step == Step.CONNECTION && (generation != connectionGeneration || status[step] == Status.WORKING)) return@post if (status[step] != Status.WORKING) status[step] = if (ok) Status.DONE else Status.TODO val last = output.lines().lastOrNull { it.isNotBlank() && !noise(it.trim()) }?.trim()?.take(160) when { ok -> detail.remove(step) - step == Step.CONNECTION -> detail[step] = app.getString(com.droiddeck.launcher.R.string.agent_connection_off) + step == Step.CONNECTION -> detail[step] = app.getString( + if (QuestExperimental.isSupported()) R.string.agent_connection_quest_off else R.string.agent_connection_off) step.required && last != null -> detail[step] = last } if (ready) AgentHost.prefs(app).edit().putBoolean(completedKey(harness), true).apply() diff --git a/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java index 8d9ddcb1f0..f87aefaa14 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/DirectAudioRelayComponent.java @@ -89,7 +89,7 @@ public class DirectAudioRelayComponent extends SessionPart { } } final java.io.PrintWriter log = out; - pid = HostProcess.start(command.toString(), env.toArray(new String[0]), + pid = HostProcess.startUncounted(command.toString(), env.toArray(new String[0]), app().getFilesDir(), null, line -> { Log.i(TAG, line); diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java index 53a0a6aacf..300a08b5f3 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java @@ -12,6 +12,7 @@ import com.droiddeck.launcher.core.TarZst; import java.io.File; import java.io.InputStream; import java.net.URL; +import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; @@ -36,9 +37,15 @@ public class PulseAudioComponent extends SessionPart { private final HostLifecycle host = new HostLifecycle(Process::killProcess); static final class HostLifecycle { + static final int MAX_STARTUP_CRASH_RESTARTS = 4; + private static final long[] STARTUP_RESTART_DELAYS_MS = {250L, 1000L, 2000L, 4000L}; + volatile int pid = -1; private long generation; private long launches; + private boolean preferStandardPerformanceMode; + private boolean sinkReady; + private int startupCrashRestarts; private final IntConsumer terminate; final ReentrantReadWriteLock commands = new ReentrantReadWriteLock(); @@ -48,6 +55,9 @@ public class PulseAudioComponent extends SessionPart { synchronized long begin() { stop(); + preferStandardPerformanceMode = false; + sinkReady = false; + startupCrashRestarts = 0; return generation; } @@ -55,6 +65,7 @@ public class PulseAudioComponent extends SessionPart { generation++; if (pid > 1) terminate.accept(pid); pid = -1; + sinkReady = false; } boolean launch(long expected, IntSupplier launch) { @@ -63,6 +74,7 @@ public class PulseAudioComponent extends SessionPart { synchronized (this) { if (expected != generation) return false; launches++; + sinkReady = false; pid = launch.getAsInt(); return true; } @@ -93,11 +105,45 @@ public class PulseAudioComponent extends SessionPart { return token == launches && pid > 1; } + synchronized boolean preferStandardPerformanceMode() { + return preferStandardPerformanceMode; + } + + synchronized void markLowLatencyFailed(long token) { + if (token == launches && pid > 1) preferStandardPerformanceMode = true; + } + + synchronized void markSinkReady(long token) { + if (token == launches && pid > 1) { + sinkReady = true; + startupCrashRestarts = 0; + } + } + synchronized boolean exited(long expected) { if (expected != generation || pid <= 1) return false; pid = -1; return true; } + + /** + * Decides whether a dead host should be restarted and after how many milliseconds. + * Returns 0 for immediate recovery of a host that had a working sink, a positive backoff + * while falling back to standard AAudio mode after a startup crash, or -1 to stop retrying. + */ + synchronized long nextRestartDelayMs(long expected) { + if (expected != generation) return -1L; + if (sinkReady) { + sinkReady = false; + startupCrashRestarts = 0; + return 0L; + } + preferStandardPerformanceMode = true; + if (startupCrashRestarts >= MAX_STARTUP_CRASH_RESTARTS) return -1L; + long delay = STARTUP_RESTART_DELAYS_MS[Math.min(startupCrashRestarts, STARTUP_RESTART_DELAYS_MS.length - 1)]; + startupCrashRestarts++; + return delay; + } } public PulseAudioComponent(Context context) { @@ -167,11 +213,14 @@ public class PulseAudioComponent extends SessionPart { if (micFifoPath != null && !micFifoPath.isEmpty()) { new File(micFifoPath).delete(); } + boolean standardMode = host.preferStandardPerformanceMode(); + String initialPerformanceMode = standardMode ? "0" : "1"; ArrayList config = new ArrayList<>(); config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\"" + socket().getAbsolutePath() + "\""); config.add(".nofail"); - config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls); + config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=" + + initialPerformanceMode + " adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls); config.add("set-default-sink DirectAudio"); config.add(".fail"); if (micFifoPath != null && !micFifoPath.isEmpty()) { @@ -186,15 +235,36 @@ public class PulseAudioComponent extends SessionPart { env.add("LD_LIBRARY_PATH=/system/lib64:" + modules + ":" + workingDir.getAbsolutePath()); env.add("HOME=" + workingDir); env.add("TMPDIR=" + workingDir); + // The daemon closes every fd at start but this one; in a worker process it is the binder + // fd whose closing Android takes for the process's death. + env.add("PULSE_PASSED_FD=" + com.droiddeck.launcher.runtime.GuestWorker.BINDER_FD_TOKEN); String command = String.join(" ", HostProcess.dataExecutable(workingDir.getAbsolutePath() + "/libpulseaudio.so")) + " --system=false --disable-shm=true --fail=false" + " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1" + " --log-level=info"; final java.io.PrintWriter out = openLog(); - if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> { + if (!host.launch(generation, () -> HostProcess.startUncounted(command, env.toArray(new String[0]), workingDir, status -> { if (host.exited(generation)) { - Log.w(TAG, "audio host exited with status " + status + "; restarting"); + long delayMs = host.nextRestartDelayMs(generation); + if (delayMs < 0) { + String msg = "audio host exited with status " + status + + " before a client sink came up too many times; not restarting again in this session"; + Log.w(TAG, msg); + note(out, msg); + return; + } + Log.w(TAG, "audio host exited with status " + status + "; restarting" + + (host.preferStandardPerformanceMode() ? " with standard AAudio mode" : "") + + (delayMs > 0 ? " in " + delayMs + " ms" : "")); + if (delayMs > 0) { + try { + Thread.sleep(delayMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } start(generation); } }, @@ -208,6 +278,24 @@ public class PulseAudioComponent extends SessionPart { guard.start(); } + private boolean loadDirectAudioSink(long token, String performanceMode) { + if ("0".equals(performanceMode)) pactlOk(token, "unload-module", "module-directaudio-native-sink"); + String loaded = pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", + "performance_mode=" + performanceMode, + "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls); + if (loaded == null) return false; + if (pactlOk(token, "set-default-sink", "DirectAudio")) return true; + String moduleId = loaded.trim(); + pactlOk(token, "unload-module", moduleId.matches("\\d+") ? moduleId : "module-directaudio-native-sink"); + return false; + } + + private boolean loadPlainAAudioSink(long token, String performanceMode) { + return pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", + "performance_mode=" + performanceMode, "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) + && pactlOk(token, "set-default-sink", "AAudioSink"); + } + private void ensureClientSink(java.io.PrintWriter out, long token) { try { // Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the @@ -229,27 +317,42 @@ public class PulseAudioComponent extends SessionPart { if (sinks == null) { line = "== client sink: the daemon did not answer in 30 s; no fallback attempted"; } else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) { - line = "== client sink: DirectAudio (module-directaudio-native-sink)"; + host.markSinkReady(token); + line = "== client sink: DirectAudio (module-directaudio-native-sink" + + (host.preferStandardPerformanceMode() ? ", standard mode" : "") + ")"; } else { // AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is - // still switching the output route as the session starts (seen on a Galaxy S24 FE): - // try DirectAudio again, then the plain sink, a few times over ten seconds. + // still switching the output route (Galaxy S24 FE) or when low-latency MMAP output + // is rejected by the HAL (Samsung One UI). Retry low-latency once if it hasn't been + // disqualified yet, then fall back to performance_mode=0 (non-MMAP) on DirectAudio + // before trying the plain AAudio sink. String loadedAs = null; for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) { try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } - if (pactlOk(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1", - "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) - && pactlOk(token, "set-default-sink", "DirectAudio")) { - loadedAs = "DirectAudio on attempt " + attempt; - } else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", - "performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) - && pactlOk(token, "set-default-sink", "AAudioSink")) { - loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt; + if (!host.live(token)) break; + if (attempt == 1 && !host.preferStandardPerformanceMode()) { + if (loadDirectAudioSink(token, "1")) { + loadedAs = "DirectAudio on attempt " + attempt; + break; + } + if (!host.live(token)) break; + host.markLowLatencyFailed(token); + } + if (loadDirectAudioSink(token, "0")) { + loadedAs = "DirectAudio (standard mode) on attempt " + attempt; + } else if (host.live(token) && loadPlainAAudioSink(token, "0")) { + loadedAs = "the plain AAudio sink (AAudioSink, standard mode) on attempt " + attempt; } } - line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs - : "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound." - + " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this"; + if (loadedAs != null) { + host.markSinkReady(token); + line = "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs; + } else if (!host.live(token)) { + line = "== client sink: audio host exited during sink recovery"; + } else { + line = "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound." + + " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this"; + } Log.w(TAG, line); } Log.i(TAG, line); @@ -404,11 +507,22 @@ public class PulseAudioComponent extends SessionPart { continue; } File destination = new File(workingDir, lib); + File temp = null; try (InputStream in = resource.openStream()) { - Files.copy(in, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); - FileUtils.chmod(destination, 0771); + temp = File.createTempFile(lib + ".", ".tmp", workingDir); + Files.copy(in, temp.toPath(), StandardCopyOption.REPLACE_EXISTING); + FileUtils.chmod(temp, 0771); + try { + Files.move(temp.toPath(), destination.toPath(), + StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(temp.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + temp = null; } catch (Exception e) { Log.w(TAG, "copy " + lib, e); + } finally { + if (temp != null) temp.delete(); } } } diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt index 55e7e61284..711a50eca3 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt @@ -61,7 +61,19 @@ object GameEnvironment { } fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map = - defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty() + defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else knownGames[scope].orEmpty() + config.games[scope].orEmpty() + + /** + * What some Steam games need here whatever the shared settings say; the game's own settings still win. + * GTA III dies at 0042A703 when a new game starts with FEX's reduced x87 precision, as the Rockstar store copy does. + */ + val knownGames: Map> = mapOf( + "12100" to mapOf("FEX_X87REDUCEDPRECISION" to "0"), + ) + + /** [config] with [knownGames] folded under each game's own settings, for the guest to read. */ + fun withKnownGames(config: Config): Config = + config.copy(games = config.games + knownGames.mapValues { (scope, known) -> known + config.games[scope].orEmpty() }) fun hasOverride(config: Config, scope: String, name: String): Boolean = scope.isNotEmpty() && config.entries(scope).containsKey(name) @@ -78,7 +90,7 @@ object GameEnvironment { val entries = config.games[scope].orEmpty() if (FexPreset.environmentKeys.none(entries::containsKey)) return null return FexPreset.all.firstOrNull { preset -> - val expected = FexPreset.environment(preset.id) + val expected = presetFor(scope, preset.id) FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] } }?.id ?: CUSTOM_FEX_PRESET } @@ -88,12 +100,16 @@ object GameEnvironment { require(preset == null || FexPreset.all.any { it.id == preset }) val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap() if (preset != null) { - val values = FexPreset.environment(preset) + val values = presetFor(scope, preset) FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] } } return config.withEntries(scope, entries) } + /** A FEX preset as a game gets it: picking one never undoes a fix the game is known to need. */ + private fun presetFor(scope: String, preset: String): Map = + FexPreset.environment(preset) + knownGames[scope].orEmpty().filterKeys { it in FexPreset.environmentKeys } + const val CUSTOM_FEX_PRESET = "__custom__" val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER) diff --git a/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt b/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt index 3e4bb53051..1daf377fb7 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GlobalSettings.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.core import android.content.Context +import android.content.pm.PackageManager import android.net.Uri import android.provider.Settings @@ -19,4 +20,14 @@ object GlobalSettings { fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED) fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled") + + /** + * True when it was off and is now on. Quest only, where Settings has no switch for it; it needs + * WRITE_SECURE_SETTINGS granted over adb. + */ + fun turnOnWirelessDebugging(context: Context): Boolean { + if (!com.droiddeck.launcher.session.QuestExperimental.isSupported() || wirelessDebuggingOn(context)) return false + if (context.checkSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) != PackageManager.PERMISSION_GRANTED) return false + return runCatching { Settings.Global.putInt(context.contentResolver, "adb_wifi_enabled", 1) }.getOrDefault(false) + } } diff --git a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt index d4a2cdc66d..d3a03036a3 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/HostProcess.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.core +import android.os.ParcelFileDescriptor import android.util.Log import java.io.File import java.util.function.Consumer @@ -7,6 +8,9 @@ import java.util.function.Consumer object HostProcess { private const val TAG = "HostProcess" private const val LINKER = "/system/bin/linker64" + // sh -c WORKER_CD sh DIR NAME=VALUE... -- PROGRAM ARGS... + private const val WORKER_CD = "cd \"\$1\" || exit 126; shift; " + + "while [ \$# -gt 0 ] && [ \"\$1\" != -- ]; do export \"\$1\"; shift; done; shift; exec \"\$@\"" /** Android 10+ refuses to execute app data files for targetSdk 29+; its linker still loads them. */ @JvmStatic @@ -65,6 +69,77 @@ object HostProcess { } } + /** + * As [start], but the program runs as the main process of one of the app's worker processes, + * which Android does not count against the app's child processes (docs/phantom-processes.md). + * Falls back to [start] when no worker is available. The exit status is the program's exit + * code, or 128 plus the signal that ended it, as Process.waitFor() reports it. + */ + @JvmStatic + @JvmOverloads + fun startUncounted(command: String, env: Array?, dir: File?, onExit: Consumer?, onLine: Consumer?, + outputFile: File? = null, onOutputComplete: Runnable? = null): Int { + val context = com.droiddeck.launcher.runtime.GuestWorkers.context + val argv = split(command) + // A missing working directory fails the launch (start() returns -1 for it), not the program + if (context == null || argv.isEmpty() || !com.droiddeck.launcher.runtime.GuestWorkers.enabled(context) || + (dir != null && !dir.isDirectory)) { + return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete) + } + val environment = LinkedHashMap(System.getenv()) + env?.forEach { line -> + val eq = line.indexOf('=') + if (eq > 0) environment[line.substring(0, eq)] = line.substring(eq + 1) + } + val assignments = environment.map { (k, v) -> "$k=$v" } + // A worker cannot chdir before its exec, so Android's shell does it. The shell starts with an + // environment of its own (the program's LD_PRELOAD of glibc libraries would stop it loading) + // and exports the program's before the exec. + val launch = if (dir != null) { + listOf("/system/bin/sh", "-c", WORKER_CD, "sh", dir.path) + assignments + listOf("--") + argv + } else argv + val workerEnv = if (dir != null) listOf("PATH=/system/bin") else assignments + var input: ParcelFileDescriptor? = null + var reader: ParcelFileDescriptor? = null + var output: ParcelFileDescriptor? = null + val pid = try { + input = ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_READ_ONLY) + output = when { + onLine != null -> ParcelFileDescriptor.createPipe().let { reader = it[0]; it[1] } + outputFile != null -> ParcelFileDescriptor.open(outputFile, + ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_APPEND) + else -> ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_WRITE_ONLY) + } + com.droiddeck.launcher.runtime.GuestWorkers.start(context, launch, workerEnv, listOf(input, output, output)) { status -> + onExit?.accept(if (status < 0) -1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f)) + } + } catch (e: Exception) { + Log.w(TAG, "no worker for ${argv.first()}", e) + -1 + } finally { + runCatching { input?.close() } + runCatching { output?.close() } + } + if (pid <= 0) { + reader?.close() + return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete) + } + Log.i(TAG, "started pid $pid outside the child-process count: ${argv.first()} (${argv.size - 1} arguments)") + reader?.let { pipe -> + Thread({ + try { + ParcelFileDescriptor.AutoCloseInputStream(pipe).bufferedReader().useLines { lines -> + lines.forEach { onLine?.accept(it) } + } + } catch (e: Exception) { + } finally { + onOutputComplete?.run() + } + }, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() } + } + return pid + } + @JvmStatic fun pidOf(process: Process): Int = try { val field = process.javaClass.getDeclaredField("pid") diff --git a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt index 6e67ff495d..5bcc716d1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt @@ -7,6 +7,8 @@ import com.droiddeck.launcher.R enum class PhantomProcessStatus { NOT_APPLICABLE, + /** The limit is on, but the session keeps its programs out of Android's count (GuestWorkers). */ + UNCOUNTED, DISABLED, ENABLED, UNSET, @@ -57,6 +59,12 @@ object PhantomProcessLimit { fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus { if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE + val status = readSetting(context, sdk) + return if (status != PhantomProcessStatus.DISABLED && com.droiddeck.launcher.runtime.GuestWorkers.limitHandled(context)) + PhantomProcessStatus.UNCOUNTED else status + } + + private fun readSetting(context: Context, sdk: Int): PhantomProcessStatus { if (usesDeviceConfig(sdk)) { val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false) val global = try { @@ -101,7 +109,8 @@ object PhantomProcessLimit { fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE fun blocksSteam(status: PhantomProcessStatus): Boolean = - status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED + status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED && + status != PhantomProcessStatus.UNCOUNTED fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) { PhantomProcessStatus.ENABLED -> R.string.phantom_title_on @@ -109,6 +118,7 @@ object PhantomProcessLimit { PhantomProcessStatus.UNREADABLE -> R.string.phantom_title_unreadable PhantomProcessStatus.DISABLED -> R.string.phantom_title_off PhantomProcessStatus.NOT_APPLICABLE -> R.string.phantom_title_not_required + PhantomProcessStatus.UNCOUNTED -> R.string.phantom_title_uncounted }) fun instructions(context: Context, status: PhantomProcessStatus): String = when (status) { @@ -116,6 +126,7 @@ object PhantomProcessLimit { context.getString(R.string.phantom_instructions_fix, fixSentence(context)) PhantomProcessStatus.DISABLED -> context.getString(R.string.phantom_instructions_off) PhantomProcessStatus.NOT_APPLICABLE -> context.getString(R.string.phantom_instructions_not_applicable) + PhantomProcessStatus.UNCOUNTED -> context.getString(R.string.phantom_instructions_uncounted) } fun gateInstructions(context: Context, status: PhantomProcessStatus): String = when (status) { @@ -132,5 +143,6 @@ object PhantomProcessLimit { PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)" PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)" PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12" + PhantomProcessStatus.UNCOUNTED -> "on, not needed (most of the session's programs run in uncounted worker processes)" } } diff --git a/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt b/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt index 650a6b8d4d..42524b5dcb 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt @@ -28,17 +28,18 @@ object SessionLogCapture { out.flush() writer = out this.target = target - pid = HostProcess.start( + pid = HostProcess.startUncounted( command(Process.myPid(), sinceMillis), null, target.parentFile, null, - ) { line -> - synchronized(this) { - try { - writer?.apply { write(line); newLine(); flush() } - } catch (e: Exception) { + onLine = { line -> + synchronized(this) { + try { + writer?.apply { write(line); newLine(); flush() } + } catch (e: Exception) { + } } - } - } + }, + ) if (pid == -1) { out.write("logcat could not be started; this ROM may not hand an app its own entries.\n") out.flush() diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt index 5c8b32f7ba..64087a24f3 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt @@ -22,6 +22,9 @@ object WirelessAdbFix { private const val HOST_FILE = "wireless-adb-host.txt" private const val CONNECTION_FILE = "wireless-adb-connection.txt" const val LOOPBACK = "127.0.0.1" + private const val TCP_PORT = 5555 + private const val WIRELESS_START_MS = 2_000L + private const val NETWORK_PROMPT_MS = 30_000L private data class SavedConnection(val host: String, val port: Int?) @@ -55,6 +58,23 @@ object WirelessAdbFix { writeAtomically(context, File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0)) } + /** + * Quest has no pairing screen. adbd in TCP mode (`adb tcpip 5555`) asks "Allow debugging?" for an + * unknown key, and Wireless debugging accepts a key allowed there, so this stands in for pairing. + * Blocks until the prompt is answered or times out. + */ + fun trustOnDevice(context: Context) { + val app = context.applicationContext + // Already trusted, as after a reboot: Wireless debugging takes the key, and port 5555 is closed by then. + val live = if (savedConnection(app) != null) liveConnectAddress(app) else null + if (live != null && acceptsKey(app, live.substringBeforeLast(':').trim('[', ']'), live.substringAfterLast(':').toInt())) return + GlobalSettings.turnOnWirelessDebugging(app) + loadOrCreateIdentity(app) + Kadb.create(LOOPBACK, TCP_PORT, 2_000, 120_000).use { check(it.shell("true").exitCode == 0) } + writeAtomically(app, File(app.noBackupFilesDir, HOST_FILE), LOOPBACK.toByteArray()) + writeAtomically(app, File(app.noBackupFilesDir, CONNECTION_FILE), ByteArray(0)) + } + private fun savedConnection(context: Context): SavedConnection? { val directory = context.applicationContext.noBackupFilesDir if (!File(directory, CERT_FILE).isFile || !File(directory, KEY_FILE).isFile) return null @@ -78,10 +98,17 @@ object WirelessAdbFix { fun liveConnectAddress(context: Context): String? { val app = context.applicationContext val saved = savedConnection(app) ?: return null + val turnedOn = GlobalSettings.turnOnWirelessDebugging(app) val host = if (':' in saved.host) "[${saved.host}]" else saved.host - saved.port?.takeIf { answers(saved.host, it) }?.let { return "$host:$it" } + if (!turnedOn) saved.port?.takeIf { answers(saved.host, it) }?.let { return "$host:$it" } val loopback = runCatching { InetAddress.getByName(saved.host).isLoopbackAddress }.getOrDefault(false) - val port = if (loopback) loopbackAdbPort(app) else findConnectPort(app, saved.host, accept = { answers(saved.host, it) }) + // Turning it on can first ask "Allow wireless debugging on this network?", so keep looking while that is answered. + val deadline = android.os.SystemClock.elapsedRealtime() + if (turnedOn) NETWORK_PROMPT_MS else 0L + var port: Int? + do { + if (turnedOn) Thread.sleep(WIRELESS_START_MS) + port = if (loopback) loopbackAdbPort(app) else findConnectPort(app, saved.host, accept = { answers(saved.host, it) }) + } while (port == null && android.os.SystemClock.elapsedRealtime() < deadline) port ?: return null saveConnection(app, saved.host, port) return "$host:$port" @@ -105,10 +132,12 @@ object WirelessAdbFix { } }.apply { start() } }.forEach { it.join() } + return open.sorted().firstOrNull { port -> acceptsKey(app, LOOPBACK, port) } + } + + private fun acceptsKey(app: Context, host: String, port: Int): Boolean { loadOrCreateIdentity(app) - return open.sorted().firstOrNull { port -> - runCatching { Kadb.create(LOOPBACK, port, 1_000, 3_000).use { it.shell("true").exitCode == 0 } }.getOrDefault(false) - } + return runCatching { Kadb.create(host, port, 1_000, 3_000).use { it.shell("true").exitCode == 0 } }.getOrDefault(false) } private val EPHEMERAL_PORTS = 32768..60999 diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt index 25124a6a52..2ae97cfc4f 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt @@ -10,11 +10,13 @@ object FrameGen { const val ENGINE_DDFG = "ddfg" private const val LEGACY_ENGINE_WINFG = "winfg" const val ENGINE_LSFG = "lsfg" + const val ENGINE_ZEROFG = "zerofg" private const val DDFG_PERF_PRESET = 2 private const val DDFG_MODEL = 4 private const val FLOW_SCALE_DDFG = 0.60f private const val FLOW_SCALE_LSFG = 0.80f + private const val FLOW_SCALE_ZEROFG = 1.0f val ADAPTIVE_TARGETS = listOf(120, 90, 60) @@ -69,6 +71,14 @@ object FrameGen { .putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply() } + fun pacerEnabled(context: Context): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean("pacer", false) + + fun setPacer(context: Context, enabled: Boolean) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("pacer", enabled).apply() + WaylandCompositor.nativeSetFrameGenPacer(enabled) + } + fun clearGlobal(context: Context) { context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() .remove("engine").remove("multiplier").remove("target").apply() @@ -80,6 +90,7 @@ object FrameGen { mode.engine == ENGINE_DDFG -> context.getString(R.string.frame_gen_ddfg, mode.multiplier) mode.engine == ENGINE_LSFG && mode.target > 0 -> context.getString(R.string.frame_gen_lsfg_adaptive, mode.target) mode.engine == ENGINE_LSFG -> context.getString(R.string.frame_gen_lsfg, mode.multiplier) + mode.engine == ENGINE_ZEROFG -> context.getString(R.string.frame_gen_zerofg, mode.multiplier) else -> context.getString(R.string.frame_gen_off) } @@ -104,6 +115,7 @@ object FrameGen { fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? { val mode = prepared.mode + WaylandCompositor.nativeSetFrameGenPacer(pacerEnabled(context)) when (mode.engine) { ENGINE_LSFG -> { val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED @@ -111,7 +123,7 @@ object FrameGen { if (status != LsfgNative.STATUS_OK || cachePath == null) { WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) val problem = context.getString( - if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed, + if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_needs_steam else R.string.lsfg_problem_failed, ) Log.w(TAG, "$problem (status $status)") return problem @@ -127,6 +139,11 @@ object FrameGen { WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_DDFG, refreshHz) WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0) } + ENGINE_ZEROFG -> { + WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_ZEROFG) + WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_ZEROFG, refreshHz) + WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0) + } else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) } Log.i(TAG, "frame generation: $mode at ${refreshHz}Hz") diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt b/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt index f78cb629ee..352885f558 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt @@ -2,22 +2,16 @@ package com.droiddeck.launcher.gpu import android.content.Context import android.util.Log -import com.droiddeck.launcher.R import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.GameStorage -import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.security.DigestOutputStream import java.security.MessageDigest object Lossless { - enum class Source { NONE, STEAM, IMPORT } - - enum class ImportResult { UPDATED, UNCHANGED, NOT_OWNED, INVALID, FAILED } - - data class State(val owned: Boolean, val ready: Boolean, val source: Source) { + data class State(val owned: Boolean, val ready: Boolean) { companion object { - val NONE = State(owned = false, ready = false, source = Source.NONE) + val NONE = State(owned = false, ready = false) } } @@ -26,15 +20,13 @@ object Lossless { private const val KEY_OWNED = "owned" private const val KEY_ID = "id" private const val KEY_SOURCE = "source" + private const val SOURCE_STEAM = "STEAM" private const val KEY_STEAM_STAMP = "steamStamp" + private const val STEAM_MANIFEST = "steamapps/appmanifest_993090.acf" private const val STEAM_DLL = "steamapps/common/Lossless Scaling/Lossless.dll" private const val UNCHANGED = -1 - fun state(context: Context): State { - val source = prefs(context).getString(KEY_SOURCE, null) - ?.let { name -> Source.entries.firstOrNull { it.name == name } } ?: Source.NONE - return State(owned(context), cacheFile(context)?.isFile == true, source) - } + fun state(context: Context) = State(owned(context), cacheFile(context)?.isFile == true) fun owned(context: Context): Boolean { if (prefs(context).getBoolean(KEY_OWNED, false)) return true @@ -43,61 +35,46 @@ object Lossless { return true } - fun cacheFile(context: Context): File? = prefs(context).getString(KEY_ID, null)?.let { cacheFor(context, it) } + fun cacheFile(context: Context): File? = steamCacheId(context)?.let { cacheFor(context, it) } + + private fun steamCacheId(context: Context): String? = prefs(context).let { + if (it.getString(KEY_SOURCE, null) == SOURCE_STEAM) it.getString(KEY_ID, null) else null + } @Synchronized fun sync(context: Context): Int { + val settings = prefs(context) + if (steamCacheId(context) == null && settings.contains(KEY_ID)) { + settings.edit().remove(KEY_ID).remove(KEY_SOURCE).remove(KEY_STEAM_STAMP).apply() + } val steam = steamDll(context) if (steam != null) { markOwned(context) val stamp = "${steam.length()}:${steam.lastModified()}" - if (stamp != prefs(context).getString(KEY_STEAM_STAMP, null)) { - val status = adopt(context, steam, Source.STEAM) + if (stamp != settings.getString(KEY_STEAM_STAMP, null)) { + val status = adoptSteamDll(context, steam) if (status != LsfgNative.STATUS_OK && status != UNCHANGED) { Log.w(TAG, "Steam copy $steam not taken: ${statusName(status)}") } - prefs(context).edit().putString(KEY_STEAM_STAMP, stamp).apply() + settings.edit().putString(KEY_STEAM_STAMP, stamp).apply() } } return ensureBuilt(context) } - @Synchronized - fun import(context: Context, dll: File): ImportResult { - if (!owned(context)) return ImportResult.NOT_OWNED - return when (adopt(context, dll, Source.IMPORT)) { - UNCHANGED -> ImportResult.UNCHANGED - LsfgNative.STATUS_OK -> ImportResult.UPDATED - LsfgNative.STATUS_UNREADABLE_FILE, LsfgNative.STATUS_NOT_PORTABLE_EXECUTABLE, - LsfgNative.STATUS_MISSING_SHADERS -> ImportResult.INVALID - else -> ImportResult.FAILED - } - } - - fun message(context: Context, result: ImportResult): String = context.getString( - when (result) { - ImportResult.UPDATED -> R.string.lsfg_imported - ImportResult.UNCHANGED -> R.string.lsfg_import_unchanged - ImportResult.NOT_OWNED -> R.string.lsfg_import_not_owned - ImportResult.INVALID -> R.string.lsfg_import_invalid - ImportResult.FAILED -> R.string.lsfg_import_failed - }, - ) - private fun ensureBuilt(context: Context): Int { - val id = prefs(context).getString(KEY_ID, null) ?: return LsfgNative.STATUS_NOT_INSTALLED - val cache = cacheFor(context, id) + val cache = cacheFile(context) ?: return LsfgNative.STATUS_NOT_INSTALLED if (usable(cache)) return LsfgNative.STATUS_OK val dll = storedDll(context) if (!dll.isFile) return LsfgNative.STATUS_NOT_INSTALLED return build(dll, cache) } - private fun adopt(context: Context, source: File, from: Source): Int { + private fun adoptSteamDll(context: Context, source: File): Int { val staged = File(dir(context).apply { mkdirs() }, "Lossless.dll.staged") try { val id = copyHashing(source, staged) - if (id == prefs(context).getString(KEY_ID, null) && usable(cacheFor(context, id))) return UNCHANGED + if (id == steamCacheId(context) && usable(cacheFor(context, id))) return UNCHANGED val cache = cacheFor(context, id) var status = LsfgNative.nativeValidateDll(staged.path) if (status == LsfgNative.STATUS_OK) status = build(staged, cache) @@ -109,9 +86,9 @@ object Lossless { cache.delete() return LsfgNative.STATUS_CACHE_UNUSABLE } - prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, from.name).apply() + prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, SOURCE_STEAM).apply() removeStale(context, id) - Log.i(TAG, "Lossless.dll from $source ($from) ready as $id") + Log.i(TAG, "Steam Lossless.dll from $source ready as $id") return LsfgNative.STATUS_OK } catch (e: java.io.IOException) { Log.w(TAG, "could not copy $source", e) @@ -158,9 +135,13 @@ object Lossless { GameStorage.effective(context)?.path?.let(::File), GameStorage.x64CardLibrary(context), ) + com.droiddeck.launcher.frontend.AddedGames.roots(context).map { it.host } - return libraries.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() } + return installedSteamDll(libraries) } + internal fun installedSteamDll(libraries: List): File? = + libraries.asSequence().filter { File(it, STEAM_MANIFEST).isFile } + .map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() } + private fun markOwned(context: Context) { if (!prefs(context).getBoolean(KEY_OWNED, false)) prefs(context).edit().putBoolean(KEY_OWNED, true).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudConfig.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudConfig.kt index 3427acc31d..c82e76ab5e 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudConfig.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudConfig.kt @@ -11,7 +11,7 @@ internal object DroidDeckHudConfig { "showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0", "showVram" to "1", "showRAM" to "1", "showSwap" to "1", "showBattery" to "0", "showBatteryTime" to "0", "showPower" to "1", "showFPS" to "1", "showFPSGraph" to "1", "fpsDecimal" to "1", - "showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", + "showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "0", "showLow001" to "0", "showEngine" to "1", "showRenderer" to "1", "showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showUpscale" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "", diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt index c5f39c65ae..b519e395c8 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt @@ -92,8 +92,8 @@ class DroidDeckHudView(context: Context) : View(context) { private var showBatteryTemp = false private var showGraph = false private var showLow1 = true - private var showLow01 = true - private var showLow001 = true + private var showLow01 = false + private var showLow001 = false private var fpsDecimal = true private var showClockTime = true private var showLatency = true @@ -188,6 +188,12 @@ class DroidDeckHudView(context: Context) : View(context) { private var graphRect: RectF? = null private var contentW = 0f private var contentH = 0f + private var viewportW = Float.POSITIVE_INFINITY + private var viewportH = Float.POSITIVE_INFINITY + + private val panelFit: Float + get() = if (dPanel == null || contentW <= 0f || contentH <= 0f) 1f + else minOf(1f, viewportW / contentW, viewportH / contentH) private var onMovedListener: BiConsumer? = null private var onSizeCycledListener: Consumer? = null @@ -998,13 +1004,20 @@ class DroidDeckHudView(context: Context) : View(context) { } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + viewportW = viewportLimit(widthMeasureSpec) + viewportH = viewportLimit(heightMeasureSpec) if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return } + val fit = panelFit setMeasuredDimension( - resolveSize(contentW.roundToInt(), widthMeasureSpec), - resolveSize(contentH.roundToInt(), heightMeasureSpec), + resolveSize((contentW * fit).roundToInt(), widthMeasureSpec), + resolveSize((contentH * fit).roundToInt(), heightMeasureSpec), ) } + private fun viewportLimit(spec: Int): Float = + if (MeasureSpec.getMode(spec) == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY + else MeasureSpec.getSize(spec).toFloat() + override fun onDraw(canvas: Canvas) { if (contentW <= 0f || contentH <= 0f) { lockController.drawBadge(canvas); return } val blend = if (dock == DroidDeckHudDock.NONE && previewEdge != DroidDeckHudDock.NONE) previewBlend else 0f @@ -1039,8 +1052,10 @@ class DroidDeckHudView(context: Context) : View(context) { } private fun drawContent(canvas: Canvas) { - - dPanel?.let { panel -> panelFrame(panel)?.let { canvas.drawBitmap(it, 0f, 0f, null) } } + val fit = panelFit + dPanel?.let { panel -> panelFrame(panel, fit)?.let { canvas.drawBitmap(it, 0f, 0f, null) } } + val saved = canvas.save() + if (fit != 1f) canvas.scale(fit, fit) if (tileRects.isNotEmpty()) { tilePaint.color = Color.argb((14 * bgOpacity).roundToInt().coerceIn(8, 40), 255, 255, 255) @@ -1070,6 +1085,7 @@ class DroidDeckHudView(context: Context) : View(context) { if (stripRect != null && layerType != LAYER_TYPE_SOFTWARE) drawCachedGraph(canvas, it) else drawGraph(canvas, it) } + canvas.restoreToCount(saved) lockController.drawBadge(canvas) } @@ -1182,13 +1198,14 @@ class DroidDeckHudView(context: Context) : View(context) { return if (dy <= 0f) p.right - stroke else if (dy >= r) cx else cx + sqrt(r * r - dy * dy) } - private fun panelFrame(panel: RectF): Bitmap? { + private fun panelFrame(panel: RectF, fit: Float): Bitmap? { if (width <= 0 || height <= 0) return null val stroke = outlineWidth() - val key = "$width,$height,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}" + val key = "$width,$height,$fit,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}" if (key == dFrameKey) dFrame?.let { return it } val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val c = Canvas(bmp) + c.scale(fit, fit) val corner = sp(6f) val body = dShape(panel.left, panel.top, panel.right, panel.bottom, dRadius, corner) bgPaint.color = panelColor() @@ -1261,8 +1278,8 @@ class DroidDeckHudView(context: Context) : View(context) { internal val isStrip: Boolean get() = stripRect != null - internal val contentWidth: Float get() = contentW - internal val contentHeight: Float get() = contentH + internal val contentWidth: Float get() = contentW * panelFit + internal val contentHeight: Float get() = contentH * panelFit internal val isDragging: Boolean get() = lockController.isDragging() || tabDragging diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt index 907d71c70d..d6958f7b17 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt @@ -46,7 +46,14 @@ internal class ControllerPortraitGeometry( } row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit) var bodyTop = top + pad + buttonHeight + gap - if (presented.any { it.control in REAR && isStock(it) }) { + if (presented.any { it.control in REAR && isStock(it) } && docked) { + val chipHeight = 36f * unit + val cell = (w - 2f * pad - 5f * gap) / 6f + listOf(0, 1, 4, 5).zip(REAR).forEach { (index, control) -> + put(control, Box(safe.left + pad + cell / 2f + index * (cell + gap), bodyTop + chipHeight / 2f, cell, chipHeight)) + } + bodyTop += chipHeight + gap + } else if (presented.any { it.control in REAR && isStock(it) }) { val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight) row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap) bodyTop += rearHeight + gap diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt index 83ae4abc47..73782d7e63 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt @@ -19,6 +19,7 @@ object ControllerPrefs { ) val opacities = listOf(40, 60, 80, 100) + val onScreenOpacityRange = 10..100 val sizes = listOf(80, 85, 90, 95, 100, 105, 110, 115, 120, 125) @@ -45,6 +46,7 @@ object ControllerPrefs { val size: Int, val stickClick: Boolean, val adaptiveSticks: Boolean, + val onScreenOpacity: Int, val rumble: Boolean, val steamButton: Boolean, val qamButton: Boolean, @@ -66,7 +68,8 @@ object ControllerPrefs { opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100, size = p.getInt("size", 100).takeIf { it in sizes } ?: 100, stickClick = p.getBoolean("stickClick", true), - adaptiveSticks = p.getBoolean("adaptiveSticks", true), + adaptiveSticks = p.getBoolean("adaptiveSticks", false), + onScreenOpacity = onScreenOpacity(context), rumble = rumbleEnabled(context), steamButton = p.getBoolean("steamButton", true), qamButton = p.getBoolean("qamButton", true), @@ -103,6 +106,13 @@ object ControllerPrefs { prefs(context).edit().putBoolean("stickClick", on).apply() } + fun onScreenOpacity(context: Context): Int = + prefs(context).getInt("onScreenOpacity", 100).coerceIn(onScreenOpacityRange) + + fun setOnScreenOpacity(context: Context, percent: Int) { + prefs(context).edit().putInt("onScreenOpacity", percent.coerceIn(onScreenOpacityRange)).apply() + } + fun setAdaptiveSticks(context: Context, on: Boolean) { prefs(context).edit().putBoolean("adaptiveSticks", on).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt b/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt index 1fdb6121fc..41cf641275 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt @@ -2,14 +2,24 @@ package com.droiddeck.launcher.input class HeldInput(private val emit: (Int, Boolean) -> Unit) { private val owners = IntArray(768) + private val ordered = arrayOfNulls<(Int, Boolean) -> Unit>(768) @Synchronized - fun set(source: Int, code: Int, down: Boolean) { + fun set(source: Int, code: Int, down: Boolean, orderedEmit: ((Int, Boolean) -> Unit)? = null) { if (code !in owners.indices) return val before = owners[code] val after = if (down) before or source else before and source.inv() owners[code] = after - if ((before == 0) != (after == 0)) emit(code, after != 0) + if ((before == 0) != (after == 0)) { + if (after != 0) { + ordered[code] = orderedEmit + orderedEmit?.invoke(code, true) ?: emit(code, true) + } else { + val fn = ordered[code] + ordered[code] = null + fn?.invoke(code, false) ?: emit(code, false) + } + } } @Synchronized @@ -21,7 +31,9 @@ class HeldInput(private val emit: (Int, Boolean) -> Unit) { fun clear() { for (code in owners.indices) if (owners[code] != 0) { owners[code] = 0 - emit(code, false) + val fn = ordered[code] + ordered[code] = null + fn?.invoke(code, false) ?: emit(code, false) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt b/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt index 5372be6db5..a9549c9918 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt @@ -4,7 +4,6 @@ import android.app.Activity import android.content.Context import android.os.Build import android.text.InputType -import android.view.KeyCharacterMap import android.view.KeyEvent import android.view.View import android.view.WindowInsets @@ -12,15 +11,17 @@ import android.view.inputmethod.BaseInputConnection import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection import android.view.inputmethod.InputMethodManager +import com.droiddeck.launcher.wayland.WaylandCompositor class KeyboardHost( context: Context, private val sendKeyEvent: (KeyEvent) -> Boolean, + private val sendText: (String) -> Unit, ) : View(context) { - constructor(activity: Activity) : this(activity, { activity.dispatchKeyEvent(it) }) + constructor(activity: Activity) : + this(activity, { activity.dispatchKeyEvent(it) }, { WaylandCompositor.textInputCommit(it) }) private val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager - private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD) var shown = false private set var imeShowing = false @@ -40,8 +41,7 @@ class KeyboardHost( override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? { if (!shown) return null - outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or - InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD + outAttrs.inputType = InputType.TYPE_CLASS_TEXT outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI return KeyConnection() @@ -93,45 +93,153 @@ class KeyboardHost( fun type(text: CharSequence?) { if (text.isNullOrEmpty()) return - val events = map.getEvents(text.toString().toCharArray()) - if (events != null) { - for (event in events) sendKeyEvent(event) - } else { - for (ch in text) { - val t = System.currentTimeMillis() - val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0, - KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0) - sendKeyEvent(CharKeyEvent(down, ch)) - sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch)) - } - } + // Text and soft editing actions share this queue to preserve IME ordering. + sendText(text.toString()) } fun tap(keyCode: Int) { + val control = softControl(keyCode) + if (control != null) { + sendText(control.toString()) + return + } val t = System.currentTimeMillis() sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0)) sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0)) } private inner class KeyConnection : BaseInputConnection(this, false) { + // A press keeps the route chosen on its first down across repeats and the matching up. + private val controlRoutes = HashMap() + + private var composingText = "" + private var composingCursor = 0 + override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean { + composingText = "" + composingCursor = 0 type(text) return true } - override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = true - override fun finishComposingText(): Boolean = true - - override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { - repeat(beforeLength) { tap(KeyEvent.KEYCODE_DEL) } - repeat(afterLength) { tap(KeyEvent.KEYCODE_FORWARD_DEL) } + override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean { + composingText = text?.toString().orEmpty() + val rawCursor = if (newCursorPosition > 0) { + composingText.length.toLong() + newCursorPosition - 1L + } else { + newCursorPosition.toLong() + } + composingCursor = rawCursor.coerceIn(0L, composingText.length.toLong()).toInt() return true } - override fun sendKeyEvent(event: KeyEvent): Boolean = this@KeyboardHost.sendKeyEvent(event) + override fun finishComposingText(): Boolean { + val text = composingText + composingText = "" + composingCursor = 0 + type(text) + return true + } + + override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { + val before = beforeLength.coerceAtLeast(0) + val after = afterLength.coerceAtLeast(0) + if (before == 0 && after == 0) return true + val consumedBefore = minOf(before, composingCursor) + val consumedAfter = minOf(after, composingText.length - composingCursor) + val guestBefore = before - consumedBefore + val guestAfter = after - consumedAfter + if (guestBefore > 1 || guestAfter > 1) return false + return applyDeletion( + composingCursor - consumedBefore, + composingCursor + consumedAfter, + guestBefore, + guestAfter, + ) + } + + override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean { + val before = beforeLength.coerceAtLeast(0) + val after = afterLength.coerceAtLeast(0) + if (before == 0 && after == 0) return true + if (splitsPair(composingCursor)) return false + val text = composingText + val beforePoints = Character.codePointCount(text, 0, composingCursor) + val afterPoints = Character.codePointCount(text, composingCursor, text.length) + val consumedBefore = minOf(before, beforePoints) + val consumedAfter = minOf(after, afterPoints) + val start = Character.offsetByCodePoints(text, composingCursor, -consumedBefore) + val end = Character.offsetByCodePoints(text, composingCursor, consumedAfter) + if (hasUnpairedSurrogate(text, start, end)) return false + return applyDeletion( + start, + end, + before - consumedBefore, + after - consumedAfter, + ) + } + + private fun applyDeletion(start: Int, end: Int, guestBefore: Int, guestAfter: Int): Boolean { + if (guestBefore > 64 || guestAfter > 64) return false + if (splitsPair(start) || splitsPair(end)) return false + if (start < end) { + composingText = composingText.removeRange(start, end) + composingCursor = start + } + val controls = StringBuilder() + repeat(guestBefore) { controls.append(BACKSPACE) } + repeat(guestAfter) { controls.append(FORWARD_DELETE) } + if (controls.isNotEmpty()) sendText(controls.toString()) + return true + } + + private fun splitsPair(index: Int): Boolean = + index > 0 && index < composingText.length && + composingText[index - 1].isHighSurrogate() && composingText[index].isLowSurrogate() + + private fun hasUnpairedSurrogate(text: CharSequence, start: Int, end: Int): Boolean { + var i = start + while (i < end) { + val c = text[i] + if (c.isHighSurrogate()) { + if (i + 1 >= end || !text[i + 1].isLowSurrogate()) return true + i += 2 + } else if (c.isLowSurrogate()) { + return true + } else { + i++ + } + } + return false + } + + override fun sendKeyEvent(event: KeyEvent): Boolean { + val control = softControl(event.keyCode) + if (control == null) return this@KeyboardHost.sendKeyEvent(event) + if (event.action == KeyEvent.ACTION_DOWN) { + val soft = if (event.repeatCount == 0) { + val route = !event.isModified() + controlRoutes[event.keyCode] = route + route + } else { + controlRoutes[event.keyCode] ?: !event.isModified() + } + if (!soft) return this@KeyboardHost.sendKeyEvent(event) + if (control == ENTER) finishComposingText() + sendText(control.toString()) + return true + } + if (event.action == KeyEvent.ACTION_UP) { + val soft = controlRoutes.remove(event.keyCode) ?: !event.isModified() + if (soft) return true + return this@KeyboardHost.sendKeyEvent(event) + } + return this@KeyboardHost.sendKeyEvent(event) + } override fun performEditorAction(actionCode: Int): Boolean { - tap(KeyEvent.KEYCODE_ENTER) + finishComposingText() + sendText(ENTER.toString()) return true } @@ -140,8 +248,22 @@ class KeyboardHost( override fun getSelectedText(flags: Int): CharSequence? = null } - private class CharKeyEvent(origin: KeyEvent, private val ch: Char) : KeyEvent(origin) { - override fun getUnicodeChar(): Int = ch.code - override fun getUnicodeChar(metaState: Int): Int = ch.code + private fun softControl(keyCode: Int): Char? = when (keyCode) { + KeyEvent.KEYCODE_DEL -> BACKSPACE + KeyEvent.KEYCODE_FORWARD_DEL -> FORWARD_DELETE + KeyEvent.KEYCODE_ENTER -> ENTER + KeyEvent.KEYCODE_TAB -> TAB + else -> null + } + + private fun KeyEvent.isModified(): Boolean = + isCtrlPressed || isShiftPressed || isAltPressed || isMetaPressed + + private companion object { + // Control characters represent editing keys on the guest text channel. + const val ENTER = '\r' + const val BACKSPACE = '\b' + const val FORWARD_DELETE = '\u007f' + const val TAB = '\t' } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index e8490f624f..88ecec5fc7 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -36,6 +36,13 @@ object OnScreenLayout { fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect, buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null, trackpads: Boolean? = null): List { + val placed = placeElements(context, saved, width, height, safe, buttonsOnly, dock, rearButtons, trackpads) + // Below the game a stick covers nothing, so it keeps its base in view instead of appearing only under the thumb. + return if (dock == null) placed else placed.map { if (it.kind == InputElementKind.STICK) it.copy(hideWhenIdle = false) else it } + } + + private fun placeElements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect, + buttonsOnly: Boolean, dock: Dock?, rearButtons: Boolean?, trackpads: Boolean?): List { if (saved == null) return emptyList() if (width <= 0 || height <= 0) return saved.elements val layout = oriented(saved, dock?.portrait ?: (height > width)) diff --git a/app/src/main/java/com/droiddeck/launcher/input/SessionTextInput.kt b/app/src/main/java/com/droiddeck/launcher/input/SessionTextInput.kt new file mode 100644 index 0000000000..387351def2 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/SessionTextInput.kt @@ -0,0 +1,327 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.net.LocalSocket +import android.net.LocalSocketAddress +import android.os.Handler +import android.os.Looper +import android.util.Log +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.io.File +import java.io.IOException +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.ScheduledThreadPoolExecutor +import java.util.concurrent.TimeUnit + +private enum class TextDelivery(val result: Int) { + NOT_DELIVERED(WaylandCompositor.TEXT_NOT_DELIVERED), + DELIVERED(WaylandCompositor.TEXT_DELIVERED), + UNRESOLVED(WaylandCompositor.TEXT_UNRESOLVED), +} + +class SessionTextInput(context: Context, private val hasFocus: () -> Boolean) { + private val delivery = deliveryFor(context) + private val owner = Any() + + fun start() = delivery.start(owner, hasFocus) + fun stop() = delivery.stop(owner) + + private companion object { + private var instance: SessionTextDelivery? = null + + @Synchronized private fun deliveryFor(context: Context): SessionTextDelivery = + instance ?: SessionTextDelivery(context.applicationContext).also { instance = it } + } +} + +private class SessionTextDelivery(private val appContext: Context) { + private val handler = Handler(Looper.getMainLooper()) + private val lock = Any() + private var generation = 0L + @Volatile private var active = false + private var owner: Any? = null + private var focusCheck: (() -> Boolean)? = null + private var executor: ScheduledThreadPoolExecutor? = null + private var socket: LocalSocket? = null + private var pendingToken = 0 + private var runningToken = 0 + private var failedToken = 0 + private val guestListener = object : WaylandCompositor.TextInputFallbackListener { + override fun onTextInputFallback(text: String, token: Int): Boolean { + synchronized(lock) { + if (!active || pendingToken != 0 || failedToken != 0 || token <= 0) return false + val received = generation + pendingToken = token + val posted = try { + handler.post { enqueue(text, received, token) } + } catch (e: RuntimeException) { + false + } + if (!posted) pendingToken = 0 + return posted + } + } + } + + fun start(nextOwner: Any, hasFocus: () -> Boolean) { + val previous = synchronized(lock) { + if (owner === nextOwner) return + owner + } + if (previous != null) stop(previous) + val queue = ScheduledThreadPoolExecutor(1) { runnable -> + Thread(runnable, "session-text-input").apply { isDaemon = true } + } + queue.executeExistingDelayedTasksAfterShutdownPolicy = false + synchronized(lock) { + this.owner = nextOwner + focusCheck = hasFocus + active = true + executor = queue + if (failedToken != 0) scheduleRetryLocked(failedToken, INITIAL_DELAY_MS) + } + WaylandCompositor.setTextInputFallbackListener(guestListener) + } + + fun stop(oldOwner: Any) { + val detached = synchronized(lock) { + if (owner !== oldOwner) return + owner = null + focusCheck = null + active = false + generation += 1 + val queue = executor + val open = socket + val token = if (runningToken == 0 && failedToken == 0) pendingToken else 0 + executor = null + socket = null + Triple(queue, open, token) + } + WaylandCompositor.clearTextInputFallbackListener(guestListener) + handler.removeCallbacksAndMessages(null) + detached.second?.let { requestCancel(it) } + detached.first?.shutdown() + if (detached.third != 0) complete(detached.third) + } + + private fun enqueue(text: String, received: Long, token: Int) { + val currentFocus = synchronized(lock) { if (active && generation == received) focusCheck else null } + if (currentFocus == null || !currentFocus() || !WaylandCompositor.isTextInputFallbackListener(guestListener)) { + Log.d(TAG, "guest text fallback skipped outside the active focused session") + complete(token) + return + } + val bytes = text.toByteArray(Charsets.UTF_8) + if (bytes.isEmpty() || bytes.size > MAX_BYTES) { + complete(token) + return + } + val queue = synchronized(lock) { + if (active && generation == received) executor else null + } + if (queue == null) { + complete(token) + return + } + try { + queue.execute { + try { + val delivery = send(bytes, received, token) + if (delivery == TextDelivery.UNRESOLVED) recover(token) + else complete(token, delivery) + } finally { + releaseRunning(token) + } + } + } catch (e: RejectedExecutionException) { + complete(token) + } + } + + private fun recover(token: Int) { + if (probe()) { + complete(token) + return + } + val marked = synchronized(lock) { + if (pendingToken == token && failedToken == 0) { + failedToken = token + WaylandCompositor.completeTextInputFallback(token, TextDelivery.UNRESOLVED.result) + scheduleRetryLocked(token, INITIAL_DELAY_MS) + true + } else { + false + } + } + if (marked) Log.w(TAG, "text injection could not be confirmed") + } + + private fun scheduleRetryLocked(token: Int, delayMs: Long) { + if (!active || failedToken != token || pendingToken != token) return + val queue = executor ?: return + val current = generation + try { + queue.schedule({ retryProbe(current, token, delayMs) }, delayMs, TimeUnit.MILLISECONDS) + } catch (e: RejectedExecutionException) { + } + } + + private fun retryProbe(received: Long, token: Int, delayMs: Long) { + val ready = synchronized(lock) { + active && generation == received && failedToken == token && pendingToken == token + } + if (!ready) return + val proven = probe() + val owned = synchronized(lock) { + if (proven) { + if (active && generation == received && failedToken == token && pendingToken == token) { + pendingToken = 0 + runningToken = 0 + failedToken = 0 + true + } else { + false + } + } else { + if (active && generation == received && failedToken == token && pendingToken == token) { + val next = (delayMs * 2).coerceAtMost(MAX_DELAY_MS) + scheduleRetryLocked(token, next) + } + false + } + } + if (owned) WaylandCompositor.completeTextInputFallback(token, TextDelivery.NOT_DELIVERED.result) + } + + private fun probe(): Boolean { + val live = LocalSocket() + return try { + live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM)) + live.soTimeout = TIMEOUT_MS + val out = live.outputStream + out.write(lengthPrefix(0)) + out.flush() + live.inputStream.read() == 0 + } catch (e: IOException) { + Log.w(TAG, "could not probe guest text input state", e) + false + } finally { + close(live) + } + } + + private fun complete(token: Int, delivery: TextDelivery = TextDelivery.NOT_DELIVERED) { + val owned = synchronized(lock) { + if (pendingToken == token) { + pendingToken = 0 + runningToken = 0 + failedToken = 0 + true + } else { + false + } + } + if (owned) WaylandCompositor.completeTextInputFallback(token, delivery.result) + } + + private fun releaseRunning(token: Int) { + synchronized(lock) { + if (runningToken == token) runningToken = 0 + } + } + + private fun send(bytes: ByteArray, received: Long, token: Int): TextDelivery { + val live = LocalSocket() + if (!claim(live, received, token)) { + close(live) + return TextDelivery.NOT_DELIVERED + } + var requested = false + try { + live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM)) + live.soTimeout = TIMEOUT_MS + if (!isCurrent(received)) return TextDelivery.NOT_DELIVERED + val out = live.outputStream + out.write(lengthPrefix(bytes.size)) + requested = true + out.write(bytes) + out.flush() + val input = live.inputStream + val ack = try { + input.read() + } catch (e: IOException) { + // Android may report a socket read timeout as a plain IOException. + requestCancel(live) + input.read() + } + if (ack == 0) Log.d(TAG, "guest did not complete text delivery") + if (ack != 0 && ack != 1 && isCurrent(received)) Log.w(TAG, "guest did not acknowledge text delivery") + return when (ack) { + 1 -> TextDelivery.DELIVERED + 0 -> TextDelivery.NOT_DELIVERED + else -> TextDelivery.UNRESOLVED + } + } catch (e: IOException) { + if (isCurrent(received)) Log.w(TAG, "could not hand text to the guest", e) + if (!requested) return TextDelivery.NOT_DELIVERED + return TextDelivery.UNRESOLVED + } finally { + release(live) + close(live) + } + } + + private fun requestCancel(live: LocalSocket) { + try { + live.shutdownOutput() + } catch (e: IOException) { + Log.w(TAG, "could not request guest text input cancellation", e) + } + } + + private fun isCurrent(received: Long) = synchronized(lock) { active && generation == received } + + private fun claim(live: LocalSocket, received: Long, token: Int) = synchronized(lock) { + if (!active || generation != received || pendingToken != token || runningToken != 0 || failedToken != 0) { + false + } else { + runningToken = token + socket = live + true + } + } + + private fun release(live: LocalSocket) { + synchronized(lock) { + if (socket === live) socket = null + } + } + + private fun endpoint(): File = File(LinuxRuntime.sessionRoot(appContext), "text-input.sock") + + private fun lengthPrefix(size: Int): ByteArray { + val flagged = if (size == 0) size else size or Int.MIN_VALUE + return byteArrayOf( + (flagged ushr 24).toByte(), + (flagged ushr 16).toByte(), + (flagged ushr 8).toByte(), + flagged.toByte(), + ) + } + + private fun close(sock: LocalSocket) { + try { + sock.close() + } catch (e: IOException) { + } + } + + private companion object { + const val TAG = "SessionTextInput" + const val MAX_BYTES = 65536 + const val TIMEOUT_MS = 3000 + const val INITIAL_DELAY_MS = 500L + const val MAX_DELAY_MS = 5000L + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/ElfSeccompPatch.kt b/app/src/main/java/com/droiddeck/launcher/runtime/ElfSeccompPatch.kt index 817cbc9757..8ebf839fd7 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/ElfSeccompPatch.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/ElfSeccompPatch.kt @@ -38,6 +38,11 @@ object ElfSeccompPatch { val end = minOf(data.size, buffer.getLong(at + 8).toInt() + buffer.getLong(at + 32).toInt()) and 3.inv() var pos = start while (pos + 4 <= end) { + if (patchTermiosRequest(buffer, pos, end)) { + patched++ + pos += 4 + continue + } val replacement = when (buffer.getInt(pos)) { MOV_X8_SET_ROBUST_LIST -> NOP MOV_X8_CLONE3, MOV_X8_RSEQ -> MOV_X0_ENOSYS @@ -65,6 +70,40 @@ object ElfSeccompPatch { return patched } + /** + * glibc 2.42 and later read and set a terminal with TCGETS2 and TCSETS2/W2/F2, which Android's + * SELinux policy refuses on an app's pseudo-terminal slaves (EACCES): isatty() was false in every + * Konsole, ssh and tmux session, so bash had no prompt or job control and stdout was not line + * buffered. TCGETS and TCSETS* carry the same struct without its two speed fields, which glibc + * then takes from c_cflag. A site is `movz xN, #lo` then `movk xN, #hi, lsl #16`; the movz gets + * the old request and the movk becomes a no-op. + */ + private fun patchTermiosRequest(buffer: ByteBuffer, pos: Int, end: Int): Boolean { + val movz = buffer.getInt(pos) + if ((movz and 0x7fe00000) != 0x52800000) return false + val low = (movz ushr 5) and 0xffff + if (low !in 0x542a..0x542d) return false + val register = movz and 0x1f + var next = pos + 4 + while (next < minOf(end, pos + 4 + 4 * 4)) { + val movk = buffer.getInt(next) + if ((movk and 0x7fe00000) == 0x72a00000 && (movk and 0x1f) == register) { + val request = when ((movk ushr 5) and 0xffff) { + 0x802c -> if (low == 0x542a) 0x5401 else return false + 0x402c -> if (low != 0x542a) 0x5402 + (low - 0x542b) else return false + else -> return false + } + buffer.putInt(pos, (movz and 0x1f.inv() and (0xffff shl 5).inv()) or (request shl 5) or register) + buffer.putInt(next, NOP) + return true + } + // Anything between that might read or write the register would see the old low half + if (intArrayOf(0, 5, 10, 16).any { (movk ushr it) and 0x1f == register }) return false + next += 4 + } + return false + } + /** Patches the file behind [path] (symlinks followed) if it still has unpatched call sites. */ fun patchFile(path: File): Int { val target = path.canonicalFile diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt b/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt new file mode 100644 index 0000000000..403a8c59cc --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt @@ -0,0 +1,271 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.os.SystemClock +import android.system.Os +import android.system.OsConstants +import android.util.Log +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.io.File +import java.io.InputStream +import java.nio.file.Files +import java.nio.file.LinkOption.NOFOLLOW_LINKS +import java.security.MessageDigest + +/** One app-issued Steam session and one attested Gamescope worker. This is not an + * isolation boundary against arbitrary code already running as the Android app UID. */ +internal object FrameAcquireWorkerProbe { + private const val SESSION_SCRIPT = "/usr/local/bin/droiddeck-session" + private const val PATH = "/usr/local/bin/gamescope" + private const val CAPABILITY = "linuxfs/usr/local/share/droiddeck/gamescope-producer-acquire-v1" + internal const val GAMESCOPE_ENABLE = "GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE=1" + internal const val GAME_ENABLE = "DROIDDECK_GAME_DROIDDECK_GAME_FRAME_ACQUIRE=1" + private const val MAX_BINARY_BYTES = 32L * 1024L * 1024L + internal const val RECEIPT_TAG = 0x44445046 + internal const val RECEIPT_BYTES = Int.SIZE_BYTES + Long.SIZE_BYTES + private const val TTL_MS = 90_000L + + internal data class Ticket( + val owner: Int, val root: File, val configuredRoot: File, val binary: File, + val expected: ByteArray, val expires: Long, val steamGameUrl: String?, + ) + internal data class Qualified(val ticket: Ticket, val dev: Long, val ino: Long, val mtime: Long, val ctime: Long) + private var intent: Ticket? = null + private var nativeOwner = 0 + private var nativePid = 0 + + private enum class Stage { ARM, MATCH, PUBLISH } + private enum class Reason { + ENABLED, MATCH_ACK, MATCH_OWNER, MATCH_EXPIRED, MATCH_PATH, MATCH_ROOT, + MATCH_ARGV, MATCH_FILE, MATCH_DIGEST, QUALIFIED, PUBLISH_TICKET, PUBLISH_RESTAT, + PUBLISH_NATIVE, PUBLISH_RECEIPT, RESERVED + } + private val reported = mutableSetOf() + @Synchronized private fun breadcrumb(stage: Stage, reason: Reason) { + if (reported.add(stage)) Log.i("FrameAcquireWorkerProbe", "worker_admission=" + reason.name) + } + + internal fun validEnvironment(agentEnvironment: List, customEnvironment: List): Boolean { + // AgentEnv supplies a replacement PATH whenever any executable override is staged. + // Custom env is user-editable, including names not known to this build; it is not a trust root. + return agentEnvironment.isEmpty() && customEnvironment.isEmpty() + } + + fun available(context: Context): Boolean = + android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.core.DeviceSupport.adreno() && + runCatching { context.assets.open(CAPABILITY).use { it.readBytes().decodeToString() } } + .getOrNull() == "droiddeck-producer-acquire-v1\n" + + private fun digest(input: InputStream, maxBytes: Long): ByteArray { + val out = MessageDigest.getInstance("SHA-256") + val buffer = ByteArray(64 * 1024) + var size = 0L + while (true) { + val n = input.read(buffer) + if (n == -1) break + require(n > 0) + size += n + require(size <= maxBytes) + out.update(buffer, 0, n) + } + require(size > 0) + return out.digest() + } + + // Compute asset identity outside SessionService's stop lock and before a worker + // exists. The resulting ticket still has to be assigned to that exact owner. + private const val STEAM_RUN_PREFIX = "steam://rungameid/" + + internal fun permittedLaunch(url: String?, frontendGame: Boolean): Boolean = + if (url == null) !frontendGame else frontendGame && url.startsWith(STEAM_RUN_PREFIX) && + com.droiddeck.launcher.frontend.GameLaunchLink.validId(url.removePrefix(STEAM_RUN_PREFIX)) + + internal fun prepare(context: Context, steamGameUrl: String?, frontendGame: Boolean): Ticket? { + if (!permittedLaunch(steamGameUrl, frontendGame) || + !available(context) || !WaylandCompositor.frameWorkerProbeEnabled()) return null + return runCatching { + val configuredRoot = LinuxRuntime.rootDir(context).absoluteFile + val root = configuredRoot.canonicalFile + val file = File(root.path + PATH) + require(file.canonicalFile == file && Files.isRegularFile(file.toPath(), NOFOLLOW_LINKS)) + val script = File(root.path + SESSION_SCRIPT) + require(exactSteamScript(SESSION_SCRIPT, root, configuredRoot)) + val stagedScript = script.inputStream().use { digest(it, 1024L * 1024L) } + val signedScript = context.assets.open("linuxfs" + SESSION_SCRIPT).use { digest(it, 1024L * 1024L) } + require(MessageDigest.isEqual(stagedScript, signedScript)) + val expected = context.assets.open("linuxfs" + PATH).use { digest(it, MAX_BINARY_BYTES) } + Ticket(0, root, configuredRoot, file, expected, SystemClock.elapsedRealtime() + TTL_MS, steamGameUrl) + }.getOrNull() + } + + @Synchronized fun arm(owner: Int, prepared: Ticket): Boolean { + if (owner <= 0 || SystemClock.elapsedRealtime() >= prepared.expires) return false + reported.clear() + intent = prepared.copy(owner = owner) + breadcrumb(Stage.ARM, Reason.ENABLED) + return true + } + + /** Native shebang handling can give Bash the staged host filename as its $0. */ + internal fun exactSteamScript(token: String, root: File, configuredRoot: File): Boolean { + if (token != SESSION_SCRIPT && token != root.path + SESSION_SCRIPT && + token != configuredRoot.path + SESSION_SCRIPT) return false + return runCatching { + val expected = File(root.path + SESSION_SCRIPT) + val supplied = if (token == SESSION_SCRIPT) expected else File(token) + // Reject symlinks within the authorized root, including a symlink replacing the script. + // Android's configured root itself may be an alias of its app-issued canonical root. + require(configuredRoot.canonicalFile == root && expected.canonicalFile == expected && + supplied.canonicalFile == expected && + Files.isRegularFile(expected.toPath(), NOFOLLOW_LINKS) && + Files.isRegularFile(supplied.toPath(), NOFOLLOW_LINKS)) + Files.isSameFile(supplied.toPath(), expected.toPath()) + }.getOrDefault(false) + } + + internal fun exactGamescopeArgs( + argv: List, steamGameUrl: String? = null, script: (String) -> Boolean, + ): Boolean { + if (argv.firstOrNull() !in listOf("gamescope", PATH)) return false + val delimiter = argv.indexOf("--") + val tailSize = if (steamGameUrl == null) 3 else 4 + if (delimiter < 4 || argv.size != delimiter + tailSize || argv[delimiter + 2] != "steam" || + !script(argv[delimiter + 1]) || + (steamGameUrl != null && (!permittedLaunch(steamGameUrl, true) || argv.last() != steamGameUrl))) return false + val opts = argv.subList(1, delimiter) + if (opts.take(4) != listOf("--backend", "wayland", "--expose-wayland", "-f")) return false + val dimensions = setOf("-W", "-H", "-w", "-h") + val seen = mutableSetOf() + var i = 4 + while (i < opts.size) { + val option = opts[i++] + if (!seen.add(option)) return false + when (option) { + "-e", "--hdr-enabled", "--mangoapp" -> Unit + "-S" -> if (opts.getOrNull(i++) != "stretch") return false + "--default-touch-mode" -> if (opts.getOrNull(i++) != "4") return false + "-W", "-H", "-w", "-h", "-r", "--xwayland-count" -> { + val value = opts.getOrNull(i++) ?: return false + if (value.length !in 1..6 || value.any { it !in '0'..'9' } || + value.toIntOrNull()?.let { it > 0 } != true) return false + } + else -> return false + } + } + return seen.containsAll(dimensions) + } + + fun match(owner: Int, root: File, file: String, argv: List, ack: Boolean): Qualified? { + val t = synchronized(this) { intent } ?: return null + // Startup's --version worker and unrelated workers must not consume the one diagnostic. + val candidate = "--version" !in argv && (file.substringAfterLast('/') == "gamescope" || + argv.firstOrNull()?.substringAfterLast('/') == "gamescope") + val rejection = when { + !ack -> Reason.MATCH_ACK + t.owner != owner -> Reason.MATCH_OWNER + SystemClock.elapsedRealtime() >= t.expires -> Reason.MATCH_EXPIRED + file != PATH -> Reason.MATCH_PATH + runCatching { root.canonicalFile }.getOrNull() != t.root -> Reason.MATCH_ROOT + !exactGamescopeArgs(argv, t.steamGameUrl) { exactSteamScript(it, t.root, t.configuredRoot) } -> Reason.MATCH_ARGV + else -> null + } + if (rejection != null) { + if (candidate) breadcrumb(Stage.MATCH, rejection) + return null + } + // Hash an actual descriptor rather than two pathname opens. Check both the + // descriptor and pathname identity; a race or substituted executable denies the grant. + val qualified = runCatching { + require(t.binary.canonicalFile == t.binary) + val before = Os.lstat(t.binary.path) + require(OsConstants.S_ISREG(before.st_mode) && before.st_size in 1..MAX_BINARY_BYTES) + val fd = Os.open(t.binary.path, OsConstants.O_RDONLY or OsConstants.O_NOFOLLOW or OsConstants.O_CLOEXEC, 0) + val sum = try { + require(stillSame(before, Os.fstat(fd))) + android.os.ParcelFileDescriptor.AutoCloseInputStream(android.os.ParcelFileDescriptor.dup(fd)).use { + digest(it, MAX_BINARY_BYTES) + }.also { require(stillSame(before, Os.fstat(fd))) } + } finally { + Os.close(fd) + } + val after = Os.lstat(t.binary.path) + require(stillSame(before, after)) + if (!MessageDigest.isEqual(sum, t.expected)) { + breadcrumb(Stage.MATCH, Reason.MATCH_DIGEST) + return null + } + Qualified(t, after.st_dev, after.st_ino, after.st_mtime, after.st_ctime) + }.getOrNull() + breadcrumb(Stage.MATCH, if (qualified == null) Reason.MATCH_FILE else Reason.QUALIFIED) + return qualified + } + + private fun stillSame(a: android.system.StructStat, b: android.system.StructStat): Boolean = + a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_size == b.st_size && + a.st_mtime == b.st_mtime && a.st_ctime == b.st_ctime && + OsConstants.S_ISREG(b.st_mode) + + internal fun validReceipt(pid: Int, workerPid: Int, ticks: Long, bytes: Int): Long = + if (pid > 1 && pid == workerPid && ticks > 0 && bytes == RECEIPT_BYTES) ticks else 0L + + internal fun parseSelfStat(stat: String, pid: Int): Long { + if (pid <= 1 || !stat.startsWith("$pid (")) return 0L + val comm = stat.lastIndexOf(')') + if (comm < 3 || stat.getOrNull(comm + 1) != ' ') return 0L + val fields = stat.substring(comm + 2).split(' ').filter { it.isNotEmpty() } + if (fields.firstOrNull()?.length != 1 || fields.size < 21) return 0L + val value = fields[19] // field 22 from field 3 (the single-character task state). + return value.takeIf { it.isNotEmpty() && it.all { ch -> ch in '0'..'9' } } + ?.toLongOrNull()?.takeIf { it > 0 } ?: 0L + } + + internal fun selfStartTicks(pid: Int): Long = runCatching { + File("/proc/self/stat").inputStream().use { input -> + val bytes = ByteArray(4096) + var used = 0 + while (used < bytes.size) { + val n = input.read(bytes, used, bytes.size - used) + if (n < 0) break + if (n == 0) return@runCatching 0L + used += n + } + if (used == bytes.size || used == 0 || bytes[used-1] != '\n'.code.toByte()) 0L + else parseSelfStat(String(bytes, 0, used, Charsets.US_ASCII), pid) + } + }.getOrDefault(0L) + + /** Runs just before the final GO byte. Failure never changes ordinary launch. */ + @Synchronized fun publish(q: Qualified, pid: Int, startTicks: Long) { + val t = q.ticket + if (intent !== t || pid <= 1 || SystemClock.elapsedRealtime() >= t.expires) { + if (intent === t) breadcrumb(Stage.PUBLISH, Reason.PUBLISH_TICKET) + return + } + intent = null // At most one candidate per explicitly armed session. + if (startTicks <= 0L) { + breadcrumb(Stage.PUBLISH, Reason.PUBLISH_RECEIPT) + return + } + val status = runCatching { + val st = Os.lstat(t.binary.path) + require(OsConstants.S_ISREG(st.st_mode) && st.st_dev == q.dev && st.st_ino == q.ino && + st.st_mtime == q.mtime && st.st_ctime == q.ctime) + if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino, startTicks)) { + nativeOwner = t.owner + nativePid = pid + Reason.RESERVED + } else Reason.PUBLISH_NATIVE + }.getOrDefault(Reason.PUBLISH_RESTAT) + breadcrumb(Stage.PUBLISH, status) + } + + @Synchronized fun revoke(owner: Int, pid: Int = 0) { + if (owner <= 0) return + if (pid == 0 && intent?.owner == owner) intent = null + if (nativeOwner == owner && (pid == 0 || pid == nativePid)) { + WaylandCompositor.frameWorkerProbeRevoke(owner, pid) + nativeOwner = 0 + nativePid = 0 + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt new file mode 100644 index 0000000000..e3f7d0ba01 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -0,0 +1,1008 @@ +package com.droiddeck.launcher.runtime + +import android.app.ActivityManager +import android.app.Service +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.net.LocalServerSocket +import android.net.LocalSocket +import android.os.Binder +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.Parcel +import android.os.ParcelFileDescriptor +import android.os.Process +import android.system.ErrnoException +import android.system.Os +import android.system.OsConstants +import android.system.StructPollfd +import android.util.Log +import org.json.JSONObject +import java.io.DataInputStream +import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +/** + * A guest program run as the main process of its own Android process. + * + * Android counts the processes in an app process's cgroup against its child-process limit, but not + * the app processes themselves. The worker execs the program in place; its binder fd stays open + * across the exec, so the system keeps the process as a live service process. The program's own + * children are still counted. See docs/phantom-processes.md. + */ +open class GuestWorker : Service() { + private val binder = object : Binder() { + override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean { + if (code != RUN) return super.onTransact(code, data, reply, flags) + val argv = data.createStringArray() ?: return false + val env = data.createStringArray() ?: return false + val fds = List(data.readInt()) { data.readFileDescriptor() } + val targets = data.createIntArray() ?: IntArray(fds.size) { it } + val fillBinderFd = data.readInt() != 0 + val go = data.readFileDescriptor() + val nice = data.readInt() + val pid = Process.myPid() + reply?.writeInt(pid) + // Optional fixed-size receipt, on the exact local, non-exported worker's Binder. + // Nothing in the guest socket request populates these fields. + if (reply != null && + Binder.getCallingUid() == Process.myUid() && + data.dataAvail() == Int.SIZE_BYTES && data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG) { + reply.writeInt(pid) + reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid)) + } + Handler(Looper.getMainLooper()).post { + // The app writes a byte once it has the reply and has taken the launch on: an exec + // before then would end this process with the reply undelivered, and with none (the + // app gave up and starts the program another way) the program must not run here. + var why = "" + // poll() with a timeout counts as network I/O to StrictMode on the main thread + android.os.StrictMode.setThreadPolicy(android.os.StrictMode.ThreadPolicy.LAX) + val committed = runCatching { + fun byte(timeout: Int): Int { + val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() } + val ready = Os.poll(arrayOf(poll), timeout) + return (if (ready > 0) Os.read(go.fileDescriptor, ByteArray(1), 0, 1) else -1) + .also { why = "poll $ready revents ${poll.revents} read $it" } + } + // The commit, an answer, and the app's word that it has the answer: the app may + // have stopped waiting for it (and started the program another way) meanwhile. + // That last word comes, or the app closes its end (a byte or EOF): no timeout, + // which could drop a launch the app has already reported as started. + byte(GO_TIMEOUT_MS) == 1 && Os.write(go.fileDescriptor, byteArrayOf(1), 0, 1) == 1 && byte(-1) == 1 + }.getOrElse { why = it.toString(); false } + go.close() + if (committed) exec(argv, env, fds, targets, fillBinderFd, nice) + else { + Log.w(TAG, "launch not committed ($why): not running ${argv.firstOrNull()}") + Process.killProcess(Process.myPid()) + } + } + return true + } + } + + override fun onBind(intent: Intent): IBinder = binder + + private fun exec(argv: Array, env: Array, fds: List, targets: IntArray, fillBinderFd: Boolean, + nice: Int) { + try { + val top = targets.maxOrNull() ?: 2 + val (binderTop, binderFd) = keepBinderOpen(maxOf(BINDER_FDS, top + 1)) + // Out of the way first, so that placing one fd cannot overwrite another not yet placed. + val above = maxOf(MOVED_FDS, top + 1, binderTop + 1) + val moved = fds.map { pfd -> pfd?.let { Os.fcntlInt(it.fileDescriptor, OsConstants.F_DUPFD, above) } } + moved.forEachIndexed { i, fd -> + if (fd == null || i >= targets.size) return@forEachIndexed + val source = ParcelFileDescriptor.adoptFd(fd).also { kept.add(it) }.fileDescriptor + Os.dup2(source, targets[i]) + Os.fcntlInt(source, OsConstants.F_SETFD, OsConstants.FD_CLOEXEC) + } + // A session of its own: in zygote's process group, a program signalling its group + // (kill(0, sig)) would reach every process of the app. + runCatching { Os.setsid() } + // The native hook closes the binder fds in every other process (hook/handoff.c). Only an + // app launch asks for the number (a whole argument or variable value), never a guest's. + val fill = { arg: String -> + if (!fillBinderFd) arg + else if (arg == BINDER_FD_TOKEN) binderFd.toString() + else if (arg.endsWith("=$BINDER_FD_TOKEN")) arg.removeSuffix(BINDER_FD_TOKEN) + binderFd + else arg + } + // This thread blocks SIGQUIT, SIGUSR1 and SIGPIPE (Android's runtime), and an exec keeps + // that: the program's hook sets DDH_SIGMASK instead (none blocked, unless the request says). + val mask = if (env.any { it.startsWith("DDH_SIGMASK=") }) emptyList() else listOf("DDH_SIGMASK=0") + // Android raised this thread to THREAD_PRIORITY_TOP_APP_BOOST (a service the top app binds with + // BIND_IMPORTANT is scheduled as the top app); the program and its threads would keep it and + // run ahead of the game. They get the asker's priority instead, as a forked child would. + runCatching { Process.setThreadPriority(nice) } + Os.execve(argv[0], argv.map(fill).toTypedArray(), + env.filterNot { it.startsWith("DDH_WORKER_PID=") }.map(fill).toTypedArray() + mask + + "DDH_WORKER_PID=${Process.myPid()}") + } catch (e: ErrnoException) { + Log.e(TAG, "could not exec ${argv.firstOrNull()}", e) + } + Process.killProcess(Process.myPid()) + } + + /** + * Binder fds stay open across the exec, at [from] or above, where no fd of the program goes. + * Returns the highest fd used and the one on /dev/binder, whose closing Android takes for + * the death of this process. + */ + private fun keepBinderOpen(from: Int): Pair { + var highest = from - 1 + var binder = -1 + File("/proc/self/fd").listFiles()?.forEach { link -> + val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach + if (target !in BINDER_DEVICES && !target.startsWith("/dev/binderfs/")) return@forEach + // A copy, not adoptFd(): some of these fds are owned (fdsan) by a ParcelFileDescriptor. + val copy = runCatching { ParcelFileDescriptor.fromFd(link.name.toIntOrNull() ?: return@forEach) }.getOrNull() + ?: return@forEach + val kept = Os.fcntlInt(copy.fileDescriptor, OsConstants.F_DUPFD, from) + highest = maxOf(highest, kept) + if (target.substringAfterLast('/') == "binder") binder = kept + copy.close() + } + return highest to binder + } + + companion object { + const val RUN = IBinder.FIRST_CALL_TRANSACTION + /** An argument, or a variable's whole value, in an app launch: replaced by the number of its kept binder fd. */ + const val BINDER_FD_TOKEN = "@DDH_WORKER_BINDER_FD@" + // Longer than the app may wait for the hook's "go" (GuestWorkers.ACK_TIMEOUT_MS) before it commits + private const val GO_TIMEOUT_MS = 15000 + private val BINDER_DEVICES = setOf("/dev/binder", "/dev/hwbinder", "/dev/vndbinder") + private const val BINDER_FDS = 900 + private const val MOVED_FDS = 1200 + private const val TAG = "GuestWorker" + private val kept = ArrayList() + + fun isWorkerProcess(context: Context, process: String?): Boolean = + process != null && process.startsWith(context.packageName + ":g") && + process.substring(context.packageName.length + 2).all { it.isDigit() } + } +} + +class GuestWorker0 : GuestWorker() +class GuestWorker1 : GuestWorker() +class GuestWorker2 : GuestWorker() +class GuestWorker3 : GuestWorker() +class GuestWorker4 : GuestWorker() +class GuestWorker5 : GuestWorker() +class GuestWorker6 : GuestWorker() +class GuestWorker7 : GuestWorker() +class GuestWorker8 : GuestWorker() +class GuestWorker9 : GuestWorker() +class GuestWorker10 : GuestWorker() +class GuestWorker11 : GuestWorker() +class GuestWorker12 : GuestWorker() +class GuestWorker13 : GuestWorker() +class GuestWorker14 : GuestWorker() +class GuestWorker15 : GuestWorker() +class GuestWorker16 : GuestWorker() +class GuestWorker17 : GuestWorker() +class GuestWorker18 : GuestWorker() +class GuestWorker19 : GuestWorker() +class GuestWorker20 : GuestWorker() +class GuestWorker21 : GuestWorker() +class GuestWorker22 : GuestWorker() +class GuestWorker23 : GuestWorker() +class GuestWorker24 : GuestWorker() +class GuestWorker25 : GuestWorker() +class GuestWorker26 : GuestWorker() +class GuestWorker27 : GuestWorker() +class GuestWorker28 : GuestWorker() +class GuestWorker29 : GuestWorker() +class GuestWorker30 : GuestWorker() +class GuestWorker31 : GuestWorker() +class GuestWorker32 : GuestWorker() +class GuestWorker33 : GuestWorker() +class GuestWorker34 : GuestWorker() +class GuestWorker35 : GuestWorker() +class GuestWorker36 : GuestWorker() +class GuestWorker37 : GuestWorker() +class GuestWorker38 : GuestWorker() +class GuestWorker39 : GuestWorker() +class GuestWorker40 : GuestWorker() +class GuestWorker41 : GuestWorker() +class GuestWorker42 : GuestWorker() +class GuestWorker43 : GuestWorker() +class GuestWorker44 : GuestWorker() +class GuestWorker45 : GuestWorker() +class GuestWorker46 : GuestWorker() +class GuestWorker47 : GuestWorker() +class GuestWorker48 : GuestWorker() +class GuestWorker49 : GuestWorker() +class GuestWorker50 : GuestWorker() +class GuestWorker51 : GuestWorker() +class GuestWorker52 : GuestWorker() +class GuestWorker53 : GuestWorker() +class GuestWorker54 : GuestWorker() +class GuestWorker55 : GuestWorker() +class GuestWorker56 : GuestWorker() +class GuestWorker57 : GuestWorker() +class GuestWorker58 : GuestWorker() +class GuestWorker59 : GuestWorker() +class GuestWorker60 : GuestWorker() +class GuestWorker61 : GuestWorker() +class GuestWorker62 : GuestWorker() +class GuestWorker63 : GuestWorker() +class GuestWorker64 : GuestWorker() +class GuestWorker65 : GuestWorker() +class GuestWorker66 : GuestWorker() +class GuestWorker67 : GuestWorker() +class GuestWorker68 : GuestWorker() +class GuestWorker69 : GuestWorker() +class GuestWorker70 : GuestWorker() +class GuestWorker71 : GuestWorker() +class GuestWorker72 : GuestWorker() +class GuestWorker73 : GuestWorker() +class GuestWorker74 : GuestWorker() +class GuestWorker75 : GuestWorker() +class GuestWorker76 : GuestWorker() +class GuestWorker77 : GuestWorker() +class GuestWorker78 : GuestWorker() +class GuestWorker79 : GuestWorker() +class GuestWorker80 : GuestWorker() +class GuestWorker81 : GuestWorker() +class GuestWorker82 : GuestWorker() +class GuestWorker83 : GuestWorker() +class GuestWorker84 : GuestWorker() +class GuestWorker85 : GuestWorker() +class GuestWorker86 : GuestWorker() +class GuestWorker87 : GuestWorker() +class GuestWorker88 : GuestWorker() +class GuestWorker89 : GuestWorker() +class GuestWorker90 : GuestWorker() +class GuestWorker91 : GuestWorker() +class GuestWorker92 : GuestWorker() +class GuestWorker93 : GuestWorker() +class GuestWorker94 : GuestWorker() +class GuestWorker95 : GuestWorker() +class GuestWorker96 : GuestWorker() +class GuestWorker97 : GuestWorker() +class GuestWorker98 : GuestWorker() +class GuestWorker99 : GuestWorker() +class GuestWorker100 : GuestWorker() +class GuestWorker101 : GuestWorker() +class GuestWorker102 : GuestWorker() +class GuestWorker103 : GuestWorker() +class GuestWorker104 : GuestWorker() +class GuestWorker105 : GuestWorker() +class GuestWorker106 : GuestWorker() +class GuestWorker107 : GuestWorker() +class GuestWorker108 : GuestWorker() +class GuestWorker109 : GuestWorker() +class GuestWorker110 : GuestWorker() +class GuestWorker111 : GuestWorker() +class GuestWorker112 : GuestWorker() +class GuestWorker113 : GuestWorker() +class GuestWorker114 : GuestWorker() +class GuestWorker115 : GuestWorker() +class GuestWorker116 : GuestWorker() +class GuestWorker117 : GuestWorker() +class GuestWorker118 : GuestWorker() +class GuestWorker119 : GuestWorker() +class GuestWorker120 : GuestWorker() +class GuestWorker121 : GuestWorker() +class GuestWorker122 : GuestWorker() +class GuestWorker123 : GuestWorker() +class GuestWorker124 : GuestWorker() +class GuestWorker125 : GuestWorker() +class GuestWorker126 : GuestWorker() +class GuestWorker127 : GuestWorker() + +/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */ +object GuestWorkers { + private const val TAG = "GuestWorkers" + private val classes: List> = listOf( + GuestWorker0::class.java, GuestWorker1::class.java, GuestWorker2::class.java, + GuestWorker3::class.java, GuestWorker4::class.java, GuestWorker5::class.java, + GuestWorker6::class.java, GuestWorker7::class.java, GuestWorker8::class.java, + GuestWorker9::class.java, GuestWorker10::class.java, GuestWorker11::class.java, + GuestWorker12::class.java, GuestWorker13::class.java, GuestWorker14::class.java, + GuestWorker15::class.java, GuestWorker16::class.java, GuestWorker17::class.java, + GuestWorker18::class.java, GuestWorker19::class.java, GuestWorker20::class.java, + GuestWorker21::class.java, GuestWorker22::class.java, GuestWorker23::class.java, + GuestWorker24::class.java, GuestWorker25::class.java, GuestWorker26::class.java, + GuestWorker27::class.java, GuestWorker28::class.java, GuestWorker29::class.java, + GuestWorker30::class.java, GuestWorker31::class.java, GuestWorker32::class.java, + GuestWorker33::class.java, GuestWorker34::class.java, GuestWorker35::class.java, + GuestWorker36::class.java, GuestWorker37::class.java, GuestWorker38::class.java, + GuestWorker39::class.java, GuestWorker40::class.java, GuestWorker41::class.java, + GuestWorker42::class.java, GuestWorker43::class.java, GuestWorker44::class.java, + GuestWorker45::class.java, GuestWorker46::class.java, GuestWorker47::class.java, + GuestWorker48::class.java, GuestWorker49::class.java, GuestWorker50::class.java, + GuestWorker51::class.java, GuestWorker52::class.java, GuestWorker53::class.java, + GuestWorker54::class.java, GuestWorker55::class.java, GuestWorker56::class.java, + GuestWorker57::class.java, GuestWorker58::class.java, GuestWorker59::class.java, + GuestWorker60::class.java, GuestWorker61::class.java, GuestWorker62::class.java, + GuestWorker63::class.java, GuestWorker64::class.java, GuestWorker65::class.java, + GuestWorker66::class.java, GuestWorker67::class.java, GuestWorker68::class.java, + GuestWorker69::class.java, GuestWorker70::class.java, GuestWorker71::class.java, + GuestWorker72::class.java, GuestWorker73::class.java, GuestWorker74::class.java, + GuestWorker75::class.java, GuestWorker76::class.java, GuestWorker77::class.java, + GuestWorker78::class.java, GuestWorker79::class.java, GuestWorker80::class.java, + GuestWorker81::class.java, GuestWorker82::class.java, GuestWorker83::class.java, + GuestWorker84::class.java, GuestWorker85::class.java, GuestWorker86::class.java, + GuestWorker87::class.java, GuestWorker88::class.java, GuestWorker89::class.java, + GuestWorker90::class.java, GuestWorker91::class.java, GuestWorker92::class.java, + GuestWorker93::class.java, GuestWorker94::class.java, GuestWorker95::class.java, + GuestWorker96::class.java, GuestWorker97::class.java, GuestWorker98::class.java, + GuestWorker99::class.java, GuestWorker100::class.java, GuestWorker101::class.java, + GuestWorker102::class.java, GuestWorker103::class.java, GuestWorker104::class.java, + GuestWorker105::class.java, GuestWorker106::class.java, GuestWorker107::class.java, + GuestWorker108::class.java, GuestWorker109::class.java, GuestWorker110::class.java, + GuestWorker111::class.java, GuestWorker112::class.java, GuestWorker113::class.java, + GuestWorker114::class.java, GuestWorker115::class.java, GuestWorker116::class.java, + GuestWorker117::class.java, GuestWorker118::class.java, GuestWorker119::class.java, + GuestWorker120::class.java, GuestWorker121::class.java, GuestWorker122::class.java, + GuestWorker123::class.java, GuestWorker124::class.java, GuestWorker125::class.java, + GuestWorker126::class.java, GuestWorker127::class.java, + ) + + private class Slot(val index: Int) { + lateinit var connection: ServiceConnection + val connected = CountDownLatch(1) + @Volatile var service: IBinder? = null + @Volatile var pid = -1 + @Volatile var guest = false + /** The session it runs a program for ([serve]'s number). */ + @Volatile var session = 0 + @Volatile var onExit: ((Int) -> Unit)? = null + /** The priority it runs its program at: the asker's (a guest, or the app thread that started it). */ + @Volatile var nice = 0 + /** Set once its program was handed over: only then does its end count as the program's. */ + @Volatile var started = false + /** Between the pid and the last word of a launch (under the slots lock): its end is held back. */ + var launching = false + /** It ended while launching: reported once the launch turns out to have run, never otherwise. */ + var endedLaunching = false + } + + private val slots = arrayOfNulls(classes.size) + // Workers bound ahead of need while a session runs: a zygote fork and the bind take about + // 60-100 ms, which every program the session starts would otherwise wait for. + private val warm = ArrayDeque() + @Volatile private var warmTarget = 0 + // Numbers the sessions: an old session's teardown can still be running when the next one starts. + @Volatile private var session = 0 + // The latest session whose teardown has begun + @Volatile private var stopped = 0 + // Held for a launch's last word and for marking a session stopped + private val authorizing = Any() + private val warming = java.util.concurrent.atomic.AtomicBoolean(false) + private const val WARM_WORKERS = 2 + // A game's start hands off a burst of programs (Wine's services, the agent's checks) within a few + // seconds: bound ahead while the client starts it, not forked while the game draws its first frames. + private const val LAUNCH_WORKERS = 16 + private const val LAUNCH_MS = 20_000L + @Volatile private var launchUntil = 0L + private val launches = java.util.concurrent.atomic.AtomicInteger() + private const val ACK_TIMEOUT_MS = 5000 + private const val ANSWER_TIMEOUT_MS = 5000 + private const val RECEIVE_TIMEOUT_MS = 10000 + // argv and the environment of one exec, with room: Linux caps them at a quarter of the stack + private const val MAX_REQUEST_BYTES = 8 shl 20 + private const val MAX_RECEIVING = 32 + private val receiving = java.util.concurrent.atomic.AtomicInteger() + private val connections = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "guest-worker-binder").apply { isDaemon = true } } + @Volatile private var server: Thread? = null + // Android sets a worker's main thread to THREAD_PRIORITY_TOP_APP_BOOST again each time the app returns to the top + private const val TOP_APP_BOOST = -10 + private const val PRIORITY_CHECK_MS = 2000L + @Volatile private var keeper: Thread? = null + + /** The app, once [attach] or [serve] ran in its main process; null before. */ + @Volatile var context: Context? = null + private set + + /** Whether the session runs its programs in workers: the native userland, and not turned off. */ + fun enabled(context: Context): Boolean = handoffAllowed(context) && NativeGuest.enabled(context) + + private fun handoffAllowed(context: Context): Boolean = + android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) + + /** How the running session's root was started: in a worker (true) or counted (false); null with none running. */ + @Volatile var sessionRootUncounted: Boolean? = null + + /** + * Whether Android's child-process limit is out of the session's way: as the running session + * started (a proot session, or one whose root fell back to a counted start, is not), else as + * the next one would start. + */ + fun limitHandled(context: Context): Boolean = + sessionRootUncounted ?: (NativeGuest.sessionMode != false && handoffAllowed(context) && NativeGuest.nextSession(context)) + + /** Whether pid is a program running in one of the workers. */ + fun runsInWorker(pid: Int): Boolean = pid > 0 && synchronized(slots) { slots.any { it != null && it.started && it.pid == pid } } + + fun socketName(context: Context): String = "droiddeck-spawn." + context.packageName + "." + Process.myUid() + + /** + * Runs [argv] (a host command line) as the main process of a free worker with [env] and the + * fds in [stdio] as its 0, 1 and 2. Returns its pid, or -1. Blocks: not for the main thread. + * [onExit] runs once the process is gone. + */ + fun start(context: Context, argv: List, env: List, stdio: List, onExit: (Int) -> Unit): Int = + start(context, argv, env, stdio, IntArray(stdio.size) { it }, onExit) + + /** As [start], with the fds in [fds] placed at the numbers in [targets]. */ + fun start(context: Context, argv: List, env: List, fds: List, targets: IntArray, + onExit: (Int) -> Unit): Int = start(context, argv, env, fds, targets, false, onExit) + + /** + * [guest]: one of the session's guest programs, which [guestPids] lists and [stopGuests] ends. + * [commit] runs with the pid before the worker may run the program; false, and it does not. + * [confirmed] runs once the worker has taken it on, just before it is told to run it; false, and it does not. + * [owner]: the session asking (the one a guest's request names), else the latest. + */ + private fun start(context: Context, argv: List, env: List, fds: List, targets: IntArray, + guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true }, + confirmed: () -> Boolean = { true }, owner: Int = session, + nice: Int = Process.getThreadPriority(Process.myTid()), + testWorker: FrameAcquireWorkerProbe.Qualified? = null): Int { + val app = context.applicationContext + if (guest && owner <= stopped) { + Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") + + ": not starting ${argv.firstOrNull()}") + return -1 + } + val slot = takeWarm() ?: bind(app)?.takeIf { fresh -> + fresh.connected.await(10, TimeUnit.SECONDS).also { if (!it) release(app, fresh) } + } ?: run { + Log.w(TAG, "no worker started for ${argv.firstOrNull()}") + return -1 + } + slot.guest = guest + slot.session = owner + slot.onExit = onExit + slot.nice = nice + // during a game's start the pool drains instead: its refill would fork while the game starts + if (android.os.SystemClock.elapsedRealtime() >= launchUntil) refill(app) + // The worker execs once a byte comes through this socket: after the reply has reached us, so + // that its exec does not cut the reply off, and after the slot is marked started. Closed + // without one, the worker ends without running the program (the caller starts it another way). + // It answers with a byte of its own: without that it gave up waiting, and nothing runs. + var go: Array? = null + var data: Parcel? = Parcel.obtain() + val reply = Parcel.obtain() + try { + go = ParcelFileDescriptor.createSocketPair() + data!!.writeStringArray(argv.toTypedArray()) + data.writeStringArray(env.toTypedArray()) + data.writeInt(fds.size) + fds.forEach { data.writeFileDescriptor(it.fileDescriptor) } + data.writeIntArray(targets) + data.writeInt(if (guest) 0 else 1) + data.writeFileDescriptor(go[0].fileDescriptor) + data.writeInt(nice) + val service = checkNotNull(slot.service) + if (testWorker != null) data.writeInt(FrameAcquireWorkerProbe.RECEIPT_TAG) + check(service.transact(GuestWorker.RUN, data, reply, 0)) + // The worker has its own copy: with ours closed (and the request's, which holds one too), + // a worker that gave up leaves no reader + data.recycle() + data = null + go[0].close() + val pid = reply.readInt() + val startTicks = if (testWorker != null) { + val size = reply.dataAvail() + if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES) + FrameAcquireWorkerProbe.validReceipt(pid, reply.readInt(), reply.readLong(), size) + else 0L + } else 0L + // Once a session's teardown has begun (stopGuests), none of its programs may start: it + // would not find them. + val stopping = { guest && owner <= stopped } + if (stopping() || !commit(pid)) { + Log.w(TAG, "worker ${slot.index}: ${argv.firstOrNull()} was not taken on") + release(app, slot) + return -1 + } + // launching, not started yet: an end before the last word is reported only if the launch ran + val live = synchronized(slots) { + (slots[slot.index] === slot && !stopping()).also { if (it) { slot.pid = pid; slot.launching = true } } + } + if (!live) { + Log.w(TAG, "worker ${slot.index} ended, or its session is stopping, before running ${argv.firstOrNull()}") + release(app, slot) + return -1 + } + Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) + val answer = StructPollfd().apply { fd = go[1].fileDescriptor; events = OsConstants.POLLIN.toShort() } + // then the word to run it: given only here, once its answer is in, so that a worker whose + // answer came too late never runs a program this call reports as not started. [confirmed] + // goes first: a caller that hears nothing runs the program itself, so it must have heard + // before the worker may run it (an app dying in between loses the program, not doubles it). + // The word and a teardown's start exclude each other: a launch is authorized before stopGuests() + // marks the session stopped, and is then stopped with the pids it takes (guestPids lists a + // launching slot), or never. + val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1 + val accepted = answered && synchronized(authorizing) { + if (stopping() || !confirmed()) false + else { + if (testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, pid, + if (slot.service === service) startTicks else 0L) + Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1 + } + } + val endedRunning = synchronized(slots) { + slot.launching = false + if (accepted && !slot.endedLaunching) slot.started = true + accepted && slot.endedLaunching + } + if (!accepted) { + Log.w(TAG, "worker ${slot.index} did not take ${argv.firstOrNull()} on") + release(app, slot) + return -1 + } + // it ran and was already gone by now: its end, once + if (endedRunning) reportEnd(app, slot) + } catch (e: Exception) { + Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e) + synchronized(slots) { slot.launching = false } + release(app, slot) + return -1 + } finally { + data?.recycle() + reply.recycle() + go?.forEach { runCatching { it.close() } } + } + Log.i(TAG, "worker ${slot.index} (pid ${slot.pid}) runs ${argv.lastOrNull { !it.startsWith("-") }}") + return slot.pid + } + + /** Binds a free worker; its [Slot.connected] opens once it is up. Null when all are in use. */ + private fun bind(app: Context): Slot? { + val slot = synchronized(slots) { + val index = slots.indexOfFirst { it == null } + if (index < 0) { + Log.w(TAG, "all ${slots.size} workers are busy") + return null + } + Slot(index).also { slots[index] = it } + } + slot.connection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, binder: IBinder) { + slot.service = binder + slot.connected.countDown() + } + + override fun onServiceDisconnected(name: ComponentName) = release(app, slot) + + override fun onBindingDied(name: ComponentName) = release(app, slot) + } + // Callbacks off the main thread: start() waits for onServiceConnected, and a caller holding a + // lock the main thread is waiting for (PulseAudio's launch) would otherwise wait out the timeout. + val bound = runCatching { + app.bindService(Intent(app, classes[slot.index]), Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT, + connections, slot.connection) + }.onFailure { Log.w(TAG, "worker ${slot.index} could not be bound", it) }.getOrDefault(false) + if (!bound) { + release(app, slot) + return null + } + return slot + } + + private fun takeWarm(): Slot? = synchronized(slots) { + while (warm.isNotEmpty()) { + val slot = warm.removeFirst() + if (slots[slot.index] === slot && slot.service?.isBinderAlive == true) return slot + } + null + } + + /** Brings the warm workers back up to [warmTarget], one at a time, off the caller's thread. */ + private fun refill(app: Context) { + if (warmTarget == 0 || !warming.compareAndSet(false, true)) return + Thread({ + try { + while (true) { + val missing = warmTarget - synchronized(slots) { warm.size } + if (missing <= 0) break + // all at once: the zygote forks them in parallel + val fresh = (1..missing).mapNotNull { bind(app) } + if (fresh.isEmpty()) break + for (slot in fresh) { + if (!slot.connected.await(10, TimeUnit.SECONDS)) { + release(app, slot) + continue + } + // decided once, under the lock: kept warm, or released + val kept = synchronized(slots) { + (slots[slot.index] === slot && warmTarget > 0).also { if (it) warm.addLast(slot) } + } + if (!kept) release(app, slot) + } + } + } finally { + warming.set(false) + } + }, "guest-worker-warm").apply { isDaemon = true; start() } + } + + /** A game is about to start: [LAUNCH_WORKERS] bound ahead, back to [WARM_WORKERS] once it is up. */ + fun expectLaunch(context: Context) { + val app = context.applicationContext + val raised = synchronized(slots) { (warmTarget > 0).also { if (it) warmTarget = LAUNCH_WORKERS } } + if (!raised) return + launchUntil = android.os.SystemClock.elapsedRealtime() + LAUNCH_MS + val launch = launches.incrementAndGet() + refill(app) + Thread({ + try { + Thread.sleep(LAUNCH_MS) + } catch (_: InterruptedException) { + return@Thread + } + if (launches.get() != launch) return@Thread + val extra = synchronized(slots) { + if (warmTarget != LAUNCH_WORKERS) emptyList() + else { + warmTarget = WARM_WORKERS + List((warm.size - WARM_WORKERS).coerceAtLeast(0)) { warm.removeLast() } + } + } + extra.forEach { release(app, it) } + refill(app) + }, "guest-worker-launch").apply { isDaemon = true; start() } + } + + private fun release(app: Context, slot: Slot) { + var report = false + val removed = synchronized(slots) { + warm.remove(slot) + if (slot.launching) slot.endedLaunching = true else report = slot.started + (slots[slot.index] === slot).also { if (it) slots[slot.index] = null } + } + if (!removed) return + runCatching { app.unbindService(slot.connection) } + if (report) reportEnd(app, slot) + } + + private fun reportEnd(app: Context, slot: Slot) { + val onExit = slot.onExit ?: return + Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start() + } + + /** The worker's exit as a wait status (exit code << 8, or the signal), -1 when unknown. */ + private fun exitStatus(app: Context, pid: Int): Int { + if (pid <= 0 || android.os.Build.VERSION.SDK_INT < 30) return -1 + val am = app.getSystemService(ActivityManager::class.java) + var recorded = false + repeat(20) { + am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let { + recorded = true + // an exit code only when the process exited itself; a signal number otherwise (a native crash) + if (it.reason == android.app.ApplicationExitInfo.REASON_EXIT_SELF) return (it.status and 0xff) shl 8 + if (it.status in 1..64) return it.status and 0x7f + // Android records the death first and the zygote's status later (as UNKNOWN, 0, then + // EXIT_SELF): a reason without a status may still be completed + if (it.reason != android.app.ApplicationExitInfo.REASON_UNKNOWN) return OsConstants.SIGKILL + } + Thread.sleep(50) + } + // killed by Android with no signal recorded, not a clean exit + return if (recorded) OsConstants.SIGKILL else -1 + } + + /** The pids of session [of]'s guest programs running in workers. */ + fun guestPids(of: Int = session): List = + synchronized(slots) { slots.mapNotNull { s -> s?.takeIf { it.guest && it.session == of }?.pid?.takeIf { it > 0 } } } + + /** Ends session [of]'s guest programs that are still running, and, for the latest session, the warm workers. */ + fun stopGuests(of: Int = session) { + // the check and the reset together: a new session's serve() may be under way + val drained = synchronized(authorizing) { + synchronized(slots) { + stopped = maxOf(stopped, of) + if (of != session) emptyList() else { warmTarget = 0; warm.toList().also { warm.clear() } } + } + } + context?.let { app -> drained.forEach { release(app, it) } } + FrameAcquireWorkerProbe.revoke(of) + val pids = guestPids(of) + if (pids.isEmpty()) return + pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) } + Thread.sleep(500) + pids.forEach { Process.killProcess(it) } + } + + /** Listens for `droiddeck-spawn` requests from the session's guests. */ + fun attach(context: Context) { + this.context = context.applicationContext + } + + /** Puts a running program's main thread back to its asker's priority after Android boosted it (once started, never stops). */ + private fun keepPriorities() { + synchronized(this) { + if (keeper != null) return + keeper = Thread({ + while (true) { + try { + Thread.sleep(PRIORITY_CHECK_MS) + } catch (_: InterruptedException) { + return@Thread + } + val running = synchronized(slots) { + slots.filterNotNull().filter { it.started && it.pid > 0 && it.nice != TOP_APP_BOOST } + } + for (s in running) runCatching { + if (Process.getThreadPriority(s.pid) == TOP_APP_BOOST) Process.setThreadPriority(s.pid, s.nice) + } + } + }, "guest-worker-priority").apply { isDaemon = true; start() } + } + } + + /** Starts a session's use of the workers (and the spawn socket, once); returns its number. */ + fun serve(context: Context): Int { + val app = context.applicationContext + this.context = app + val number = synchronized(slots) { warmTarget = WARM_WORKERS; ++session } + refill(app) + keepPriorities() + synchronized(this) { + if (server != null) return number + server = Thread({ + val socket = try { + LocalServerSocket(socketName(app)) + } catch (e: Exception) { + Log.e(TAG, "no spawn socket", e) + synchronized(this) { server = null } + return@Thread + } + while (true) { + val client = runCatching { socket.accept() }.getOrNull() + if (client == null) { + Thread.sleep(100) // out of fds, for one: do not spin + continue + } + // A bounded number of requests still coming in: a stalled sender holds a thread + if (receiving.incrementAndGet() > MAX_RECEIVING) { + receiving.decrementAndGet() + Log.w(TAG, "$MAX_RECEIVING spawn requests are still coming in: refusing another") + runCatching { client.close() } + continue + } + Thread({ + try { + handle(app, client) { receiving.decrementAndGet() } + } catch (e: Throwable) { + Log.w(TAG, "spawn request failed", e) + } + }, "guest-spawn").start() + } + }, "guest-spawn-server").apply { isDaemon = true; start() } + } + return number + } + + private fun handle(app: Context, client: LocalSocket, received: () -> Unit) { + var receiving = true + val done = { if (receiving) { receiving = false; received() } } + try { + handleRequest(app, client, done) + } finally { + done() + } + } + + private fun handleRequest(app: Context, client: LocalSocket, received: () -> Unit) { + client.use { + if (client.peerCredentials.uid != Process.myUid()) return + // The whole request and its fds within this, however slowly they come (the wait for a + // program's exit is not): each read gets what is left of it + val deadline = android.os.SystemClock.elapsedRealtime() + RECEIVE_TIMEOUT_MS + fun left() { + val ms = deadline - android.os.SystemClock.elapsedRealtime() + if (ms <= 0) throw java.net.SocketTimeoutException("spawn request not received in time") + client.soTimeout = ms.toInt() + } + val input = DataInputStream(client.inputStream) + val fds = ArrayList() + fun take() { + val received = client.ancillaryFileDescriptors.orEmpty() + try { + received.forEach { fds.add(ParcelFileDescriptor.dup(it)) } + } finally { + received.forEach { runCatching { Os.close(it) } } + } + } + // fds can come with any read, the request's own bytes too: each read's are taken at once + fun fill(bytes: ByteArray) { + var got = 0 + while (got < bytes.size) { + left() + val n = input.read(bytes, got, bytes.size - got) + take() + if (n < 0) throw java.io.EOFException("spawn request ended at $got of ${bytes.size} bytes") + got += n + } + } + // Until start() has them: closed on every way out before that, from the first byte on + var handedOver = false + try { + val length = ByteArray(4).also { fill(it) }.let { java.nio.ByteBuffer.wrap(it).int } + if (length !in 1..MAX_REQUEST_BYTES) { + Log.w(TAG, "spawn request of $length bytes refused") + return + } + val payload = ByteArray(length).also { fill(it) } + val request = JSONObject(String(payload)) + if (request.has("fdchunks")) { + // The hook sends its fds after the request, a chunk with each byte (hook/handoff.c) + val total = (request.optJSONArray("fds")?.length() ?: 0) + (if (request.has("table")) 1 else 0) + while (fds.size < total) { + left() + if (input.read() < 0) throw java.io.EOFException("fds ended at ${fds.size} of $total") + take() + } + } else { + take() + } + received() + val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } } + val env = LinkedHashMap() + request.optJSONObject("env")?.let { o -> o.keys().forEach { env[it] = o.getString(it) } } + request.optJSONArray("envlist")?.let { a -> + for (i in 0 until a.length()) a.getString(i).split('=', limit = 2).let { if (it.size == 2) env[it[0]] = it[1] } + } + // What the hook told the program that asked (it may run in a worker itself) is not this one's + env.keys.removeAll { it.startsWith("DDH_") } + val cwd = request.optString("cwd", "/") + val wait = request.optBoolean("wait", false) + // A path without a slash names a file in the cwd, as execve() takes it, not one on PATH + val file = request.optString("file", "").let { if (it.isNotEmpty() && '/' !in it) "./$it" else it } + // The handoff table (the hook's) comes last among the fds; the rest go to these numbers. + val tableIndex = request.optInt("table", -1) + val numbers = request.optJSONArray("fds")?.let { a -> IntArray(a.length()) { a.getInt(it) } } ?: IntArray(3) { it } + val table = fds.getOrNull(tableIndex)?.takeIf { pfd -> + runCatching { Os.readlink("/proc/self/fd/${pfd.fd}") }.getOrNull()?.contains("ddnatv-handoff") == true + } + val slot = request.optInt("slot", -1) + val parent = request.optInt("parent", -1) + var programFds = fds.filterIndexed { i, _ -> i != tableIndex } + var targets = numbers + if (table != null && slot >= 0) { + // The program reports its own exit status into the table (hook/handoff.c) + val tableFd = (numbers.maxOrNull() ?: 2) + 1 + programFds = programFds + table + targets = numbers + tableFd + env["DDH_TABLE"] = "$tableFd:$slot:$parent:${request.optInt("child", -1)}" + } + val root = env["DDNATV_ROOT"]?.let(::File) + val out = client.outputStream + if (root == null || argv.isEmpty()) { + out.write("error no guest root or program\n".toByteArray()) + return + } + val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile } + val args = if (file.isNotEmpty()) { + listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; a=\$2; f=\$3; shift 3; exec -a \"\$a\" \"\$f\" \"\$@\"", + "droiddeck-spawn", cwd, argv[0], file) + argv.drop(1) + } else { + listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\"", "droiddeck-spawn", cwd) + argv + } + val command = NativeGuest.command(root, shell, args) + env["DDNATV_REAL_EXE"] = File(root, shell.removePrefix("/")).path + // The hook restores these in the program (tools/nativeguest/hook/handoff.c). + if (request.has("sigign")) env["DDH_SIGIGN"] = request.getLong("sigign").toString() + if (request.has("nofile")) { + env["DDH_NOFILE"] = request.getLong("nofile").toString() + + (if (request.has("nofilemax")) ":" + request.getLong("nofilemax") else "") + } + if (request.has("umask")) env["DDH_UMASK"] = request.getLong("umask").toString() + if (request.has("pgid")) env["DDH_PGID"] = request.getLong("pgid").toString() + if (request.has("anchor")) env["DDH_ANCHOR"] = request.getLong("anchor").toString() + if (request.has("pstart")) env["DDH_PSTART"] = request.getLong("pstart").toString() + if (request.has("astart")) env["DDH_ASTART"] = request.getLong("astart").toString() + env["DDH_SIGMASK"] = request.optLong("sigmask", 0L).toString() + // The shell above: the hook restores nothing there (bash changes its own signal mask), + // only in the program it execs, which no longer has this. + env["DDH_WRAPPER"] = "1" + val child = request.optInt("child", -1) + val exited = CountDownLatch(1) + var status = -1 + var worker = -1 + // The hook answers the pid with "go" (ack): without it (it died, or gave up and runs the + // program itself) the worker must not run it too. + val ack = request.optBoolean("ack", false) + var answered = false + // the hook's last word, sent once the worker has taken the program on and before it runs it + var confirmedToHook = false + // The session whose guest asks, not the latest: a new session can start (serve()) while an + // older one's guests are still sending, and that older one's teardown must find its programs. + // A request that names none is refused (start() runs nothing for session 0): the hook and + // droiddeck-spawn always name it, and which session's it is cannot be told otherwise. + val owner = request.optInt("session", 0).coerceAtLeast(0) + // The sender is the forked child (or droiddeck-spawn): its priority is the one the program would inherit + val nice = runCatching { Process.getThreadPriority(client.peerCredentials.pid) }.getOrDefault(Process.THREAD_PRIORITY_DEFAULT) + val testWorker = FrameAcquireWorkerProbe.match(owner, root, file, argv, ack) + val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, onExit = { code -> + if (testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker) + status = code + if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker) + exited.countDown() + }, confirmed = { + val confirmed = !ack || runCatching { + out.write("ok\n".toByteArray()) + out.flush() + confirmedToHook = true + }.isSuccess + confirmed + }, commit = { started -> + worker = started + if (!ack) return@start true + runCatching { + out.write("pid $started\n".toByteArray()) + out.flush() + answered = true + client.soTimeout = ACK_TIMEOUT_MS + // the whole line: a hook whose write stopped short treats it as failed and runs the program itself + val line = StringBuilder() + var ended = false + while (!ended) { + val c = input.read() + if (c < 0) break + if (c == '\n'.code) ended = true else line.append(c.toChar()) + } + ended && line.toString() == "go" + }.getOrDefault(false) + }, testWorker = testWorker) + if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker) + handedOver = true + programFds.filter { it !== table }.forEach { runCatching { it.close() } } + if (pid <= 0) table?.let { runCatching { it.close() } } + if (!answered) { + out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray()) + out.flush() + } else if (!confirmedToHook) { + // nothing runs it in a worker: the hook runs it itself + runCatching { out.write("error not started\n".toByteArray()); out.flush() } + } + if (pid > 0 && wait) { + exited.await() + // droiddeck-spawn exits with this: an exit code, or 128 plus the signal + val code = if (status < 0) 1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f) + out.write("exit $code\n".toByteArray()) + out.flush() + } + } finally { + if (!handedOver) fds.forEach { runCatching { it.close() } } + } + } + } + + // Layout of the hook's table (tools/nativeguest/hook/handoff.c): a 64-byte header, then 64-byte + // entries of int32 child, real, parent, state, ..., and at 32 the app's report: int32 status, child. + // The report is one 8-byte write tagged with the child it is for; only the hook changes an + // entry's state, so a report that lands after the entry went to another child is ignored there. + private fun reportExit(table: ParcelFileDescriptor, slot: Int, status: Int, parent: Int, child: Int, worker: Int) { + runCatching { + val entry = 64L + slot * 64L + val head = java.nio.ByteBuffer.allocate(16).order(java.nio.ByteOrder.nativeOrder()) + Os.pread(table.fileDescriptor, head, entry) + val real = head.getInt(4) + val state = head.getInt(12) + // Also while the hook holds the entry (TAKEN) or has already guessed its end (EXITED): + // the report is for this child only, and wins over the timeout's guess (ddh_status) + if (head.getInt(0) != child || head.getInt(8) != parent || (real != 0 && real != worker) || state !in 1..4) + return@runCatching + // An exit Android has no record of is reported as a failure, not as a signal. + val report = java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.nativeOrder()) + .putInt(0, if (status < 0) 1 shl 8 else status).putInt(4, child) + Os.pwrite(table.fileDescriptor, report, entry + 32) + if (parent > 0) Process.sendSignal(parent, OsConstants.SIGCHLD) + }.onFailure { Log.w(TAG, "could not report an exit to the guest's parent", it) } + runCatching { table.close() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt b/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt index 3f4589ae13..8008cf82ed 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt @@ -35,9 +35,40 @@ object LegacyNames { @Synchronized fun migrateEtc(root: File) { for ((old, new) in LINKED_DIRS) moveAndLink(File(root, old), File(root, new)) - File(root, "etc/droiddeck/empty").mkdirs() + clearEmptyStandIn(root) + File(root, NO_THERMAL).mkdirs() } + /** + * It stands in for /sys/bus/pci/devices, and libpci exits the whole process on an entry it cannot + * parse; older builds let thermal bind mount points leak into it. The guest can write here, so a + * link is never followed: one in place of the folder is removed, and one above it stops the cleanup. + */ + private fun clearEmptyStandIn(root: File) { + val linkedAbove = listOf("etc", "etc/droiddeck").firstOrNull { Files.isSymbolicLink(File(root, it).toPath()) } + if (linkedAbove != null) { + Log.w(TAG, "not clearing the empty stand-in: $linkedAbove is a link") + return + } + val empty = File(root, "etc/droiddeck/empty") + if (Files.isSymbolicLink(empty.toPath())) runCatching { Files.delete(empty.toPath()) } + .onFailure { Log.w(TAG, "could not remove the link at $empty", it); return } + empty.mkdirs() + empty.listFiles()?.forEach { entry -> + runCatching { deleteWithoutFollowing(entry.toPath()) }.onFailure { Log.w(TAG, "could not clear $entry", it) } + } + } + + private fun deleteWithoutFollowing(path: java.nio.file.Path) { + if (Files.isDirectory(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) { + Files.newDirectoryStream(path).use { entries -> entries.forEach(::deleteWithoutFollowing) } + } + Files.deleteIfExists(path) + } + + /** Stands in for a /sys/class/thermal the kernel won't list; proot adds the bound zones' mount points to it. */ + const val NO_THERMAL = "etc/droiddeck/no-thermal" + @Synchronized fun migrateRootfs(root: File) { migrateEtc(root) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java index 142d4e90bc..327e7fc1ea 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java @@ -248,7 +248,7 @@ public final class LinuxRuntime { // A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort // at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its // wrapper gave up: it lists the directory for CPU temperatures. Empty there instead. - if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal"); + if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, LegacyNames.NO_THERMAL).getPath() + ":/sys/class/thermal"); bind(cmd, context.getFilesDir().getPath()); bind(cmd, context.getCacheDir().getPath()); bind(cmd, liveDir(context).getPath()); diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt index babaae550a..95a660eaf4 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt @@ -24,6 +24,16 @@ object NativeGuest { fun enabled(context: Context): Boolean = SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context)) + /** + * Whether the next session will start natively. The session stages the hook from the APK before + * it starts, so only the setting and the rootfs's loader decide, and a runtime still to be + * installed will have one. + */ + fun nextSession(context: Context): Boolean = + SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context)) + + internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null + /** The mode the running session started in; null between sessions. */ @Volatile var sessionMode: Boolean? = null diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt index a8b76934ee..ffccd3e237 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt @@ -219,6 +219,19 @@ object BottomDesktop { fun sendText(text: String) { val target = service ?: return + if (text.isNotEmpty() && text.all { it == '\r' || it == '\n' || it == '\b' || it == '\u007f' || it == '\t' }) { + for (c in text) { + val evdev = when (c) { + '\r', '\n' -> 28 + '\b' -> 14 + '\u007f' -> 111 + else -> 15 + } + sendKey(evdev, true) + sendKey(evdev, false) + } + return + } send(target, Message.obtain(null, Comp.MSG_TEXT).apply { data = Bundle().apply { putString(Comp.KEY_TEXT, text) } }) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt index 146509bba7..b9be461b01 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt @@ -30,6 +30,8 @@ object ComponentsManager { private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components" internal const val DD_NIGHTLY = "linux-nightly" internal const val DD_BIONIC = "bionic-stable" + /** FEX for original Xbox games on DroidDeck-Bionic: kept apart from [DD_BIONIC] so automatic FEX updates never pick it. */ + internal const val DD_XBOX = "bionic-xbox" private val RELEASES = linkedMapOf( "FexCore-Linux" to "fex", "Dxvk-Linux" to "dxvk", @@ -38,7 +40,8 @@ object ComponentsManager { "Vkd3d-proton-Linux" to "vkd3d", ) private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex") - private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC) + private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC) + + (DD_COMPONENTS to DD_XBOX) private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS) private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d") private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux") @@ -253,6 +256,28 @@ object ComponentsManager { saveState(context, state) } + internal enum class Assigned { SET, NOT_LISTED, CHANGED } + + /** + * Sets a game's component to a listed package, fetching it first when it is not stored. [expected] is the component + * the caller read when it decided: if the game's component is something else once the package is ready (the player + * chose one during the download), nothing is written. [onSet] runs under the same lock as the write. + */ + internal fun assignGameComponent(context: Context, scope: String, comp: String, file: String, release: String, + expected: String?, onSet: () -> Unit = {}): Assigned { + val wcp = File(packagesDir(context), safeName(file)) + if (!wcp.isFile || runCatching { packageInfo(context, wcp) }.isFailure) { + wcp.delete() + download(context, catalogItem(context, file, release) ?: return Assigned.NOT_LISTED) {} + } + synchronized(lock) { + if (gameComponents(context, scope)[comp] != expected) return Assigned.CHANGED + setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) } + onSet() + } + return Assigned.SET + } + fun clearGameComponents(context: Context, scope: String) = synchronized(lock) { require(GameEnvironment.validScope(scope)) val state = loadState(context) @@ -1124,7 +1149,7 @@ object ComponentsManager { internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) { DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value - DD_BIONIC -> "fex" + DD_BIONIC, DD_XBOX -> "fex" else -> null } diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt index fa1cc45d7f..86eef4b578 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt @@ -121,7 +121,7 @@ object GameEnvironmentStore { ) { publishGameCores(context) val stored = config ?: read(context) - val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared) + val resolved = GameEnvironment.withKnownGames(stored).copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared) val json = encode(resolved) val dxvk = TextureFiltering.dxvkOptions( SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context), diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt index 263860334c..3c2d722c06 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt @@ -59,13 +59,18 @@ object GameStorage { return when { pref == SessionPrefs.GAME_STORAGE_OFF -> null pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) } - else -> Option(SessionPrefs.gameStorageLabel(context), pref).takeIf { attached(File(pref)) } + else -> reachable(pref).let { path -> Option(SessionPrefs.gameStorageLabel(context), path).takeIf { attached(File(path)) } } } } fun disconnected(context: Context): Boolean { val pref = SessionPrefs.gameStorage(context) - return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(pref)) + return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(reachable(pref))) + } + + internal fun reachable(path: String, usable: (File) -> Boolean = { it.isDirectory && it.canWrite() }): String { + val alias = UsbLink.storagePath(path) + return if (alias != path && !usable(File(path)) && usable(File(alias))) alias else path } internal fun attached( diff --git a/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt b/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt new file mode 100644 index 0000000000..8dc2079e1c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.session + +import android.util.Log +import java.io.File + +internal object PageCacheTrim { + private const val TAG = "PageCacheTrim" + private const val MIN_FILE_BYTES = 8L shl 20 + private const val POLL_MS = 3000L + private const val RESCAN_MS = 120_000L + + data class Mem(val freeKb: Long, val fileKb: Long) + + fun parse(meminfo: String): Mem? { + fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(meminfo)?.groupValues?.get(1)?.toLongOrNull() + val free = field("MemFree") ?: return null + val file = (field("Active\\(file\\)") ?: return null) + (field("Inactive\\(file\\)") ?: return null) + return Mem(free, file) + } + + fun shouldTrim(mem: Mem, baselineFileKb: Long): Boolean { + val built = mem.fileKb - baselineFileKb + return (mem.freeKb < 2560 * 1024 && built >= 768 * 1024) || + (mem.freeKb < 1024 * 1024 && built >= 128 * 1024) + } + + fun start(roots: () -> List, alive: () -> Boolean) { + Thread({ + var baseline = 0L + var files = emptyList() + var scanned = 0L + var trims = 0 + var failureLogged = false + while (alive()) { + runCatching { + val mem = parse(File("/proc/meminfo").readText()) + if (mem != null && shouldTrim(mem, baseline)) { + val now = System.currentTimeMillis() + if (now - scanned > RESCAN_MS) { + files = roots().flatMap { root -> root.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.filter { it.isFile && it.length() >= MIN_FILE_BYTES }.toList() } + scanned = now + } + val began = System.nanoTime() + files.forEach(::drop) + val after = parse(File("/proc/meminfo").readText()) + baseline = after?.fileKb ?: mem.fileKb + trims++ + Log.i(TAG, "trim #$trims: free ${mem.freeKb / 1024} -> ${after?.freeKb?.div(1024)} MB, file cache ${mem.fileKb / 1024} -> ${after?.fileKb?.div(1024)} MB, ${files.size} files, ${(System.nanoTime() - began) / 1_000_000} ms") + } + }.onFailure { + if (!failureLogged) Log.w(TAG, "trim failed: $it") + failureLogged = true + } + Thread.sleep(POLL_MS) + } + }, "page-cache-trim").apply { isDaemon = true }.start() + } + + private fun drop(file: File) { + PageCacheNative.fadviseDontNeed(file.path) + } +} + +internal object PageCacheNative { + init { + System.loadLibrary("sdnative") + } + + @JvmStatic external fun fadviseDontNeed(path: String): Int +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SecondaryLibrary.kt b/app/src/main/java/com/droiddeck/launcher/session/SecondaryLibrary.kt index 53fc319c26..08fa86f608 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SecondaryLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SecondaryLibrary.kt @@ -46,7 +46,16 @@ object SecondaryLibrary { } fun privateRoot(files: File, library: File): File { - val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray()) + val own = privateDir(files, library.canonicalPath) + if (own.exists()) return own + val raw = UsbLink.rawPath(library.absolutePath) + val alias = if (raw != library.absolutePath) raw else UsbLink.storagePath(library.absolutePath) + if (alias == library.absolutePath) return own + return privateDir(files, runCatching { File(alias).canonicalPath }.getOrDefault(alias)).takeIf { it.exists() } ?: own + } + + private fun privateDir(files: File, path: String): File { + val digest = MessageDigest.getInstance("SHA-256").digest(path.toByteArray()) .joinToString("") { "%02x".format(it.toInt() and 255) } return File(files, "steam-libraries/$digest") } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt index 919891fa45..10a20f9fcc 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt @@ -16,6 +16,7 @@ object SessionDisplay { const val LINK_PORTRAIT = "link/portrait" const val DEFAULT_RESOLUTION = "720p" + const val DEFAULT_STEAM_PORTRAIT_RESOLUTION = "1280x800" private val PRESET_HEIGHTS = listOf(720, 900, 1080) fun presetHeight(choice: String): Int? = diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index ef43a53767..f0dfae6ebd 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -11,6 +11,7 @@ import com.droiddeck.launcher.runtime.DesktopCatalog import com.droiddeck.launcher.runtime.LegacyNames import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.ProotFastPath +import org.json.JSONObject import java.io.File object SessionFiles { @@ -21,6 +22,8 @@ object SessionFiles { private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad" const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio" private const val STAGED_LEDGER = "usr/local/.droiddeck-staged" + private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json" + private const val IME_DEFAULT_MODE = 420 val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread") internal val DESKTOP_FILES = arrayOf( @@ -35,6 +38,7 @@ object SessionFiles { "usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper", "usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js", "etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop", + "usr/share/applications/droiddeck-return-gaming.desktop" to "usr/share/applications/droiddeck-return-gaming.desktop", "etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc", ) @@ -129,7 +133,11 @@ object SessionFiles { "usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent", "usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility", "usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard", + "usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn", + "usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer", "usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard", + "usr/local/bin/droiddeck-text-input" to "usr/local/bin/droiddeck-text-input", + "usr/local/bin/droiddeck-steam-ime" to "usr/local/bin/droiddeck-steam-ime", "usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window", "usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install", "usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply", @@ -153,6 +161,7 @@ object SessionFiles { "usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks", "usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads", "usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root", + "usr/local/bin/droiddeck-user" to "usr/local/bin/droiddeck-user", "usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text", "usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd", "usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators", @@ -336,6 +345,7 @@ object SessionFiles { if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged") } for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger) + stageImeFiles(context, root, ledger) ledger.save() for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively() val preload = StringBuilder("/usr/local/lib/libddsession.so\n") @@ -362,6 +372,7 @@ object SessionFiles { Log.e(TAG, "could not write steam-compatibility-label") } writeCjkFontConfig(root, etc) + writeSessionBusPolicy(etc) writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() }) val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() } val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged") @@ -421,6 +432,42 @@ object SessionFiles { seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) } } + private fun stageImeFiles(context: Context, root: File, ledger: StageLedger) { + val entries = LinkedHashMap() + try { + val text = context.assets.open("linuxfs/$IME_MANIFEST").bufferedReader().use { it.readText() } + val files = JSONObject(text).getJSONObject("files") + for (name in files.keys()) { + entries[name] = files.optJSONObject(name)?.optString("mode").orEmpty().toIntOrNull(8) ?: IME_DEFAULT_MODE + } + entries[IME_MANIFEST] = IME_DEFAULT_MODE + } catch (e: Exception) { + Log.w(TAG, "the Chinese input payload is not bundled; Steam sessions start without it", e) + return + } + for ((relative, mode) in entries) { + val target = File(root, relative) + if (ledger.current(relative, target)) continue + val staged = File(target.parentFile, target.name + ".staged") + var installed = false + try { + target.parentFile?.mkdirs() + context.assets.open("linuxfs/$relative").use { input -> + staged.outputStream().use { output -> FileUtils.copy(input, output) } + } + installed = staged.setReadable(true, false) && + staged.setWritable((mode and 0x80) != 0, true) && + staged.setExecutable((mode and 0x49) != 0, false) && + staged.renameTo(target) + } catch (e: Exception) { + Log.w(TAG, "could not stage $relative", e) + } finally { + if (!installed) staged.delete() + } + if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged") + } + } + internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean { synchronized(STEAM_CONFIG) { if (!config.isFile) return true @@ -884,6 +931,24 @@ object SessionFiles { } } + /** + * A session bus admits only its owner, and with droiddeck-user (the native hook's ordinary + * user) a root process and a user's share the bus while the kernel sees one Android uid. + */ + private fun writeSessionBusPolicy(etc: File) { + val xml = """ + + + + + +""" + val conf = File(etc, "dbus-1/session.d/droiddeck-users.conf") + conf.parentFile?.mkdirs() + if (!FileUtils.writeString(conf, xml)) Log.e(TAG, "could not write the session bus policy") + } + private fun writeCjkFontConfig(root: File, etc: File) { try { val confDir = File(etc, "fonts/conf.d").apply { mkdirs() } 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 a040ef9de8..b2cc52bcee 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -63,6 +63,24 @@ object SessionPrefs { .takeIf { value -> orientationOptions.any { it.first == value } } ?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + fun orientation(context: Context, mode: String?): Int { + val key = when (mode) { + "steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam" + "desktop", SessionService.MODE_DESKTOP -> "orientation.desktop" + else -> null + } ?: return orientation(context) + val stored = prefs(context).getInt(key, Int.MIN_VALUE) + return if (stored == Int.MIN_VALUE) orientation(context) + else stored.takeIf { value -> orientationOptions.any { it.first == value } } ?: orientation(context) + } + + fun setOrientation(context: Context, mode: String, orientation: Int) { + require(mode == "steam" || mode == "desktop") + require(orientationOptions.any { it.first == orientation }) + val key = if (mode == "steam") "orientation.steam" else "orientation.desktop" + prefs(context).edit().putInt(key, orientation).apply() + } + /** The session menu's width in dp the user dragged it to; null keeps the default. */ fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 } @@ -75,11 +93,19 @@ object SessionPrefs { prefs(context).edit().putInt("orientation", orientation).apply() } - fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int = - if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation")) + fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int, mode: String? = null): Int { + val modeKey = when (mode) { + "steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam" + "desktop", SessionService.MODE_DESKTOP -> "orientation.desktop" + else -> null + } + val preferences = prefs(context) + if (modeKey != null && preferences.contains(modeKey)) return orientation(context, mode) + return if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !preferences.contains("orientation")) ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context) + } - fun portrait(context: Context): Boolean = when (orientation(context)) { + fun portrait(context: Context, mode: String? = null): Boolean = when (orientation(context, mode)) { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true ActivityInfo.SCREEN_ORIENTATION_USER -> context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT @@ -92,6 +118,39 @@ object SessionPrefs { prefs(context).edit().putBoolean("launcherFullscreen", on).apply() } + fun launcherFrost(context: Context): Boolean = prefs(context).getBoolean("launcherFrost", false) + + fun setLauncherFrost(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("launcherFrost", on).apply() + } + + fun frostWallpaper(context: Context): Boolean = prefs(context).getBoolean("frostWallpaper", true) + + fun setFrostWallpaper(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("frostWallpaper", on).apply() + } + + fun frostCards(context: Context): Boolean = prefs(context).getBoolean("frostCards", true) + + fun setFrostCards(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("frostCards", on).apply() + } + + fun frostTransparency(context: Context): Int = frostPercent(context, "frostTransparency", com.droiddeck.launcher.ui.FROST_WALLPAPER_DEFAULT) + + fun setFrostTransparency(context: Context, percent: Int) = setFrostPercent(context, "frostTransparency", percent) + + fun frostCardTransparency(context: Context): Int = frostPercent(context, "frostCardTransparency", com.droiddeck.launcher.ui.FROST_DEFAULT) + + fun setFrostCardTransparency(context: Context, percent: Int) = setFrostPercent(context, "frostCardTransparency", percent) + + private fun frostPercent(context: Context, key: String, default: Int): Int = + prefs(context).getInt(key, default).coerceIn(0, com.droiddeck.launcher.ui.FROST_MAX) + + private fun setFrostPercent(context: Context, key: String, percent: Int) { + prefs(context).edit().putInt(key, percent.coerceIn(0, com.droiddeck.launcher.ui.FROST_MAX)).apply() + } + fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true) fun setControllerHaptics(context: Context, on: Boolean) { @@ -305,13 +364,13 @@ object SessionPrefs { prefs(context).edit().putInt("libraryCardLevel", level).apply() } - fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", true) + fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", false) fun setLibraryShowTitle(context: Context, show: Boolean) { prefs(context).edit().putBoolean("libraryShowTitle", show).apply() } - fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", true) + fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", false) fun setLibraryShowSize(context: Context, show: Boolean) { prefs(context).edit().putBoolean("libraryShowSize", show).apply() @@ -493,6 +552,17 @@ object SessionPrefs { prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply() } + fun drawerSections(context: Context): Map = + idList(prefs(context).getString("drawerSections", null)).mapNotNull { entry -> + val at = entry.lastIndexOf('=').takeIf { it > 0 } ?: return@mapNotNull null + entry.substring(0, at) to (entry.substring(at + 1) == "1") + }.toMap() + + fun setDrawerSections(context: Context, sections: Map) { + prefs(context).edit().putString("drawerSections", sections.entries.filter { ',' !in it.key } + .joinToString(",") { "${it.key}=${if (it.value) 1 else 0}" }).apply() + } + fun setNavTabHidden(context: Context, keys: Set) { prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply() } @@ -876,13 +946,21 @@ object SessionPrefs { } - fun picturePosition(context: Context): String = - prefs(context).getString("picturePosition", "center") - ?.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center" + private val picturePositions = setOf("center", "top", "bottom", "left", "right") - fun setPicturePosition(context: Context, position: String) { - prefs(context).edit().putString("picturePosition", - position.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center").apply() + private fun picturePositionKey(portrait: Boolean) = + if (portrait) "picturePosition.portrait" else "picturePosition.landscape" + + fun picturePosition(context: Context, portrait: Boolean): String { + val preferences = prefs(context) + return preferences.getString(picturePositionKey(portrait), null)?.takeIf { it in picturePositions } + ?: preferences.getString("picturePosition", null)?.takeIf { it in picturePositions } + ?: if (portrait) "top" else "center" + } + + fun setPicturePosition(context: Context, portrait: Boolean, position: String) { + require(position in picturePositions) + prefs(context).edit().putString(picturePositionKey(portrait), position).apply() } fun integerScaling(context: Context): Boolean = @@ -1100,10 +1178,20 @@ object SessionPrefs { fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true) + /** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */ + fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true) + fun setNativeUserland(context: Context, on: Boolean) { prefs(context).edit().putBoolean("nativeUserland", on).apply() } + /** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */ + fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false) + + fun setDesktopAsUser(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("desktopAsUser", on).apply() + } + fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true) fun setProotFastPath(context: Context, on: Boolean) { @@ -1433,10 +1521,12 @@ object SessionPrefs { fun resolutionStored(context: Context, mode: String, panel: Pair, portrait: Boolean): String { if (!portrait) return landscapeResolutionStored(context, mode, panel) - val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE + val fallback = if (mode == SessionService.MODE_STEAM) SessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION + else SessionDisplay.LINK_LANDSCAPE + val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return fallback if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) || SessionDisplay.presetHeight(value) != null) return value - return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE + return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: fallback } fun parseOrientedResolution(text: String): Pair? = @@ -1698,6 +1788,9 @@ object SessionPrefs { name.removeSuffix(from) + to to moved } + fun storedAddedGameAppId(context: Context, folderPath: String): Long? = + prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L } + fun addedGameAppId(context: Context, folderPath: String, first: Long): Long = synchronized(addedGameLock) { val p = prefs(context) p.getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L } @@ -1794,10 +1887,17 @@ object SessionPrefs { prefs(context).edit().putBoolean(hdrKey(mode), on).apply() } - fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true) + /** Restart-scoped opt-in; not inferred from Zero-copy (which defaults on). */ + fun producerAcquireFences(context: Context): Boolean = prefs(context).getBoolean("producerAcquireFences", false) + + fun setProducerAcquireFences(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("producerAcquireFences", on).apply() + } + + fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.${prefMode(mode)}", true) fun setZeroCopy(context: Context, mode: String, on: Boolean) { - prefs(context).edit().putBoolean("zeroCopy.$mode", on).apply() + prefs(context).edit().putBoolean("zeroCopy.${prefMode(mode)}", on).apply() } const val FPS_UNPACED = -1 @@ -1807,16 +1907,15 @@ object SessionPrefs { const val PIP_FPS = 30 - fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int { - val limit = when { - mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED - mirrorRefreshLimit <= 0 -> sessionLimit - sessionLimit <= 0 -> mirrorRefreshLimit - else -> minOf(mirrorRefreshLimit, sessionLimit) - } + fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false, hostCap: Int = 0): Int { + val limit = listOf(mirrorRefreshLimit, sessionLimit, hostCap).filter { it > 0 }.minOrNull() ?: FPS_UNPACED return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit } + /** The per-app rate Android holds this window to (Game Mode's FPS override), or 0 when the panel's rate applies. */ + fun hostFrameCap(overrideHz: Float, panelHz: Float): Int = + if (overrideHz > 1f && panelHz - overrideHz > 1f) Math.round(overrideHz) else 0 + val upscalerChoices = listOf( 2 to "Nearest", 0 to "Linear", 4 to "AMD FSR 1", 3 to "Snapdragon GSR", 8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only", @@ -2117,6 +2216,12 @@ object SessionPrefs { (resolutionChosen(context, SessionService.MODE_DESKTOP) || resolutionChosen(context, SessionService.MODE_DESKTOP, true))) SessionService.MODE_DESKTOP else prefMode(mode) + fun showGlassesShortcut(context: Context): Boolean = prefs(context).getBoolean("showGlassesShortcut", true) + + fun setShowGlassesShortcut(context: Context, show: Boolean) { + prefs(context).edit().putBoolean("showGlassesShortcut", show).apply() + } + fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true) fun setPipAutoEnter(context: Context, enabled: Boolean) { 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 c88db261af..5d2946d2d8 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -394,8 +394,10 @@ class SessionService : Service() { SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM) SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty() SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI) - SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL) - val steamUrlGameId = SessionState.steamUrl + val launchSteamUrl = intent?.getStringExtra(EXTRA_STEAM_URL) + val frontendSteamGame = intent?.getBooleanExtra(EXTRA_FRONTEND_STEAM_GAME, false) == true + SessionState.steamUrl = launchSteamUrl + val steamUrlGameId = launchSteamUrl ?.let { url -> when { url.startsWith(GAME_URL_PREFIX) -> @@ -426,6 +428,11 @@ class SessionService : Service() { ++sessionGen } } + val trimGen = gen + PageCacheTrim.start( + roots = { listOfNotNull(File(filesDir, "linuxfs"), GameStorage.effective(applicationContext)?.let { File(it.path) }).filter(File::isDirectory) }, + alive = { SessionState.running && sessionGen == trimGen }, + ) if (SessionState.stopRequested) { stopSession(0) return START_NOT_STICKY @@ -447,7 +454,7 @@ class SessionService : Service() { Thread({ OrphanReaper.reap("session starting") ProtonExtras.awaitReplacement(120_000) - runSession(gen) + runSession(gen, launchSteamUrl, frontendSteamGame) }, "session-start").start() return START_NOT_STICKY } @@ -500,7 +507,7 @@ class SessionService : Service() { } - private fun runSession(gen: Int) { + private fun runSession(gen: Int, launchSteamUrl: String?, frontendSteamGame: Boolean) { SessionPrefs.ensurePowerVrAutoDriversAfterGpuQuery(this) if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) { com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) } @@ -555,9 +562,10 @@ class SessionService : Service() { return } } - val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) } + val nextAgentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) } .onFailure { Log.w(TAG, "agent environment skipped", it) } - .getOrDefault(emptyList()) + val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList()) + val customEnvironment = extraEnv() try { if (systemVulkan) { SystemVulkanDriver.prepare(this) @@ -614,6 +622,9 @@ class SessionService : Service() { val size = SessionState.outputSize val guest = ArrayList() val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP + runCatching { SessionEvents.step("components-xbox") { XboxBackCompatComponents.ensure(this) } } + .onSuccess { if (it != null) Log.i(TAG, it) } + .onFailure { Log.w(TAG, "original Xbox components", it) } runCatching { SessionEvents.step("components-republish") { ComponentsManager.republish(this) } } .onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") } .onFailure { Log.w(TAG, "component selections", it) } @@ -623,7 +634,7 @@ class SessionService : Service() { .onFailure { Log.w(TAG, "forced components", it) } } try { - SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) } + SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment, customEnvironment) } } catch (e: IllegalStateException) { Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e) failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1) @@ -661,7 +672,7 @@ class SessionService : Service() { Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output") } if (SessionState.followScreen || size.first < size.second || - SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) + SessionPrefs.orientation(this, SessionState.mode) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) guest.add("DD_FOLLOW_OUTPUT=1") if (SessionState.hdr) { guest.add("DD_HDR=1") @@ -705,10 +716,38 @@ class SessionService : Service() { if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1") } guest.add("DD_LAUNCH_DIR=" + sessionRoot.path) + // this session's worker number: the shared field may be a newer session's by the time it is used + var ownWorkers = 0 + if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) { + val fenceWorker = com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe + val preparedFence = if (steamHere && !systemVulkan && !VenusComponent.wanted(this) && + SessionPrefs.zeroCopy(this, MODE_STEAM) && SessionPrefs.producerAcquireFences(this) && + nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment(agentEnvironment, customEnvironment) + ) fenceWorker.prepare(this, launchSteamUrl, frontendSteamGame) else null + var fenceArmed = false + // Under the lock a stop takes its number with: a stop either comes first (and this session + // starts no workers) or owns them + ownWorkers = synchronized(stopLock) { + if (gen != sessionGen || !SessionState.running) 0 + else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { + guestWorkerSession = it + if (preparedFence != null) fenceArmed = fenceWorker.arm(it, preparedFence) + } + } + if (ownWorkers > 0) { + guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this)) + guest.add("DD_SPAWN_SESSION=$ownWorkers") + if (fenceArmed) { + guest.add(fenceWorker.GAMESCOPE_ENABLE) + guest.add(fenceWorker.GAME_ENABLE) + } + } + } // Proton builds up to 11.12 report X11 text fields under this name. guest.add("BL_LAUNCH_DIR=" + sessionRoot.path) GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) } if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("DD_STEAM_UI=desktop") + if (SessionPrefs.desktopAsUser(this)) guest.add("DD_DESKTOP_USER=1") // Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not // an Adreno, or Setup's switch), and graphics-report.txt for every session. if (GraphicsReport.detailed(this)) guest.add("DD_GAME_LOGS=1") @@ -723,7 +762,7 @@ class SessionService : Service() { val desktopGuest = ArrayList(guest) guest.add(LinuxRuntime.SESSION_SCRIPT) guest.add(SessionState.mode) - if (SessionState.mode == MODE_STEAM) SessionState.steamUrl?.takeIf { it.startsWith("steam://") }?.let { + if (SessionState.mode == MODE_STEAM) launchSteamUrl?.takeIf { it.startsWith("steam://") }?.let { guest.add(it) Log.i(TAG, "steam: handing the client $it") } @@ -863,10 +902,10 @@ class SessionService : Service() { watchLaunchRequests(sessionRoot) watchSyncWanted(root) EsyncPacks.fetchInBackground(this, root) - val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status -> + val pid = SessionEvents.step("guest-launch") { HostProcess.startUncounted(line, hostEnv.asArray(), root, { status -> if (gen != sessionGen) { Log.i(TAG, "an earlier session's process ended ($status); the current one carries on") - return@start + return@startUncounted } val program = programStatus(sessionRoot) Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "") @@ -882,10 +921,19 @@ class SessionService : Service() { syncWatcher = null } abandonStart(gen, sessionDir, started) - if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start() + val workers = ownWorkers + if (pid > 1) Thread({ teardown(pid, workerSession = workers) }, "session-teardown").start() + else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers) return } sessionPid = pid + // Under the lock Stop clears it with, and only while this session still runs: a Stop since the + // check above has cleared it already, and this would set it again for no running session. + val uncounted = com.droiddeck.launcher.runtime.GuestWorkers.runsInWorker(pid) + synchronized(stopLock) { + if (gen == sessionGen && SessionState.running) + com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = uncounted + } if (pid > 1) { raiseTracer(pid, gen) SessionEvents.guestStarted(pid) @@ -993,7 +1041,8 @@ class SessionService : Service() { return com.droiddeck.launcher.input.GesturePrefs.read(this, game).relativeMouseMode } - private fun addClientEnvironment(guest: MutableList, steamHere: Boolean, agentEnvironment: List) { + private fun addClientEnvironment(guest: MutableList, steamHere: Boolean, + agentEnvironment: List, customEnvironment: List) { guest.add("/usr/bin/env") guest.add("-i") guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this)) @@ -1113,7 +1162,7 @@ class SessionService : Service() { guest.add("DD_ZRAM=1") } guest.add("AUDIO_DIRECT_DECAY=0") - val extra = extraEnv() + agentEnvironment + val extra = customEnvironment + agentEnvironment guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra)) if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=") extra.forEach { guest.add(it) } @@ -1537,10 +1586,15 @@ class SessionService : Service() { return binds } - private fun teardown(prootPid: Int, expectedStartTime: Long? = null) { + // The workers' session number of the session running now (GuestWorkers.serve) + @Volatile private var guestWorkerSession = 0 + + private fun teardown(prootPid: Int, expectedStartTime: Long? = null, workerSession: Int = guestWorkerSession) { fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime if (!stillSameProcess()) return - val tree = descendants(prootPid) + // The session's programs that run in worker processes are not descendants of its root. + val workers = if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workerSession) else emptyList() + val tree = descendants(prootPid) + workers.flatMap { pid -> listOfNotNull(readStat(pid)?.let { Pair(pid, it.second) }) + descendants(pid) } if (!stillSameProcess()) return saveWineRegistries(tree) android.os.Process.sendSignal(prootPid, 15) @@ -1557,6 +1611,7 @@ class SessionService : Service() { killed++ } if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind") + if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workerSession) } private fun clearCachedApps() { @@ -1731,6 +1786,7 @@ class SessionService : Service() { SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen)) watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId) Log.i(TAG, "queued Steam game $gameId for the running client") + com.droiddeck.launcher.runtime.GuestWorkers.expectLaunch(this) } private fun watchGameExit( @@ -2327,12 +2383,16 @@ class SessionService : Service() { return } completeNativeSleep() + var workers = 0 val (ended, endedArch) = synchronized(stopLock) { if (gen != null && gen != sessionGen) return + // as it is when running is cleared: startup registers its workers under this lock too + workers = guestWorkerSession cancelQueuedSteamGame() gameExitWatchToken++ // also when startup stopped before the guest ran com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null + com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = null if (!SessionState.running) return if (relaunch) SessionState.confirmRelaunchStop() SessionEvents.record("guest.exited", mapOf("status" to status)) @@ -2393,7 +2453,8 @@ class SessionService : Service() { if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid) com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession) auxiliary.forEach { (pid, started) -> teardown(pid, started) } - if (prootPid > 1) teardown(prootPid) + if (prootPid > 1) teardown(prootPid, workerSession = workers) + else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers) killGuestLeftovers(ended) pruneSystemVulkanRuntime() finishSessionStop(status, stoppedGen, collectEnded) @@ -2402,6 +2463,7 @@ class SessionService : Service() { } else { Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start() Thread({ + com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers) com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession) finishSessionStop(status, stoppedGen, collectEnded) if (launcherEnded) importLauncherGames() @@ -2720,6 +2782,9 @@ class SessionService : Service() { const val EXTRA_PROGRAM_ARGS = "programArgs" const val EXTRA_STEAM_UI = "steamUi" const val EXTRA_STEAM_URL = "steamUrl" + // Set by the first-party Library play action on the private SessionActivity/Service path. + // Never copied from an exported intent or Agent command. + internal const val EXTRA_FRONTEND_STEAM_GAME = "com.droiddeck.launcher.FRONTEND_STEAM_GAME" const val EXTRA_GAME_ID = "gameId" fun start( @@ -2727,6 +2792,7 @@ class SessionService : Service() { steamUi: String? = null, steamUrl: String? = null, programArgs: Array? = null, gameId: String? = null, displayId: Int = Display.DEFAULT_DISPLAY, + frontendSteamGame: Boolean = false, ) { SteamClientPrefetch.cancel() SessionState.activityDisplayId = displayId @@ -2737,6 +2803,7 @@ class SessionService : Service() { if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs) if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi) if (steamUrl != null) intent.putExtra(EXTRA_STEAM_URL, steamUrl) + if (frontendSteamGame) intent.putExtra(EXTRA_FRONTEND_STEAM_GAME, true) if (gameId != null) intent.putExtra(EXTRA_GAME_ID, gameId) if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index dcac4fef89..e4fb6ed9c3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -12,15 +12,15 @@ object SettingsReset { private const val TAG = "SettingsReset" internal val SESSION_KEYS = setOf( - "orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", + "orientation", "launcherFullscreen", "launcherFrost", "frostWallpaper", "frostCards", "frostTransparency", "frostCardTransparency", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", "drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", - "stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", + "stretch16x9", "avoidNotch", "picturePosition", "picturePosition.portrait", "picturePosition.landscape", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", - "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", + "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "producerAcquireFences", "paceCores", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", "noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite", "mountSharedStorage", "guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt index 578f1c5cb4..4b08d0a3da 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt @@ -10,9 +10,23 @@ import java.io.File // browser view placed outside the Big Picture window, composition capped at "notification" so gamescope keeps the game // focused, and gamepad focus on the main UI. The hold is a lease the app renews, so Steam recovers if the app goes away. object SteamQam { - data class Target(val port: Int, val path: String) + /** [mainPath] is Steam's main menu page, shown beside the quick access menu in the split layout. */ + data class Target(val port: Int, val path: String, val mainPath: String? = null) + const val MAIN_MENU = 1 const val QUICK_ACCESS = 2 + + /** Height in CSS pixels both menus are laid out at in the split layout, so they show at one scale. */ + const val SPLIT_CSS_HEIGHT = 480 + + /** Steam's own width for the main menu; quick access takes the rest of the panel. */ + const val MAIN_CSS_WIDTH = 240 + + /** Holds the parked main menu in place and spreads its item rows (not dividers) over the full height, at most 80 px each. */ + private const val MAIN_PARKED_CSS = + ".BasicUI > .Panel { transform: none !important; width: 100% !important; height: 100% !important; margin: 0 !important; } " + + ".BasicUI > .Panel > :has(> .Focusable) { flex: 1 1 0 !important; height: auto !important; max-height: 80px; } " + + ".BasicUI > .Panel > :has(> .Focusable) > .Panel { height: 100% !important; }" const val LEASE_MS = 5_000 private const val TAG = "SteamQam" private const val EVAL_MS = 6_000L @@ -26,21 +40,54 @@ object SteamQam { * Takes or renews the lease for [owner], or releases it. A live lease held by a newer panel is never taken back by an * older one, so a late request from a panel being torn down cannot end its replacement's lease or change its layout. */ - internal fun leaseScript(on: Boolean, owner: Long, aspect: Float = 0f): String = + internal fun leaseScript(on: Boolean, owner: Long, aspect: Float = 0f, split: Boolean = false): String = if (on) "if (!(g.__ddQamUntil > Date.now()) || !(g.__ddQamOwner > $owner)) { g.__ddQamOwner = $owner; g.__ddQamUntil = Date.now() + $LEASE_MS;" + - (if (aspect > 0f) " g.__ddQamAspect = $aspect;" else "") + " }" + (if (aspect > 0f) " g.__ddQamAspect = $aspect;" else "") + " g.__ddQamSplit = $split; }" else "if (g.__ddQamOwner === $owner) g.__ddQamUntil = 0;" - /** [aspect] is the panel's width over height: the menu is laid out at that shape so every tab shows at one scale. */ - internal fun script(on: Boolean, aspect: Float = 0f, owner: Long = 0): String = """(() => { - const g = globalThis, QAM = 2; + /** + * [aspect] is the panel's width over height: the menu is laid out at that shape so every tab shows at one scale. With + * [split], Steam's main menu is kept rendered at its own width beside the quick access menu, which gets the rest. + */ + internal fun script(on: Boolean, aspect: Float = 0f, owner: Long = 0, split: Boolean = false): String = """(() => { + const g = globalThis, QAM = 2, MAIN = 1; const W = SteamUIStore.WindowStore.SteamUIWindows[0]; const m = W.MenuStore, c = W.m_CompositionStateStore; const nav = W.m_FocusNavContext; const popup = g_PopupManager.GetExistingPopup("SP BPM_uid0"); const held = () => g.__ddQamUntil > Date.now(); - const ours = () => held() && m.m_eOpenSideMenu === QAM && !g.__ddQamTop; + const split = () => held() && g.__ddQamSplit === true; + // Steam's views carry no names: the main menu's is the one Steam focuses while the main menu is open. Until Steam + // has shown it, the main menu is opened once with its view parked like the quick access menu's. + const probing = () => g.__ddMainProbe > Date.now(); + const ours = () => held() && !g.__ddQamTop && (m.m_eOpenSideMenu === QAM || (probing() && m.m_eOpenSideMenu === MAIN)); const width = (h) => g.__ddQamAspect > 0 ? Math.round(h * g.__ddQamAspect) : 0; + const parkX = () => popup.m_popup.innerWidth + 64; + const mainSize = () => [$MAIN_CSS_WIDTH, $SPLIT_CSS_HEIGHT]; + const qamSplitSize = () => [Math.max(Math.round($SPLIT_CSS_HEIGHT * (g.__ddQamAspect > 0 ? g.__ddQamAspect : 1)) - $MAIN_CSS_WIDTH, 320), $SPLIT_CSS_HEIGHT]; + const size = (w, h) => split() ? qamSplitSize() : [width(h) || w, h]; + const mainView = () => views().find(v => v.__ddMain); + // Only the quick access view is parked: the one Steam focuses while quick access is open. Before Steam has + // focused it, any view but the main menu's and the header's web page (Store and other pages) may be it. + const headerView = () => W.m_HeaderStore?.m_currentBrowserAndBackstack?.m_browserView; + const isQam = (v) => !v.__ddMain && v !== headerView() && + (!!v.__ddQamView || !views().some(o => o.__ddQamView) || (probing() && m.m_eOpenSideMenu === MAIN)); + const mainParked = () => split() && (m.m_eOpenSideMenu !== MAIN || probing()); + const mainDoc = () => { + for (const s of SteamUIStore.m_GamepadNavigationManager?.m_rgGamepadInputSources || []) { + try { const d = s.m_targetWindow?.document; if (d?.title?.startsWith("MainMenu")) return d; } catch (e) {} + } + return null; + }; + // Steam slides the main menu out whenever it is not the open side menu; parked, it stays in place and fills its view. + const mainStyle = (on) => { + const d = mainDoc(); + let s = d?.getElementById("dd-main-split"); + if (!on) { s?.remove(); return; } + if (!d?.head) return; + if (!s) { s = d.createElement("style"); s.id = "dd-main-split"; d.head.appendChild(s); } + if (s.textContent !== "$MAIN_PARKED_CSS") s.textContent = "$MAIN_PARKED_CSS"; + }; if (!c.__ddQam) { c.__ddQam = c.ComputeOverallMinimumRequestedComposition; m.__ddQam = m.OnMenuDeactivated; @@ -59,6 +106,18 @@ object SteamQam { return without >= 2 ? v : 1; }; } + // Steam frosts its Store page while a side menu is open; a parked menu is not over it. + const inst = m.m_Instance; + if (inst?.SetStoreBrowserGlass && !inst.__ddQamGlass) { + inst.__ddQamGlass = inst.SetStoreBrowserGlass; + inst.SetStoreBrowserGlass = function (e) { return inst.__ddQamGlass.call(this, ours() ? 0 : e); }; + } + const glass = () => { + const on = !ours() && m.m_eOpenSideMenu !== 0; + if (g.__ddQamGlassOn === on) return; + g.__ddQamGlassOn = on; + inst?.SetStoreBrowserGlass?.(m.m_eOpenSideMenu); + }; const views = () => popup?.m_rgChildBrowserViews || []; const backdrop = (hide) => { const doc = popup?.m_popup?.document; @@ -75,16 +134,61 @@ object SteamQam { }; const keep = () => { for (const v of views()) { - if (v.__ddQam) continue; - v.__ddQam = v.SetBounds; + if (!v.__ddQam) v.__ddQam = v.SetBounds; + if (v.__ddQamW === 4) continue; + v.__ddQamW = 4; + v.__ddQamVis = v.__ddQamVis || v.SetVisible; + v.__ddQamFocus = v.__ddQamFocus || v.SetFocus; v.SetBounds = function (x, y, w, h, ...r) { + if (v.__ddMain && mainParked()) { + if (w > 0) v.__ddMainAsked = [x, y, w, h]; + [w, h] = mainSize(); + v.__ddMainOn = true; v.__ddMainW = w; v.__ddMainH = h; + return v.__ddQam.call(this, parkX(), 0, w, h, ...r); + } + if (v.__ddMain && w > 0) mainStyle(false); v.__ddAsked = [x, y, w, h]; - if (w > 0 && ours()) { x = popup.m_popup.innerWidth + 64; w = width(h) || w; } + if (w > 0 && ours() && isQam(v)) { x = parkX(); [w, h] = size(w, h); } v.__ddAt = x; v.__ddW = w; + v.__ddH = h; return v.__ddQam.call(this, x, y, w, h, ...r); }; + v.SetVisible = function (on, ...r) { + return v.__ddQamVis.call(this, on || (!!v.__ddMain && mainParked()), ...r); + }; + v.SetFocus = function (on, ...r) { + if (on && m.m_eOpenSideMenu === MAIN && v !== headerView()) { + for (const o of views()) if (o !== v) delete o.__ddMain; + v.__ddMain = true; + delete v.__ddQamView; + } + if (on && m.m_eOpenSideMenu === QAM && !v.__ddMain && v !== headerView()) { + for (const o of views()) if (o !== v) delete o.__ddQamView; + v.__ddQamView = true; + } + return v.__ddQamFocus.call(this, on, ...r); + }; } + if (g.__ddMainProbe && !probing()) { g.__ddMainProbe = 0; g.__ddMainProbed = true; } + if (probing() && mainView()) { g.__ddMainProbe = 0; g.__ddMainProbed = true; } + const mv = mainView(); + if (mv && !probing()) { + if (mainParked()) { + const [w, h] = mainSize(); + if (!mv.__ddMainOn || mv.__ddMainW !== w || mv.__ddMainH !== h) { + mv.__ddQam.call(mv, parkX(), 0, w, h); + mv.__ddQamVis.call(mv, true); + mv.__ddMainOn = true; mv.__ddMainW = w; mv.__ddMainH = h; + } + } else if (mv.__ddMainOn) { + mv.__ddMainOn = false; + if (m.m_eOpenSideMenu !== MAIN) { mv.__ddQamVis.call(mv, false); mv.__ddQam.call(mv, 0, 0, 0, 0); } + else if (mv.__ddMainAsked) mv.__ddQam.call(mv, ...mv.__ddMainAsked); + } + } + mainStyle(!!mv && mainParked() && !probing()); + glass(); if (!held()) { const parked = !g.__ddQamTop; g.__ddQamTop = false; @@ -124,6 +228,25 @@ object SteamQam { } g.__ddQamTop = false; } + // Each Split activation gets a fresh probe budget, and a spent one refills after a backoff, so a Steam that was + // still loading does not leave the main menu undiscovered for good. + if (split() !== !!g.__ddQamSplitOn) { g.__ddQamSplitOn = split(); if (split()) g.__ddMainProbes = 0; } + if (split() && !mv) { + if (probing()) return; + if ((g.__ddMainProbes || 0) >= 3 && Date.now() - (g.__ddMainProbeLast || 0) > 30000) g.__ddMainProbes = 0; + if ((g.__ddMainProbes || 0) < 3 && m.m_eOpenSideMenu !== MAIN) { + g.__ddMainProbes = (g.__ddMainProbes || 0) + 1; + g.__ddMainProbeLast = Date.now(); + g.__ddMainProbe = Date.now() + 1500; + m.OpenMainMenu(); + c.EnsureCorrectComposition?.(); + return; + } + } + if (g.__ddMainProbed) { + g.__ddMainProbed = false; + if (m.m_eOpenSideMenu === MAIN) m.OpenQuickAccessMenu(g.__ddQamTab ?? undefined); + } const decky = !!g.DeckyPluginLoader?.tabsHook?.qamBrowserViewPatch; // Decky hooks the menu after Steam starts; the menu has to unmount for its tab to appear, so reopen on the next tick. if (m.m_eOpenSideMenu === QAM && decky && !g.__ddQamDecky) { g.__ddQamDecky = true; m.CloseSideMenus(); return; } @@ -136,18 +259,26 @@ object SteamQam { if (m.m_eQuickAccessTab != null) g.__ddQamTab = m.m_eQuickAccessTab; if (!g.__ddQamOn) { g.__ddQamOn = true; c.EnsureCorrectComposition?.(); } for (const v of views()) { + if (v.__ddMain) continue; + if (!isQam(v)) { + // A view parked before the quick access view was known goes back where Steam asked for it. + const a = v.__ddAsked; + if (a?.[2] > 0 && v.__ddAt >= popup.m_popup.innerWidth) { v.__ddQam.call(v, ...a); v.__ddAt = a[0]; v.__ddW = a[2]; v.__ddH = a[3]; } + continue; + } if (!v.__ddAsked) { const b = v.GetBounds?.(); - if (b && b.width > 0) { v.__ddAsked = [b.x, b.y, b.width, b.height]; v.__ddAt = b.x; v.__ddW = b.width; } + if (b && b.width > 0) { v.__ddAsked = [b.x, b.y, b.width, b.height]; v.__ddAt = b.x; v.__ddW = b.width; v.__ddH = b.height; } } const a = v.__ddAsked; - if (a?.[2] > 0 && (v.__ddAt < popup.m_popup.innerWidth || (width(a[3]) && v.__ddW !== width(a[3])))) v.SetBounds(...a); + const [w, h] = a?.[2] > 0 ? size(a[2], a[3]) : [0, 0]; + if (a?.[2] > 0 && (v.__ddAt < popup.m_popup.innerWidth || v.__ddW !== w || v.__ddH !== h)) v.SetBounds(...a); } const main = nav?.m_rgGamepadNavigationTrees?.find(t => t.m_ID === "GamepadUI_Full_Root"); - if (main && nav.m_LastActiveNavTree?.m_ID?.startsWith("QuickAccess")) nav.SetActiveNavTree(main); + if (main && /^(QuickAccess|MainMenu)/.test(nav.m_LastActiveNavTree?.m_ID ?? "")) nav.SetActiveNavTree(main); backdrop(true); }; - ${leaseScript(on, owner, aspect)} + ${leaseScript(on, owner, aspect, split)} keep(); if (held() && !g.__ddQamTimer) { g.__ddQamTimer = setInterval(() => { @@ -161,7 +292,8 @@ object SteamQam { /** [open] is Steam's open side menu; [top] is true while the menu is shown on the top screen. */ data class Hold(val open: Int, val top: Boolean) - fun hold(context: Context, aspect: Float, owner: Long): Hold? = eval(context, script(true, aspect, owner))?.let(::parseHold) + fun hold(context: Context, aspect: Float, owner: Long, split: Boolean = false): Hold? = + eval(context, script(true, aspect, owner, split))?.let(::parseHold) internal fun parseHold(text: String): Hold? = runCatching { val a = JSONArray(text) @@ -181,7 +313,9 @@ object SteamQam { fun target(context: Context): Target? = runCatching { val devtools = File(AgentGuest.dir(context), "cdp-port").readText().trim().toInt() val (relay, secret) = parseRelay(helper(context, "start", devtools.toString())) ?: return null - val found = runCatching { parseTarget(relay, get(relay, "/$secret/json"))?.let { it.copy(path = "/$secret${it.path}") } } + val found = runCatching { + parseTarget(relay, get(relay, "/$secret/json"))?.let { t -> t.copy(path = "/$secret${t.path}", mainPath = t.mainPath?.let { "/$secret$it" }) } + } if (found.getOrNull() == null) helper(context, "stop", relay.toString()) found.getOrThrow() }.onFailure { android.util.Log.e(TAG, "no quick access target: $it") }.getOrNull() @@ -232,14 +366,16 @@ object SteamQam { internal fun parseTarget(port: Int, json: String): Target? { val list = JSONArray(json) - for (i in 0 until list.length()) { - val t = list.optJSONObject(i) ?: continue - if (!t.optString("title").startsWith("QuickAccess")) continue - val ws = t.optString("webSocketDebuggerUrl") - val path = Regex("^ws://[^/]+(/devtools/page/[A-Za-z0-9-]+)$").find(ws)?.groupValues?.get(1) ?: continue - return Target(port, path) + fun page(prefix: String): String? { + for (i in 0 until list.length()) { + val t = list.optJSONObject(i) ?: continue + if (!t.optString("title").startsWith(prefix)) continue + val ws = t.optString("webSocketDebuggerUrl") + Regex("^ws://[^/]+(/devtools/page/[A-Za-z0-9-]+)$").find(ws)?.groupValues?.get(1)?.let { return it } + } + return null } - return null + return page("QuickAccess")?.let { Target(port, it, page("MainMenu")) } } private fun eval(context: Context, expression: String): String? = runCatching { diff --git a/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt b/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt new file mode 100644 index 0000000000..e547cd8963 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.gpu.GpuInfo +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreGameSidecar +import com.droiddeck.launcher.stores.StoreInstallRoot +import com.droiddeck.launcher.stores.xbox.XboxManifest + +/** + * Microsoft's original Xbox releases for PC run its emulator, which needs FEX and VKD3D-Proton builds with fixes of + * their own (each off unless droiddeck-game-env turns it on for these games) and a newer DXVK than some Protons carry. + * Each installed one gets them as its game components. A component the player chose for the game is never replaced; + * one set here follows this list, so a newer build replaces it, and one the player cleared stays cleared. + */ +internal object XboxBackCompatComponents { + private const val TAG = "XboxBackCompat" + private const val PREFS = "xbox-backcompat-components" + + internal data class Wanted(val comp: String, val file: String, val release: String) + + internal fun wanted(family: GpuInfo.Family?): List = listOf( + Wanted("fex", "FEXCore-2611.1-xbox-bionic.wcp", ComponentsManager.DD_XBOX), + Wanted("vkd3d", "vkd3d-proton-arm64ec-3.1-xbox-linux.wcp", "Vkd3d-proton-Linux"), + Wanted("dxvk", if (family == GpuInfo.Family.A6XX) "dxvk-gplasync-3.2-a6xx-1-linux.wcp" else "dxvk-gplasync-3.2-1-linux.wcp", + "Dxvk-gplasync-Linux"), + ) + + /** The file to set for one component of a game, or null to leave it as it is. */ + internal fun decide(current: String?, assigned: String?, wanted: String): String? = when { + current == null && assigned == null -> wanted + current != null && current == assigned && current != wanted -> wanted + else -> null + } + + internal class Game(val scope: String, val title: String) + + internal fun installed(context: Context): List = StoreInstallRoot.gameFolders(context).mapNotNull { folder -> + val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.store == Store.XBOX && it.isInstalled } ?: return@mapNotNull null + if (!XboxManifest.backCompat(folder)) return@mapNotNull null + val appId = SessionPrefs.storedAddedGameAppId(context, folder.path) ?: return@mapNotNull null + Game(appId.toString(), sidecar.title) + } + + fun ensure(context: Context): String? { + val games = installed(context) + if (games.isEmpty()) return null + val marks = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val wanted = wanted(runCatching { GpuInfo.detect().family }.getOrNull()) + val lines = mutableListOf() + for (game in games) { + val current = ComponentsManager.gameComponents(context, game.scope) + for (w in wanted) { + val key = "${game.scope}/${w.comp}" + val file = decide(current[w.comp], marks.getString(key, null), w.file) ?: continue + val label = ComponentsManager.LABEL[w.comp] + runCatching { + ComponentsManager.assignGameComponent(context, game.scope, w.comp, file, w.release, expected = current[w.comp]) { + marks.edit().putString(key, file).apply() + } + } + .onSuccess { result -> + lines += when (result) { + ComponentsManager.Assigned.SET -> "${game.title}: $label ${file.removeSuffix(".wcp")}" + ComponentsManager.Assigned.NOT_LISTED -> "${game.title}: $file is not listed; $label unchanged" + ComponentsManager.Assigned.CHANGED -> "${game.title}: $label was chosen during the download; kept" + } + } + .onFailure { e -> + Log.w(TAG, "${game.title}: $file", e) + lines += "${game.title}: $label unchanged (${e.message ?: e.javaClass.simpleName})" + } + } + } + return lines.joinToString("; ").ifEmpty { null } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrGesture.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrGesture.kt new file mode 100644 index 0000000000..cbd66f1964 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrGesture.kt @@ -0,0 +1,68 @@ +package com.droiddeck.launcher.session.xr + +/** + * The menu gesture: both controllers held together. It arms when the two aim points come within + * [ARM_METRES], cancels once they part beyond [CANCEL_METRES], and fires after [HOLD_MS] held. + * It needs both controllers apart again before it can arm a second time. + */ +internal class XrGesture { + enum class Phase { IDLE, ARMING, FIRED } + + var phase = Phase.IDLE + private set + var progress = 0f + private set + var midpoint = Vec3.ZERO + private set + private var startedMs = 0L + private var needsRelease = false + + /** Returns true on the frame the gesture completes. */ + fun update(left: XrHand, right: XrHand, nowMs: Long): Boolean { + if (!left.active || !right.active) { + reset(release = false) + return false + } + val a = left.aim.position + val b = right.aim.position + val distance = (a - b).length + midpoint = Vec3.lerp(a, b, 0.5f) + if (needsRelease) { + if (distance > CANCEL_METRES) needsRelease = false + phase = Phase.IDLE + progress = 0f + return false + } + when (phase) { + Phase.IDLE, Phase.FIRED -> if (distance < ARM_METRES) { + phase = Phase.ARMING + startedMs = nowMs + progress = 0f + } + Phase.ARMING -> if (distance > CANCEL_METRES) { + phase = Phase.IDLE + progress = 0f + } else { + progress = ((nowMs - startedMs).toFloat() / HOLD_MS).coerceIn(0f, 1f) + if (progress >= 1f) { + phase = Phase.FIRED + needsRelease = true + return true + } + } + } + return false + } + + fun reset(release: Boolean) { + phase = Phase.IDLE + progress = 0f + if (release) needsRelease = true + } + + companion object { + const val ARM_METRES = 0.09f + const val CANCEL_METRES = 0.14f + const val HOLD_MS = 1500L + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrHost.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrHost.kt new file mode 100644 index 0000000000..48424cccbf --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrHost.kt @@ -0,0 +1,160 @@ +package com.droiddeck.launcher.session.xr + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** + * Typed access to the two buffers quest_xr.cpp shares each frame (app/src/main/cpp/questxr/xr_host.h). + * The offsets here must match that header. + */ +internal object XrHostLayout { + const val VERSION = 1 + const val LAYERS = 6 + const val STATE_SIZE = 288 + const val CONTROL_SIZE = 552 + const val POSE_SIZE = 32 + const val HAND_SIZE = 96 + const val STATE_HEAD = 32 + const val STATE_HANDS = 64 + const val HAND_GRIP = 0 + const val HAND_AIM = 32 + const val HAND_TRIGGER = 64 + const val HAND_SQUEEZE = 68 + const val HAND_STICK = 72 + const val HAND_BUTTONS = 80 + const val HAND_ACTIVE = 84 + const val CONTROL_HANDS = 8 + const val HAND_CONTROL_SIZE = 40 + const val HAND_CONTROL_MASK = 0 + const val HAND_CONTROL_LASER = 4 + const val HAND_CONTROL_HAPTIC = 8 + const val CONTROL_ORB = 88 + const val CONTROL_LAYERS = 136 + const val LAYER_SIZE = 64 + + const val FLAG_SURFACE_SWAPCHAIN = 1 + const val FLAG_FOCUSED = 2 + const val MASK_INPUT = 1 + const val LAYER_ALPHA = 1 + const val LAYER_HEAD_LOCKED = 2 + + const val SECONDARY_CLICK = 1 shl 2 +} + +internal class XrHand( + val grip: Pose, + val aim: Pose, + val trigger: Float, + val squeeze: Float, + val stickX: Float, + val stickY: Float, + val buttons: Int, + val active: Boolean, +) { + val secondary: Boolean get() = buttons and XrHostLayout.SECONDARY_CLICK != 0 + + companion object { + val IDLE = XrHand(Pose(), Pose(), 0f, 0f, 0f, 0f, 0, false) + } +} + +internal class XrFrame(val flags: Int, val frame: Long, val displayTimeNs: Long, val head: Pose, val hands: List) { + val focused: Boolean get() = flags and XrHostLayout.FLAG_FOCUSED != 0 + val surfaces: Boolean get() = flags and XrHostLayout.FLAG_SURFACE_SWAPCHAIN != 0 +} + +internal class XrHaptic(val durationMs: Int, val amplitude: Float, val frequency: Float = 0f) + +internal class XrLayerOut( + val id: Int, + val pose: Pose, + val width: Float, + val height: Float, + val order: Int, + val alpha: Boolean = true, +) + +internal class XrControlOut { + val masks = BooleanArray(2) + val lasers = FloatArray(2) + val haptics = arrayOfNulls(2) + var orb: Orb? = null + val layers = mutableListOf() + + class Orb(val position: Vec3, val radius: Float, val progress: Float, val burst: Float) +} + +internal class XrHost(state: ByteBuffer, control: ByteBuffer) { + private val state = state.order(ByteOrder.nativeOrder()) + private val control = control.order(ByteOrder.nativeOrder()) + private val hapticIds = LongArray(2) + + init { + require(state.capacity() >= XrHostLayout.STATE_SIZE && control.capacity() >= XrHostLayout.CONTROL_SIZE) { "XR host buffers too small" } + } + + fun read(): XrFrame = readFrame(state) + + fun write(out: XrControlOut) = writeControl(control, out, hapticIds) + + companion object { + fun readPose(b: ByteBuffer, at: Int) = Pose( + Quat(b.getFloat(at), b.getFloat(at + 4), b.getFloat(at + 8), b.getFloat(at + 12)), + Vec3(b.getFloat(at + 16), b.getFloat(at + 20), b.getFloat(at + 24)), + ) + + fun writePose(b: ByteBuffer, at: Int, pose: Pose) { + b.putFloat(at, pose.orientation.x); b.putFloat(at + 4, pose.orientation.y) + b.putFloat(at + 8, pose.orientation.z); b.putFloat(at + 12, pose.orientation.w) + b.putFloat(at + 16, pose.position.x); b.putFloat(at + 20, pose.position.y); b.putFloat(at + 24, pose.position.z) + b.putInt(at + 28, 0) + } + + fun readFrame(b: ByteBuffer): XrFrame { + val hands = (0 until 2).map { hand -> + val at = XrHostLayout.STATE_HANDS + hand * XrHostLayout.HAND_SIZE + XrHand( + readPose(b, at + XrHostLayout.HAND_GRIP), readPose(b, at + XrHostLayout.HAND_AIM), + b.getFloat(at + XrHostLayout.HAND_TRIGGER), b.getFloat(at + XrHostLayout.HAND_SQUEEZE), + b.getFloat(at + XrHostLayout.HAND_STICK), b.getFloat(at + XrHostLayout.HAND_STICK + 4), + b.getInt(at + XrHostLayout.HAND_BUTTONS), b.getInt(at + XrHostLayout.HAND_ACTIVE) != 0, + ) + } + return XrFrame(b.getInt(8), b.getLong(16), b.getLong(24), readPose(b, XrHostLayout.STATE_HEAD), hands) + } + + fun writeControl(b: ByteBuffer, out: XrControlOut, hapticIds: LongArray) { + for (i in 0 until XrHostLayout.CONTROL_SIZE step 4) b.putInt(i, 0) + b.putInt(0, XrHostLayout.VERSION) + for (hand in 0 until 2) { + val at = XrHostLayout.CONTROL_HANDS + hand * XrHostLayout.HAND_CONTROL_SIZE + b.putInt(at + XrHostLayout.HAND_CONTROL_MASK, if (out.masks[hand]) XrHostLayout.MASK_INPUT else 0) + b.putFloat(at + XrHostLayout.HAND_CONTROL_LASER, out.lasers[hand]) + out.haptics[hand]?.let { hapticIds[hand]++ } + val haptic = at + XrHostLayout.HAND_CONTROL_HAPTIC + b.putLong(haptic, hapticIds[hand]) + out.haptics[hand]?.let { + b.putLong(haptic + 8, it.durationMs * 1_000_000L) + b.putFloat(haptic + 16, it.amplitude) + b.putFloat(haptic + 20, it.frequency) + } + } + out.orb?.let { orb -> + val at = XrHostLayout.CONTROL_ORB + b.putInt(at, 1) + b.putFloat(at + 4, orb.progress); b.putFloat(at + 8, orb.burst); b.putFloat(at + 12, orb.radius) + writePose(b, at + 16, Pose(position = orb.position)) + } + out.layers.take(XrHostLayout.LAYERS).forEachIndexed { index, layer -> + val at = XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE + b.putInt(at, layer.id) + b.putInt(at + 4, 1) + b.putInt(at + 8, if (layer.alpha) XrHostLayout.LAYER_ALPHA else 0) + b.putInt(at + 12, layer.order) + writePose(b, at + 16, layer.pose) + b.putFloat(at + 48, layer.width); b.putFloat(at + 52, layer.height) + } + for (index in out.layers.size until XrHostLayout.LAYERS) b.putInt(XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE, -1) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrInteraction.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrInteraction.kt new file mode 100644 index 0000000000..d045a87663 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrInteraction.kt @@ -0,0 +1,303 @@ +package com.droiddeck.launcher.session.xr + +import kotlin.math.PI +import kotlin.math.abs + +/** + * [barButton]: the grab bar has a button at its left end; the menu has its own close button instead. + * [tilt]: how far the panel leans back from upright, in radians, as a keyboard lies on a desk. + */ +internal enum class XrPanelKind( + val key: String, val resizable: Boolean, val chrome: Boolean, val barButton: Boolean = false, val tilt: Float = 0f, +) { + MENU("menu", resizable = true, chrome = true), + PET_HEAD("pet_head", resizable = false, chrome = false), + PET_CHAT("pet_chat", resizable = true, chrome = true, barButton = true), + KEYBOARD("keyboard_desk", resizable = true, chrome = true, barButton = true, tilt = (PI / 4).toFloat()); + + /** Turned towards [head] about the vertical axis, then leant back by [tilt]. */ + fun orient(position: Vec3, head: Vec3): Quat = facing(position, head) * Quat.pitch(-tilt) +} + +/** Where a panel is and how big, in metres; [pixelWidth] and [pixelHeight] are its surface's size. */ +internal class XrPanelState(val kind: XrPanelKind, var pose: Pose, var width: Float, var height: Float) { + var pixelWidth = XrUnits.pixels(width) + var pixelHeight = XrUnits.pixels(height) + /** 0 while it opens or closes from [animationFrom], 1 when it is in place and takes input. */ + var scale = 1f + var animationFrom: Vec3? = null + + val shownPose: Pose get() = animationFrom?.let { Pose(pose.orientation, Vec3.lerp(it, pose.position, scale)) } ?: pose + val interactive: Boolean get() = scale >= 1f + + fun hit(ray: Pose): XrHit? = hitPlane(ray, bounded = true) + + /** Where [ray] meets this panel's plane; [bounded] limits it to the panel itself. */ + fun hitPlane(ray: Pose, bounded: Boolean, plane: Pose = pose, w: Float = width, h: Float = height): XrHit? { + val normal = plane.orientation.rotate(Vec3(0f, 0f, 1f)) + val direction = ray.forward + val denominator = direction dot normal + if (denominator > -1e-4f) return null + val distance = ((plane.position - ray.position) dot normal) / denominator + if (distance <= 0f) return null + val local = plane.toLocal(ray.position + direction * distance) + if (bounded && (abs(local.x) > w / 2f || abs(local.y) > h / 2f)) return null + return XrHit(this, local.x, local.y, distance) + } + + fun u(localX: Float) = (localX / width + 0.5f).coerceIn(0f, 1f) + fun v(localY: Float) = (0.5f - localY / height).coerceIn(0f, 1f) + fun pixelX(localX: Float) = u(localX) * pixelWidth + fun pixelY(localY: Float) = v(localY) * pixelHeight + + /** The grab bar runs along the bottom, as under Quest's own windows, with its button at the left end. */ + fun inBar(hit: XrHit) = kind.chrome && hit.y + 0.5f * height <= XrUnits.BAR_METRES + fun inBarButtons(hit: XrHit) = kind.barButton && inBar(hit) && hit.x + 0.5f * width <= XrUnits.BAR_BUTTONS_METRES + fun inResizeGrip(hit: XrHit) = kind.resizable && + 0.5f * width - hit.x <= XrUnits.GRIP_METRES && hit.y + 0.5f * height <= XrUnits.GRIP_METRES +} + +internal class XrHit(val panel: XrPanelState, val x: Float, val y: Float, val distance: Float) + +internal object XrUnits { + const val DP_PER_METRE = 900f + const val DENSITY = 2f + const val DPI = 320 + const val BAR_METRES = 52f / DP_PER_METRE + const val BAR_BUTTONS_DP = 150f + const val BAR_BUTTONS_METRES = BAR_BUTTONS_DP / DP_PER_METRE + const val GRIP_METRES = 0.05f + const val MIN_METRES = 0.3f + const val MAX_METRES = 1.6f + const val MIN_DISTANCE = 0.4f + const val MAX_DISTANCE = 3f + fun pixels(metres: Float) = (metres * DP_PER_METRE * DENSITY).toInt().coerceAtLeast(16) +} + +internal sealed class XrPointerEvent(val panel: XrPanelState) { + class Down(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel) + class Move(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel) + class Up(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel) + class Cancel(panel: XrPanelState, val hand: Int = 0) : XrPointerEvent(panel) + class Scroll(panel: XrPanelState, val x: Float, val y: Float, val amount: Float) : XrPointerEvent(panel) + class Back(panel: XrPanelState) : XrPointerEvent(panel) + class Click(panel: XrPanelState) : XrPointerEvent(panel) + class Resized(panel: XrPanelState) : XrPointerEvent(panel) + class Moved(panel: XrPanelState) : XrPointerEvent(panel) +} + +internal class XrInteractionOut { + val events = mutableListOf() + val masks = BooleanArray(2) + val lasers = FloatArray(2) + val ticks = BooleanArray(2) + /** Where each controller points on each panel, in its pixels, left hand first; panels with no entry show none. */ + val cursors = mutableMapOf>>() + + fun point(panel: XrPanelState, x: Float, y: Float) { + cursors.getOrPut(panel) { mutableListOf() } += x to y + } +} + +/** + * What the two controllers do to the panels each frame. A controller acts on a panel only while it + * points at one, or while it holds one it picked up, pressed or is resizing; only then is its input + * taken from the game. + */ +internal class XrInteraction { + private sealed class Hold { + object None : Hold() + class Press(val panel: XrPanelState, var x: Float, var y: Float) : Hold() + class Move(val panel: XrPanelState, var offset: Vec3, val byGrip: Boolean) : Hold() + class Resize(val panel: XrPanelState, val plane: Pose, val width: Float, val height: Float, val startX: Float, val startY: Float) : Hold() + class HeadPress(val panel: XrPanelState, val startX: Float, val startY: Float, val offset: Vec3) : Hold() + } + + private val holds = arrayOf(Hold.None, Hold.None) + private val trigger = BooleanArray(2) + private val grip = BooleanArray(2) + private val secondary = BooleanArray(2) + + fun holding(panel: XrPanelState) = holds.any { held(it) === panel } + + private fun held(hold: Hold): XrPanelState? = when (hold) { + is Hold.Press -> hold.panel + is Hold.Move -> hold.panel + is Hold.Resize -> hold.panel + is Hold.HeadPress -> hold.panel + Hold.None -> null + } + + /** Lets go of everything, as when the immersive view goes. A button still held counts only once let go and pressed again. */ + fun reset() { + holds.fill(Hold.None) + trigger.fill(true) + grip.fill(true) + secondary.fill(true) + } + + /** Cancels a press and ends a move or resize where it is, as when the headset loses focus; then [reset]. */ + fun cancel(out: XrInteractionOut) { + for ((hand, hold) in holds.withIndex()) when (hold) { + is Hold.Press -> out.events += XrPointerEvent.Cancel(hold.panel, hand) + is Hold.Move -> out.events += XrPointerEvent.Moved(hold.panel) + is Hold.Resize -> out.events += XrPointerEvent.Resized(hold.panel) + else -> Unit + } + reset() + } + + /** Lets go of [panel], as when it closes. */ + fun release(panel: XrPanelState, out: XrInteractionOut) { + for (hand in 0..1) if (held(holds[hand]) === panel) { + if (holds[hand] is Hold.Press) out.events += XrPointerEvent.Cancel(panel, hand) + holds[hand] = Hold.None + } + } + + fun update(head: Pose, hands: List, panels: List, dtSeconds: Float): XrInteractionOut { + val out = XrInteractionOut() + for (hand in 0..1) handFrame(hand, head, hands[hand], panels.filter { it.interactive }, dtSeconds, out) + return out + } + + private fun handFrame(index: Int, head: Pose, hand: XrHand, panels: List, dt: Float, out: XrInteractionOut) { + val wasTrigger = trigger[index] + val wasGrip = grip[index] + val wasSecondary = secondary[index] + trigger[index] = if (wasTrigger) hand.trigger > 0.4f else hand.trigger > 0.6f + grip[index] = if (wasGrip) hand.squeeze > 0.5f else hand.squeeze > 0.7f + secondary[index] = hand.secondary + val triggerDown = trigger[index] && !wasTrigger + val triggerUp = !trigger[index] && wasTrigger + val gripDown = grip[index] && !wasGrip + val secondaryDown = secondary[index] && !wasSecondary + val hold = holds[index] + if (!hand.active) { + if (hold is Hold.Press) out.events += XrPointerEvent.Cancel(hold.panel, index) + if (hold is Hold.Move) out.events += XrPointerEvent.Moved(hold.panel) + if (hold is Hold.Resize) out.events += XrPointerEvent.Resized(hold.panel) + holds[index] = Hold.None + return + } + val ray = hand.aim + when (hold) { + is Hold.Move -> { + val panel = hold.panel + if (abs(hand.stickY) > 0.2f) { + val length = hold.offset.length + val wanted = (length * (1f + hand.stickY * 1.2f * dt)).coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE) + hold.offset = hold.offset.normalized() * wanted + } + val position = ray.toWorld(hold.offset) + panel.pose = Pose(panel.kind.orient(position, head.position), position) + out.masks[index] = true + out.lasers[index] = hold.offset.length + val released = if (hold.byGrip) !grip[index] else !trigger[index] + if (released) { + holds[index] = Hold.None + out.events += XrPointerEvent.Moved(panel) + } + return + } + is Hold.Resize -> { + val panel = hold.panel + out.masks[index] = true + hold.panel.hitPlane(ray, bounded = false, plane = hold.plane, w = hold.width, h = hold.height)?.let { hit -> + val left = -hold.width / 2f + val top = hold.height / 2f + val width = (hold.width + hit.x - hold.startX).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) + val height = (hold.height + hold.startY - hit.y).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) + panel.width = width + panel.height = height + panel.pose = Pose(hold.plane.orientation, hold.plane.toWorld(Vec3(left + width / 2f, top - height / 2f, 0f))) + out.lasers[index] = hit.distance + } + if (!trigger[index]) { + holds[index] = Hold.None + out.events += XrPointerEvent.Resized(panel) + } + return + } + is Hold.Press -> { + val panel = hold.panel + out.masks[index] = true + val hit = panel.hitPlane(ray, bounded = false) + if (hit != null) { + val x = panel.pixelX(hit.x) + val y = panel.pixelY(hit.y) + if (x != hold.x || y != hold.y) out.events += XrPointerEvent.Move(panel, x, y, index) + hold.x = x; hold.y = y + out.lasers[index] = hit.distance + out.point(panel, x, y) + } + if (secondaryDown) out.events += XrPointerEvent.Back(panel) + if (triggerUp || !trigger[index]) { + out.events += if (hit != null) XrPointerEvent.Up(panel, hold.x, hold.y, index) else XrPointerEvent.Cancel(panel, index) + holds[index] = Hold.None + } + return + } + is Hold.HeadPress -> { + val panel = hold.panel + out.masks[index] = true + val hit = panel.hitPlane(ray, bounded = false) + if (hit != null) { + out.lasers[index] = hit.distance + val moved = Vec3(hit.x - hold.startX, hit.y - hold.startY, 0f).length + if (moved > HEAD_DRAG_METRES) { + holds[index] = Hold.Move(panel, hold.offset, byGrip = false) + val position = ray.toWorld(hold.offset) + panel.pose = Pose(panel.kind.orient(position, head.position), position) + return + } + } + if (!trigger[index]) { + holds[index] = Hold.None + if (panel.hit(ray) != null) out.events += XrPointerEvent.Click(panel) + } + return + } + Hold.None -> Unit + } + val hit = panels.mapNotNull { it.hit(ray) }.minByOrNull { it.distance } ?: return + val panel = hit.panel + out.masks[index] = true + out.lasers[index] = hit.distance + val x = panel.pixelX(hit.x) + val y = panel.pixelY(hit.y) + out.point(panel, x, y) + val other = holds[1 - index] + val heldByOther = held(other) === panel && other !is Hold.Press + when { + heldByOther -> Unit + gripDown -> { + holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = true) + out.ticks[index] = true + } + triggerDown && panel.kind == XrPanelKind.PET_HEAD -> + holds[index] = Hold.HeadPress(panel, hit.x, hit.y, ray.toLocal(panel.pose.position)) + triggerDown && panel.inResizeGrip(hit) -> { + holds[index] = Hold.Resize(panel, panel.pose, panel.width, panel.height, hit.x, hit.y) + out.ticks[index] = true + } + triggerDown && panel.inBar(hit) && !panel.inBarButtons(hit) -> { + holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = false) + out.ticks[index] = true + } + triggerDown -> { + holds[index] = Hold.Press(panel, x, y) + out.events += XrPointerEvent.Down(panel, x, y, index) + } + } + if (holds[index] === Hold.None) { + if (abs(hand.stickY) > 0.25f) out.events += XrPointerEvent.Scroll(panel, x, y, hand.stickY * SCROLL_PER_SECOND * dt) + if (secondaryDown) out.events += XrPointerEvent.Back(panel) + } + } + + companion object { + const val HEAD_DRAG_METRES = 0.02f + const val SCROLL_PER_SECOND = 12f + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrKeyboard.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrKeyboard.kt new file mode 100644 index 0000000000..275322d745 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrKeyboard.kt @@ -0,0 +1,283 @@ +package com.droiddeck.launcher.session.xr + +import android.view.KeyEvent +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.Backspace +import androidx.compose.material.icons.automirrored.outlined.KeyboardReturn +import androidx.compose.material.icons.outlined.KeyboardArrowUp +import androidx.compose.material3.Icon +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 +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.compositeOver +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.EditCommand +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.ImeOptions +import androidx.compose.ui.text.input.PlatformTextInputService +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.input.PC_KEY_ROWS +import kotlinx.coroutines.delay +import com.droiddeck.launcher.ui.TypingRequest + +/** Sends text fields in the floating panels to [XrKeyboard], since the system keyboard cannot show in the immersive view. */ +internal class XrTextInput : PlatformTextInputService { + private var request: TypingRequest? = null + + override fun startInput( + value: TextFieldValue, imeOptions: ImeOptions, + onEditCommand: (List) -> Unit, onImeActionPerformed: (ImeAction) -> Unit, + ) { + val next = TypingRequest(value, imeOptions, { onEditCommand(TypingRequest.editsFor(it)) }, onImeActionPerformed) + request = next + XrPanels.startTyping(next) + } + + override fun stopInput() { + request?.let { XrPanels.stopTyping(it) } + request = null + } + + override fun showSoftwareKeyboard() { + request?.let { XrPanels.startTyping(it) } + } + + override fun hideSoftwareKeyboard() { + request?.let { XrPanels.stopTyping(it) } + } + + override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) { + request?.value = newValue + } +} + +internal object XrKeys { + private val letters = listOf("qwertyuiop", "asdfghjkl", "zxcvbnm") + private val symbols = listOf("1234567890", "@#&*-+=()", "!?:;'\"/,") + + fun rows(numbers: Boolean, shift: Boolean): List = + (if (numbers) symbols else letters).map { if (shift && !numbers) it.uppercase() else it } + + fun insert(value: TextFieldValue, text: String): TextFieldValue { + val start = minOf(value.selection.start, value.selection.end) + val end = maxOf(value.selection.start, value.selection.end) + val next = value.text.substring(0, start) + text + value.text.substring(end) + return TextFieldValue(next, TextRange(start + text.length)) + } + + fun backspace(value: TextFieldValue): TextFieldValue { + val start = minOf(value.selection.start, value.selection.end) + val end = maxOf(value.selection.start, value.selection.end) + if (start != end) return TextFieldValue(value.text.substring(0, start) + value.text.substring(end), TextRange(start)) + if (start == 0) return value + val cut = value.text.offsetByCodePoints(start, -1) + return TextFieldValue(value.text.substring(0, cut) + value.text.substring(start), TextRange(cut)) + } + + const val REPEAT_DELAY_MS = 450L + const val REPEAT_MS = 50L + + /** Return sends when the field asks for an action, and starts a new line otherwise. */ + fun returnSends(options: ImeOptions) = options.imeAction != ImeAction.Default && options.imeAction != ImeAction.None && + options.singleLine +} + +/** Where the laser keyboard's keys go: a text field in a panel, or the game. */ +internal interface XrKeyTarget { + fun type(text: String) + fun backspace() + fun enter() +} + +internal class XrFieldTarget(private val request: TypingRequest) : XrKeyTarget { + override fun type(text: String) = request.send(XrKeys.insert(request.value, text)) + override fun backspace() = request.send(XrKeys.backspace(request.value)) + override fun enter() = if (XrKeys.returnSends(request.imeOptions)) request.action() else type("\n") +} + +internal class XrGameTarget(private val host: XrMenuHost) : XrKeyTarget { + override fun type(text: String) = host.xrTypeText(text) + override fun backspace() = host.xrTapKey(KeyEvent.KEYCODE_DEL) + override fun enter() = host.xrTapKey(KeyEvent.KEYCODE_ENTER) +} + +/** + * DroidDeck's PC keyboard typing into a panel's text field: the keys that make a character type it, + * Backspace, Enter and Space edit, and Shift and Caps Lock pick the case. The rest have nothing to do there. + */ +internal class XrPcText(private val target: XrKeyTarget, private val timer: XrTimer = XrTimer.Main) { + private val keys = PC_KEY_ROWS.flatten() + .filter { it.labelRes == 0 && it.label.length == 1 && it.code !in ARROWS } + .associateBy { it.code } + private val shifts = mutableSetOf() + private var caps = false + private var stopRepeat: (() -> Unit)? = null + + fun key(code: Int, down: Boolean) { + if (code == LEFT_SHIFT || code == RIGHT_SHIFT) { + if (down) shifts += code else shifts -= code + return + } + if (!down && code != BACKSPACE) return + stopRepeat?.invoke() + stopRepeat = null + if (!down) return + val shifted = shifts.isNotEmpty() + when (code) { + BACKSPACE -> { + target.backspace() + stopRepeat = timer.after(XrKeys.REPEAT_DELAY_MS, ::repeatBackspace) + } + ENTER -> target.enter() + SPACE -> target.type(" ") + CAPS -> caps = !caps + else -> keys[code]?.let { key -> + target.type(when { + shifted && key.shifted != null -> key.shifted + key.label[0].isLetter() && (shifted xor caps) -> key.label.uppercase() + else -> key.label + }) + } + } + } + + private fun repeatBackspace() { + target.backspace() + stopRepeat = timer.after(XrKeys.REPEAT_MS, ::repeatBackspace) + } + + private companion object { + const val LEFT_SHIFT = 42 + const val RIGHT_SHIFT = 54 + const val BACKSPACE = 14 + const val ENTER = 28 + const val SPACE = 57 + const val CAPS = 58 + val ARROWS = setOf(103, 105, 106, 108) + } +} + +/** Runs an action later on the main thread; the function it returns cancels it. */ +internal fun interface XrTimer { + fun after(ms: Long, action: () -> Unit): () -> Unit + + companion object { + private val handler by lazy { android.os.Handler(android.os.Looper.getMainLooper()) } + val Main = XrTimer { ms, action -> + val runnable = Runnable(action) + handler.postDelayed(runnable, ms) + ({ handler.removeCallbacks(runnable) }) + } + } +} + +/** The Android-style text keyboard. */ +@Composable +internal fun XrKeyboard(target: XrKeyTarget) { + var shift by remember { mutableStateOf(false) } + var numbers by remember { mutableStateOf(false) } + fun type(text: String) { + target.type(text) + if (shift) shift = false + } + Column(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + XrKeys.rows(numbers, shift).forEachIndexed { index, row -> + Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (index == 2) KeyIcon(Icons.Outlined.KeyboardArrowUp, stringResource(R.string.pckb_key_shift), active = shift, weight = 1.5f) { shift = !shift } + row.forEach { key -> Key(key.toString()) { type(key.toString()) } } + if (index == 2) KeyIcon(Icons.AutoMirrored.Outlined.Backspace, stringResource(R.string.pckb_key_backspace), weight = 1.5f, repeats = true) { target.backspace() } + } + } + Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Key(if (numbers) "abc" else "?123", weight = 1.5f) { numbers = !numbers } + Key(",") { type(",") } + Key(" ", weight = 5f) { type(" ") } + Key(".") { type(".") } + KeyIcon(Icons.AutoMirrored.Outlined.KeyboardReturn, stringResource(R.string.pckb_key_enter), weight = 1.5f) { target.enter() } + } + } +} + +/** A key that lights while the laser is over it and dips while it is pressed; [repeats] keeps acting while held. */ +@Composable +private fun RowScope.KeyBox( + weight: Float, active: Boolean, onClick: () -> Unit, repeats: Boolean = false, content: @Composable (Color) -> Unit, +) { + val colors = MaterialTheme.colorScheme + val source = remember { MutableInteractionSource() } + val (pointedAt, pointed) = rememberXrPointed() + val hovered = pointed.value + val pressed by source.collectIsPressedAsState() + val action by rememberUpdatedState(onClick) + var repeated by remember { mutableStateOf(false) } + if (repeats) LaunchedEffect(pressed) { + if (!pressed) return@LaunchedEffect + repeated = false + delay(XrKeys.REPEAT_DELAY_MS) + repeated = true + while (true) { + action() + delay(XrKeys.REPEAT_MS) + } + } + val fill by animateColorAsState( + when { + pressed -> colors.primary + active -> colors.primary.copy(alpha = 0.8f) + hovered -> colors.onSurface.copy(alpha = 0.22f).compositeOver(colors.surfaceVariant) + else -> colors.surfaceVariant + }, tween(if (pressed) 40 else 140), label = "keyFill", + ) + val scale by animateFloatAsState(if (pressed) 0.9f else if (hovered) 1.05f else 1f, tween(if (pressed) 40 else 140), label = "keyScale") + Box( + Modifier.weight(weight).fillMaxHeight() + .then(pointedAt) + .graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale } + .clip(RoundedCornerShape(8.dp)).background(fill) + .border(if (hovered) 2.dp else 0.dp, if (hovered) colors.primary else Color.Transparent, RoundedCornerShape(8.dp)) + .clickable(interactionSource = source, indication = null) { if (repeated) repeated = false else onClick() }, + contentAlignment = Alignment.Center, + ) { content(if (pressed || active) colors.onPrimary else colors.onSurface) } +} + +@Composable +private fun RowScope.Key(label: String, weight: Float = 1f, onClick: () -> Unit) = + KeyBox(weight, active = false, onClick) { tint -> Text(label, color = tint, fontSize = 22.sp, maxLines = 1) } + +@Composable +private fun RowScope.KeyIcon(icon: ImageVector, label: String, active: Boolean = false, weight: Float = 1f, repeats: Boolean = false, onClick: () -> Unit) = + KeyBox(weight, active, onClick, repeats) { tint -> Icon(icon, label, tint = tint) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrMath.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrMath.kt new file mode 100644 index 0000000000..4f5072f142 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrMath.kt @@ -0,0 +1,61 @@ +package com.droiddeck.launcher.session.xr + +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.sqrt + +internal data class Vec3(val x: Float, val y: Float, val z: Float) { + operator fun plus(o: Vec3) = Vec3(x + o.x, y + o.y, z + o.z) + operator fun minus(o: Vec3) = Vec3(x - o.x, y - o.y, z - o.z) + operator fun times(s: Float) = Vec3(x * s, y * s, z * s) + infix fun dot(o: Vec3) = x * o.x + y * o.y + z * o.z + infix fun cross(o: Vec3) = Vec3(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x) + val length: Float get() = sqrt(this dot this) + fun normalized(): Vec3 = length.let { if (it > 1e-6f) this * (1f / it) else ZERO } + + companion object { + val ZERO = Vec3(0f, 0f, 0f) + val FORWARD = Vec3(0f, 0f, -1f) + val UP = Vec3(0f, 1f, 0f) + fun lerp(a: Vec3, b: Vec3, t: Float) = a + (b - a) * t + } +} + +internal data class Quat(val x: Float, val y: Float, val z: Float, val w: Float) { + fun rotate(v: Vec3): Vec3 { + val u = Vec3(x, y, z) + return u * (2f * (u dot v)) + v * (w * w - (u dot u)) + (u cross v) * (2f * w) + } + + fun conjugate() = Quat(-x, -y, -z, w) + + operator fun times(o: Quat) = Quat( + w * o.x + x * o.w + y * o.z - z * o.y, + w * o.y - x * o.z + y * o.w + z * o.x, + w * o.z + x * o.y - y * o.x + z * o.w, + w * o.w - x * o.x - y * o.y - z * o.z, + ) + + companion object { + val IDENTITY = Quat(0f, 0f, 0f, 1f) + fun yaw(radians: Float) = Quat(0f, sin(radians / 2f), 0f, cos(radians / 2f)) + fun pitch(radians: Float) = Quat(sin(radians / 2f), 0f, 0f, cos(radians / 2f)) + } +} + +internal data class Pose(val orientation: Quat = Quat.IDENTITY, val position: Vec3 = Vec3.ZERO) { + val forward: Vec3 get() = orientation.rotate(Vec3.FORWARD) + fun toLocal(world: Vec3): Vec3 = orientation.conjugate().rotate(world - position) + fun toWorld(local: Vec3): Vec3 = position + orientation.rotate(local) +} + +/** Yaw of a direction in the horizontal plane, 0 along -Z, matching [Quat.yaw] applied to -Z. */ +internal fun yawOf(direction: Vec3): Float = atan2(-direction.x, -direction.z) + +/** An orientation that turns +Z, the side of a quad that shows, from [position] towards [target] about the vertical axis only. */ +internal fun facing(position: Vec3, target: Vec3): Quat { + val d = target - position + if (d.x * d.x + d.z * d.z < 1e-8f) return Quat.IDENTITY + return Quat.yaw(atan2(d.x, d.z)) +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelChrome.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelChrome.kt new file mode 100644 index 0000000000..00540563a1 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelChrome.kt @@ -0,0 +1,126 @@ +package com.droiddeck.launcher.session.xr + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Remove +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** + * The frame of a floating panel: the content, a bar under it to grab it by with up to two buttons at + * its left end, a corner grip to resize it, and the dot where a controller points. Its sizes match [XrUnits]. + */ +@Composable +internal fun XrPanelChrome( + cursor: State>>, + buttons: List, + resizable: Boolean, + content: @Composable () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val shape = RoundedCornerShape(18.dp) + Box(Modifier.fillMaxSize().clip(shape).background(colors.background).border(1.dp, Color(0x33FFFFFF), shape)) { + Column(Modifier.fillMaxSize()) { + Box(Modifier.weight(1f).fillMaxWidth().padding(start = 10.dp, top = 10.dp, end = 10.dp)) { + CompositionLocalProvider(LocalXrPointers provides cursor) { content() } + } + Box( + Modifier.fillMaxWidth().height(52.dp).background(colors.surfaceVariant.copy(alpha = 0.6f)), + contentAlignment = Alignment.Center, + ) { + Box(Modifier.width(72.dp).height(6.dp).clip(CircleShape).background(colors.onSurface.copy(alpha = 0.35f))) + if (buttons.isNotEmpty()) Row( + Modifier.align(Alignment.CenterStart).width(XrUnits.BAR_BUTTONS_DP.dp).padding(start = 8.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + buttons.take(2).forEach { button -> + if (button.icon != null) IconButton(onClick = button.onClick, modifier = Modifier.size(44.dp)) { + Icon(button.icon, button.label, tint = colors.onSurface) + } else TextButton(onClick = button.onClick, modifier = Modifier.height(40.dp), contentPadding = PaddingValues(horizontal = 10.dp)) { + Text(button.label, color = colors.onSurface, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1) + } + } + } + } + } + if (resizable) Canvas(Modifier.align(Alignment.BottomEnd).padding(6.dp).size(28.dp)) { + val stroke = Stroke(width = 3.dp.toPx()) + for (step in 1..3) { + val inset = size.width * step / 4f + drawLine(Color(0x99FFFFFF), Offset(size.width, inset), Offset(inset, size.height), stroke.width) + } + } + val density = LocalDensity.current + Canvas(Modifier.fillMaxSize()) { + val radius = with(density) { 7.dp.toPx() } + for ((x, y) in cursor.value) { + drawCircle(Color(0xCC1E9EFF), radius, Offset(x, y)) + drawCircle(Color.White, radius, Offset(x, y), style = Stroke(with(density) { 2.dp.toPx() })) + } + } + } +} + +/** Where each laser meets the panel, in the panel's pixels; null off a floating panel. */ +internal val LocalXrPointers = staticCompositionLocalOf>>?> { null } + +/** + * Whether a laser rests on the element the returned [Modifier] is put on, for both controllers at + * once, where a mouse hover has room for one. False off a floating panel. + */ +@Composable +internal fun rememberXrPointed(): Pair> { + val pointers = LocalXrPointers.current + var bounds by remember { mutableStateOf(Rect.Zero) } + val pointed = remember(pointers) { + derivedStateOf { pointers != null && pointers.value.any { (x, y) -> bounds.contains(Offset(x, y)) } } + } + return Modifier.onGloballyPositioned { bounds = it.boundsInWindow() } to pointed +} + +/** With no [icon] the button shows [label] itself, for a short word such as a keyboard mode. */ +internal class XrPanelButton(val icon: ImageVector?, val label: String, val onClick: () -> Unit) + +internal val XrCollapseIcon get() = Icons.Outlined.Remove diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelWindow.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelWindow.kt new file mode 100644 index 0000000000..0d54d8cafe --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelWindow.kt @@ -0,0 +1,271 @@ +package com.droiddeck.launcher.session.xr + +import android.app.Presentation +import android.content.Context +import android.hardware.display.DisplayManager +import android.hardware.display.VirtualDisplay +import android.os.Bundle +import android.os.SystemClock +import android.view.InputDevice +import android.view.MotionEvent +import android.view.Surface +import android.view.View +import android.view.ViewGroup +import android.view.WindowManager +import android.view.inspector.WindowInspector +import android.widget.FrameLayout +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalTextInputService +import androidx.compose.ui.text.input.TextInputService +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.activity.OnBackPressedDispatcher +import androidx.activity.OnBackPressedDispatcherOwner +import androidx.activity.setViewTreeOnBackPressedDispatcherOwner +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.ViewModelStoreOwner +import androidx.lifecycle.setViewTreeLifecycleOwner +import androidx.lifecycle.setViewTreeViewModelStoreOwner +import androidx.savedstate.SavedStateRegistry +import androidx.savedstate.SavedStateRegistryController +import androidx.savedstate.SavedStateRegistryOwner +import androidx.savedstate.setViewTreeSavedStateRegistryOwner +import com.droiddeck.launcher.ui.LocalPresentationWindow + +/** Keeps a panel's Compose content running while the activity that made it is stopped behind the XR view. */ +private class PanelOwner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner, OnBackPressedDispatcherOwner { + private val registry = LifecycleRegistry(this) + private val saved = SavedStateRegistryController.create(this) + override val lifecycle: Lifecycle get() = registry + override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry + override val viewModelStore = ViewModelStore() + override val onBackPressedDispatcher = OnBackPressedDispatcher() + + fun own(view: View) { + view.setViewTreeLifecycleOwner(this) + view.setViewTreeSavedStateRegistryOwner(this) + view.setViewTreeViewModelStoreOwner(this) + view.setViewTreeOnBackPressedDispatcherOwner(this) + } + + init { + saved.performRestore(null) + registry.currentState = Lifecycle.State.RESUMED + } + + fun destroy() { + registry.currentState = Lifecycle.State.DESTROYED + viewModelStore.clear() + } +} + +/** + * One floating panel's Android side: a private virtual display drawing into the panel's OpenXR + * surface, and a presentation on it holding the Compose content. Main thread only. + */ +internal class XrPanelWindow( + private val context: Context, + private var surface: Surface, + width: Int, + height: Int, + startPaused: Boolean, + private val content: @Composable () -> Unit, +) { + private var paused = startPaused + private val owner = PanelOwner() + private val textInput = TextInputService(XrTextInput()) + private val display: VirtualDisplay = context.getSystemService(DisplayManager::class.java).createVirtualDisplay( + "DroidDeck XR panel", width, height, XrUnits.DPI, surface.takeUnless { paused }, DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY, + ) + private val presentation = PanelPresentation(context, display.display) + private var downTime = 0L + private var target: View? = null + /** The controllers pressing the panel, by hand, as fingers of one touch. */ + private val touches = linkedMapOf>() + private var hovering: View? = null + private var hoverAt = 0f to 0f + private var cursor: Pair? = null + + init { + try { + presentation.show() + } catch (failure: RuntimeException) { + release() + throw failure + } + } + + val displayId: Int get() = display.display.displayId + + fun resize(surface: Surface, width: Int, height: Int) { + this.surface = surface + if (!paused) display.surface = surface + display.resize(width, height, XrUnits.DPI) + } + + /** Stops drawing into the panel's layer, or starts again. */ + fun pause(pause: Boolean) { + if (pause == paused) return + paused = pause + display.surface = if (pause) null else surface + } + + fun release() { + runCatching { presentation.dismiss() } + owner.destroy() + display.release() + } + + private inner class PanelPresentation(outer: Context, display: android.view.Display) : Presentation(outer, display) { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + window?.setBackgroundDrawableResource(android.R.color.transparent) + window?.addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) + val compose = ComposeView(context).apply { + owner.own(this) + setContent { + CompositionLocalProvider( + LocalPresentationWindow provides true, + LocalTextInputService provides textInput, + ) { content() } + } + } + val frame = FrameLayout(context).apply { + addView(compose, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + } + setContentView(frame) + window?.decorView?.let(owner::own) + } + } + + /** + * The topmost window on this panel's display under the point, so popups and dialogs get the input. + * A focusable popup or dialog on top takes a press outside it too, as on a touchscreen, where it + * dismisses itself rather than letting the press act on what is behind it. + */ + private fun rootAt(x: Float, y: Float): View? { + val roots = WindowInspector.getGlobalWindowViews().filter { it.isAttachedToWindow && it.display?.displayId == displayId && it.isShown } + val location = IntArray(2) + fun contains(root: View): Boolean { + root.getLocationOnScreen(location) + return x >= location[0] && y >= location[1] && x < location[0] + root.width && y < location[1] + root.height + } + val top = roots.lastOrNull() ?: return null + val focusable = (top.layoutParams as? WindowManager.LayoutParams) + ?.let { it.flags and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE == 0 } ?: false + if (roots.size > 1 && focusable && !contains(top)) return top + return roots.lastOrNull(::contains) ?: top + } + + /** Sends every finger in [touches] to [target]; [action] is already shifted by its pointer index where it needs one. */ + private fun sendTouches(action: Int, time: Long) { + val view = target ?: return + val location = IntArray(2) + view.getLocationOnScreen(location) + val properties = touches.keys.map { hand -> + MotionEvent.PointerProperties().apply { id = hand; toolType = MotionEvent.TOOL_TYPE_FINGER } + }.toTypedArray() + val coords = touches.values.map { (x, y) -> + MotionEvent.PointerCoords().apply { this.x = x - location[0]; this.y = y - location[1]; pressure = 1f; size = 1f } + }.toTypedArray() + val event = MotionEvent.obtain(downTime, time, action, touches.size, properties, coords, 0, 0, 1f, 1f, 0, 0, + InputDevice.SOURCE_TOUCHSCREEN, 0) + try { + view.dispatchTouchEvent(event) + } finally { + event.recycle() + } + } + + private fun indexed(action: Int, hand: Int) = + action or (touches.keys.indexOf(hand) shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) + + private fun send(view: View, action: Int, x: Float, y: Float, time: Long, generic: Boolean, scroll: Float = 0f): Boolean { + val location = IntArray(2) + view.getLocationOnScreen(location) + val properties = arrayOf(MotionEvent.PointerProperties().apply { + id = 0 + toolType = if (generic) MotionEvent.TOOL_TYPE_MOUSE else MotionEvent.TOOL_TYPE_FINGER + }) + val coords = arrayOf(MotionEvent.PointerCoords().apply { + this.x = x - location[0] + this.y = y - location[1] + pressure = 1f + size = 1f + if (scroll != 0f) setAxisValue(MotionEvent.AXIS_VSCROLL, scroll) + }) + val source = if (generic) InputDevice.SOURCE_MOUSE else InputDevice.SOURCE_TOUCHSCREEN + val event = MotionEvent.obtain(if (generic) time else downTime, time, action, 1, properties, coords, 0, 0, 1f, 1f, 0, 0, source, 0) + return try { + if (generic) view.dispatchGenericMotionEvent(event) else view.dispatchTouchEvent(event) + } finally { + event.recycle() + } + } + + /** The laser resting on the panel, as a mouse hovering, so keys and buttons light under it. Null: it left. */ + fun hover(at: Pair?) { + cursor = at + if (target != null) return + val now = SystemClock.uptimeMillis() + val root = at?.let { (x, y) -> rootAt(x, y) } + if (root !== hovering) endHover(now) + if (root == null || at == null) return + if (hovering == null) send(root, MotionEvent.ACTION_HOVER_ENTER, at.first, at.second, now, generic = true) + send(root, MotionEvent.ACTION_HOVER_MOVE, at.first, at.second, now, generic = true) + hovering = root + hoverAt = at + } + + private fun endHover(now: Long) { + hovering?.let { send(it, MotionEvent.ACTION_HOVER_EXIT, hoverAt.first, hoverAt.second, now, generic = true) } + hovering = null + } + + fun pointer(event: XrPointerEvent) { + val now = SystemClock.uptimeMillis() + when (event) { + is XrPointerEvent.Down -> { + if (event.hand in touches) return + touches[event.hand] = event.x to event.y + if (touches.size == 1) { + endHover(now) + downTime = now + target = rootAt(event.x, event.y) + sendTouches(MotionEvent.ACTION_DOWN, now) + } else sendTouches(indexed(MotionEvent.ACTION_POINTER_DOWN, event.hand), now) + } + is XrPointerEvent.Move -> { + if (event.hand !in touches) return + touches[event.hand] = event.x to event.y + sendTouches(MotionEvent.ACTION_MOVE, now) + } + is XrPointerEvent.Up -> { + if (event.hand !in touches) return + touches[event.hand] = event.x to event.y + if (touches.size > 1) { + sendTouches(indexed(MotionEvent.ACTION_POINTER_UP, event.hand), now) + touches -= event.hand + } else { + sendTouches(MotionEvent.ACTION_UP, now) + touches.clear() + target = null + hover(cursor) + } + } + is XrPointerEvent.Cancel -> { + if (event.hand !in touches) return + sendTouches(MotionEvent.ACTION_CANCEL, now) + touches.clear() + target = null + } + is XrPointerEvent.Scroll -> rootAt(event.x, event.y)?.let { + send(it, MotionEvent.ACTION_SCROLL, event.x, event.y, now, generic = true, scroll = event.amount) + } + else -> Unit + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanels.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanels.kt new file mode 100644 index 0000000000..17431f1458 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanels.kt @@ -0,0 +1,611 @@ +package com.droiddeck.launcher.session.xr + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.util.Log +import android.view.Surface +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.KeyboardHide +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.agent.AgentHost +import com.droiddeck.launcher.session.QuestExperimental +import com.droiddeck.launcher.ui.AgentPage +import com.droiddeck.launcher.ui.AgentPet +import com.droiddeck.launcher.ui.DroidDeckTheme +import com.droiddeck.launcher.ui.PcKeyboard +import com.droiddeck.launcher.ui.PetFigure +import com.droiddeck.launcher.ui.TypingRequest +import com.droiddeck.launcher.ui.petStateNow +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import java.lang.ref.WeakReference +import java.nio.ByteBuffer +import java.util.concurrent.ConcurrentLinkedQueue +import kotlin.math.PI + +/** The 2D session window, which hands its menu to the immersive view while that is open. */ +internal interface XrMenuHost { + @Composable + fun XrMenuContent() + fun xrSetMenuOpen(open: Boolean) + fun xrMenuBack() + /** A key of DroidDeck's PC keyboard, by Linux key code, to the game. */ + fun xrSendKey(code: Int, down: Boolean) + /** Text from the laser keyboard to the game, as the Android keyboard sends it. */ + fun xrTypeText(text: String) + fun xrTapKey(keyCode: Int) + /** The immersive view opened or closed; Steam's screen, which SteamVR mirrors as its Steam window, sizes for it. */ + fun xrImmersiveChanged(active: Boolean) +} + +/** What the immersive view's native loop offers: surface-backed layers it composites in front of the game. */ +internal interface XrLayerSource { + val context: Context + fun createLayer(width: Int, height: Int): Int + fun layerSurface(id: Int): Surface? + fun destroyLayer(id: Int) + fun setOrbImage(image: android.graphics.Bitmap) + fun leave() +} + +/** + * DroidDeck's own windows inside the immersive Quest view: the session menu, opened by holding the + * controllers together, and the agent pet with its chat. Quest only. [frame] runs on the XR thread + * each frame; the rest runs on the main thread. + */ +internal object XrPanels { + private const val TAG = "XrPanels" + private const val OPEN_MS = 350f + private const val CLOSE_MS = 250f + private const val BURST_MS = 400f + + /** The immersive view is up, so the menu and pet belong in it. Always false off Quest. */ + @Volatile + var immersiveActive = false + + /** Counts attachments, so work posted from one immersive view is dropped once a later one, or none, is up. */ + @Volatile + private var attachment = 0 + private set + + private val main = Handler(Looper.getMainLooper()) + + /** Whether the headset shows the session; panels draw into their layers only then. */ + @Volatile + private var drawing = false + private val lock = Any() + private val ops = ConcurrentLinkedQueue<() -> Unit>() + private var source: XrLayerSource? = null + private var host: XrHost? = null + private var menuHost: WeakReference? = null + private var scope: CoroutineScope? = null + + private class Panel(val state: XrPanelState, val content: @Composable (State>>) -> Unit) { + val cursorState = mutableStateOf>>(emptyList()) + var layerId = -1 + var window: XrPanelWindow? = null + var openedMs = 0L + var closingMs = 0L + var resizing = false + var cursor: List> = emptyList() + } + + private val panels = mutableListOf() + private val gesture = XrGesture() + private val interaction = XrInteraction() + private var lastFrameMs = 0L + private var orbImageSent = false + private var lastHead = Pose() + private var burstMs = 0L + private var burstAt = Vec3.ZERO + private var lastTick = 0 + private var menuFrom: Vec3? = null + private val typing = mutableStateOf(null) + /** The keyboard was opened for the game, from the session menu; a panel's text field takes it over while it types. */ + private val gameKeyboard = mutableStateOf(false) + private val pcKeyboard = mutableStateOf(false) + + fun gateOpen(model: String, device: String, manufacturer: String, immersive: Boolean) = + immersive && QuestExperimental.supported(model, device, manufacturer) + + fun setMenuHost(menu: XrMenuHost?) { + menuHost = menu?.let { WeakReference(it) } + if (immersiveActive) menu?.xrImmersiveChanged(true) + } + + fun clearMenuHost(menu: XrMenuHost) { + if (menuHost?.get() === menu) menuHost = null + } + + /** Main thread: the immersive view handed over its buffers. */ + fun attach(layers: XrLayerSource, state: ByteBuffer, control: ByteBuffer) { + if (!QuestExperimental.isSupported()) return + synchronized(lock) { + source = layers + host = XrHost(state, control) + orbImageSent = false + } + attachment++ + immersiveActive = true + menuHost?.get()?.xrImmersiveChanged(true) + scope?.cancel() + scope = MainScope().also { scope -> + scope.launch { + snapshotFlow { com.droiddeck.launcher.agent.AgentGuest.focusRevision }.collect { + menuHost?.get()?.xrImmersiveChanged(true) + } + } + scope.launch { + snapshotFlow { AgentPet.enabled && AgentHost.installed }.collect { on -> + if (on) { if (!shown(XrPanelKind.PET_CHAT)) open(XrPanelKind.PET_HEAD) } + else { close(XrPanelKind.PET_HEAD); close(XrPanelKind.PET_CHAT) } + } + } + } + } + + /** + * XR thread, as the session becomes visible or stops being so. OpenXR allows writing into a surface + * swapchain only while the session is visible or focused, and requires the writes to have stopped + * before xrEndSession, so this returns once the panels have stopped or started drawing. + */ + fun setDrawing(visible: Boolean) { + val done = java.util.concurrent.CountDownLatch(1) + val apply = Runnable { + try { + drawing = visible + synchronized(lock) { panels.mapNotNull { it.window } }.forEach { it.pause(!visible) } + } finally { + done.countDown() + } + } + if (Looper.myLooper() == Looper.getMainLooper()) apply.run() + else if (main.post(apply) && !done.await(1, java.util.concurrent.TimeUnit.SECONDS)) + Log.w(TAG, "panels did not ${if (visible) "start" else "stop"} drawing within a second") + } + + /** Main thread: the immersive view is going; every panel goes with it. */ + fun detach() { + if (!immersiveActive) return + immersiveActive = false + scope?.cancel() + scope = null + val windows = synchronized(lock) { + source = null + host = null + ops.clear() + interaction.reset() + panels.mapNotNull { it.window }.also { panels.clear() } + } + windows.forEach { it.release() } + typing.value = null + gameKeyboard.value = false + gesture.reset(release = false) + menuHost?.get()?.xrSetMenuOpen(false) + menuHost?.get()?.xrImmersiveChanged(false) + } + + /** Main thread, from the session window's menu state. */ + fun showMenu(): Boolean { + if (!immersiveActive) return false + open(XrPanelKind.MENU, menuFrom) + menuFrom = null + return true + } + + fun hideMenu() = close(XrPanelKind.MENU) + + /** Main thread: closes the immersive view, as a stop chosen in its menu asks. */ + fun leaveImmersive() { + synchronized(lock) { source }?.leave() + } + + /** Main thread: a text field in a panel wants typing, so the laser keyboard opens. */ + fun startTyping(request: TypingRequest) { + if (!immersiveActive) return + typing.value = request + open(XrPanelKind.KEYBOARD) + } + + fun stopTyping(request: TypingRequest) { + if (typing.value !== request) return + typing.value = null + if (!gameKeyboard.value) close(XrPanelKind.KEYBOARD) + } + + /** + * Main thread: the session menu's keyboards. [pc] picks DroidDeck's PC keyboard over the Android-style one; + * asking again for the one already open closes it. False off the immersive view, where the 2D keyboards stay. + */ + fun toggleGameKeyboard(pc: Boolean): Boolean { + if (!immersiveActive) return false + if (gameKeyboard.value && pcKeyboard.value == pc && shown(XrPanelKind.KEYBOARD)) hideKeyboard() + else showGameKeyboard(pc) + return true + } + + fun showGameKeyboard(pc: Boolean): Boolean { + if (!immersiveActive) return false + gameKeyboard.value = true + pcKeyboard.value = pc + open(XrPanelKind.KEYBOARD) + return true + } + + private fun hideKeyboard() { + typing.value = null + gameKeyboard.value = false + close(XrPanelKind.KEYBOARD) + } + + private fun shown(kind: XrPanelKind) = synchronized(lock) { panels.any { it.state.kind == kind && it.closingMs == 0L } } + + private fun open(kind: XrPanelKind, from: Vec3? = null) { + ops += { create(kind, from) } + } + + private fun close(kind: XrPanelKind) { + ops += { + panels.filter { it.state.kind == kind && it.closingMs == 0L }.forEach { panel -> + panel.closingMs = SystemClock.uptimeMillis() + val out = XrInteractionOut() + interaction.release(panel.state, out) + dispatch(out) + } + } + } + + /** XR thread. */ + private fun create(kind: XrPanelKind, from: Vec3?) { + val layers = source ?: return + panels.firstOrNull { it.state.kind == kind }?.let { existing -> + if (existing.closingMs != 0L) { + existing.closingMs = 0L + val elapsed = 1f - Math.cbrt((1.0 - existing.state.scale).coerceIn(0.0, 1.0)).toFloat() + existing.openedMs = SystemClock.uptimeMillis() - (elapsed * OPEN_MS).toLong() + } + return + } + val placed = XrPlacement.load(layers.context, kind, lastHead) + val state = XrPanelState(kind, placed.pose, placed.width, placed.height) + state.scale = 0f + state.animationFrom = from ?: placed.pose.position + val id = layers.createLayer(state.pixelWidth, state.pixelHeight) + val surface = if (id >= 0) layers.layerSurface(id) else null + if (surface == null) { + Log.w(TAG, "no layer for the ${kind.key} panel") + if (id >= 0) layers.destroyLayer(id) + if (kind == XrPanelKind.MENU) main.post { menuHost?.get()?.xrSetMenuOpen(false) } + return + } + val panel = Panel(state, contentFor(kind)) + panel.layerId = id + panel.openedMs = SystemClock.uptimeMillis() + panels += panel + val context = layers.context + main.post { + synchronized(lock) { + if (panel !in panels) return@post + panel.window = runCatching { + XrPanelWindow(context, surface, state.pixelWidth, state.pixelHeight, startPaused = !drawing) { + panel.content(panel.cursorState) + } + }.onFailure { + Log.w(TAG, "could not show the ${kind.key} panel", it) + panels -= panel + ops += { if (source === layers) layers.destroyLayer(id) } + if (kind == XrPanelKind.MENU) menuHost?.get()?.xrSetMenuOpen(false) + }.getOrNull() + } + } + } + + private fun contentFor(kind: XrPanelKind): @Composable (State>>) -> Unit = when (kind) { + XrPanelKind.MENU -> { cursor -> + DroidDeckTheme { + XrPanelChrome(cursor, buttons = emptyList(), resizable = true) { + menuHost?.get()?.XrMenuContent() + } + } + } + XrPanelKind.PET_HEAD -> { _ -> + DroidDeckTheme { Box(Modifier.fillMaxSize()) { PetFigure(petStateNow(), Modifier.fillMaxSize()) } } + } + XrPanelKind.KEYBOARD -> { cursor -> + DroidDeckTheme { + val buttons = listOf( + XrPanelButton(Icons.Outlined.KeyboardHide, stringResource(R.string.pckb_hide), ::hideKeyboard), + XrPanelButton(null, if (pcKeyboard.value) "Android" else "PC") { pcKeyboard.value = !pcKeyboard.value }, + ) + XrPanelChrome(cursor, buttons, resizable = true) { KeyboardContent() } + } + } + XrPanelKind.PET_CHAT -> { cursor -> + DroidDeckTheme { + XrPanelChrome(cursor, listOf(XrPanelButton(XrCollapseIcon, stringResource(R.string.bottom_chat_close), ::collapseChat)), resizable = true) { + AgentPage(Modifier.fillMaxSize().padding(horizontal = 12.dp), visible = true, startTyping = false, hidesPet = false) + } + } + } + } + + /** A panel's text field takes the keyboard while it types; otherwise its keys go to the game. */ + @Composable + private fun KeyboardContent() { + val request = typing.value + val host = menuHost?.get()?.takeIf { gameKeyboard.value } + val target = request?.let(::XrFieldTarget) ?: host?.let(::XrGameTarget) ?: return + if (pcKeyboard.value) { + val pcText = remember(request) { request?.let { XrPcText(XrFieldTarget(it)) } } + PcKeyboard( + sendKey = { code, down -> pcText?.key(code, down) ?: host?.xrSendKey(code, down) }, + onAndroidKeyboard = { pcKeyboard.value = false }, + onClose = ::hideKeyboard, + heightFraction = 1f, + showButtons = false, + hoverFeedback = true, + ) + } else XrKeyboard(target) + } + + private fun collapseChat() { + close(XrPanelKind.PET_CHAT) + open(XrPanelKind.PET_HEAD) + } + + private fun expandChat(from: Vec3) { + close(XrPanelKind.PET_HEAD) + open(XrPanelKind.PET_CHAT, from) + } + + /** XR thread, once per frame, from QuestXrActivity.onXrHostFrame. */ + fun frame() = synchronized(lock) { + val host = host ?: return + val layers = source ?: return + val frame = host.read() + lastHead = frame.head + while (true) (ops.poll() ?: break).invoke() + if (!orbImageSent) { + orbImageSent = true + runCatching { + android.graphics.BitmapFactory.decodeResource(layers.context.resources, R.drawable.logo) + }.getOrNull()?.let { layers.setOrbImage(it); it.recycle() } + } + val now = SystemClock.uptimeMillis() + val dt = if (lastFrameMs == 0L) 0f else ((now - lastFrameMs) / 1000f).coerceIn(0f, 0.1f) + lastFrameMs = now + val control = XrControlOut() + animate(now, layers) + val active = panels.filter { it.closingMs == 0L && it.window != null } + if (frame.focused) { + if (gesture.update(frame.hands[0], frame.hands[1], now)) { + burstMs = now + burstAt = gesture.midpoint + lastTick = 0 + for (hand in 0..1) control.haptics[hand] = XrHaptic(60, 0.9f) + val from = gesture.midpoint + val posted = attachment + main.post { if (immersiveActive && posted == attachment) toggleMenu(from) } + } else if (gesture.phase == XrGesture.Phase.ARMING) { + val step = (gesture.progress * 4).toInt() + if (step > lastTick) for (hand in 0..1) control.haptics[hand] = XrHaptic(18, 0.2f + 0.15f * step) + lastTick = step + } else lastTick = 0 + val out = interaction.update(frame.head, frame.hands, active.map { it.state }, dt) + for (hand in 0..1) { + control.masks[hand] = out.masks[hand] + control.lasers[hand] = out.lasers[hand] + if (out.ticks[hand] && control.haptics[hand] == null) control.haptics[hand] = XrHaptic(12, 0.35f) + } + dispatch(out) + } else { + gesture.reset(release = false) + val out = XrInteractionOut() + interaction.cancel(out) + dispatch(out) + } + control.orb = orb(now) + panels.forEachIndexed { index, panel -> + if (panel.layerId < 0 || panel.window == null) return@forEachIndexed + val state = panel.state + control.layers += XrLayerOut(panel.layerId, state.shownPose, state.width * state.scale, state.height * state.scale, + order = if (state.kind == XrPanelKind.PET_HEAD) 100 else index) + } + host.write(control) + } + + private fun orb(now: Long): XrControlOut.Orb? { + if (gesture.phase == XrGesture.Phase.ARMING) + return XrControlOut.Orb(gesture.midpoint, 0.02f + 0.01f * gesture.progress, gesture.progress, 0f) + val burst = (now - burstMs) / BURST_MS + if (burstMs != 0L && burst < 1f) return XrControlOut.Orb(burstAt, 0.03f, 1f, burst.coerceAtLeast(0.01f)) + return null + } + + private fun animate(now: Long, layers: XrLayerSource) { + val gone = mutableListOf() + for (panel in panels) { + val state = panel.state + if (panel.closingMs != 0L) { + val t = ((now - panel.closingMs) / CLOSE_MS).coerceIn(0f, 1f) + state.scale = minOf(state.scale, 1f - easeOut(t)) + if (state.animationFrom == null) state.animationFrom = state.pose.position + if (t >= 1f) gone += panel + } else if (state.scale < 1f) { + state.scale = easeOut(((now - panel.openedMs) / OPEN_MS).coerceIn(0f, 1f)) + if (state.scale >= 1f) state.animationFrom = null + } + } + for (panel in gone) { + panels -= panel + if (panel.layerId >= 0) layers.destroyLayer(panel.layerId) + val window = panel.window + val context = layers.context + val state = panel.state + val head = lastHead + main.post { + window?.release() + XrPlacement.save(context, state.kind, head, state.pose, state.width, state.height) + } + } + } + + private fun easeOut(t: Float) = 1f - (1f - t) * (1f - t) * (1f - t) + + /** XR thread: hands each panel its input on the main thread and follows up on moves and resizes. */ + private fun dispatch(out: XrInteractionOut) { + val layers = source ?: return + for (panel in panels) { + val cursor = out.cursors[panel.state]?.toList().orEmpty() + if (cursor != panel.cursor) { + panel.cursor = cursor + val target = panel.cursorState + val window = panel.window + main.post { + target.value = cursor + window?.hover(cursor.firstOrNull()) + } + } + } + for (event in out.events) { + val panel = panels.firstOrNull { it.state === event.panel } ?: continue + when (event) { + is XrPointerEvent.Back -> main.post { back(panel.state.kind) } + is XrPointerEvent.Click -> { + val from = panel.state.pose.position + main.post { expandChat(from) } + } + is XrPointerEvent.Resized -> { + savePlacement(panel, layers) + resize(panel, layers) + } + is XrPointerEvent.Moved -> savePlacement(panel, layers) + else -> { + val window = panel.window + main.post { window?.pointer(event) } + } + } + } + } + + /** XR thread: the place a move or resize ended at, read together now and saved on the main thread. */ + private fun savePlacement(panel: Panel, layers: XrLayerSource) { + val state = panel.state + val kind = state.kind + val head = lastHead + val pose = state.pose + val width = state.width + val height = state.height + val context = layers.context + main.post { XrPlacement.save(context, kind, head, pose, width, height) } + } + + /** XR thread: gives a resized panel a surface of its new size once its content has moved over to it. */ + private fun resize(panel: Panel, layers: XrLayerSource) { + val state = panel.state + val width = XrUnits.pixels(state.width) + val height = XrUnits.pixels(state.height) + if (width == state.pixelWidth && height == state.pixelHeight) return + val id = layers.createLayer(width, height) + val surface = if (id >= 0) layers.layerSurface(id) else null + if (surface == null) { + if (id >= 0) layers.destroyLayer(id) + return + } + val window = panel.window + main.post { + window?.resize(surface, width, height) + ops += { + if (panel in panels) { + val old = panel.layerId + panel.layerId = id + state.pixelWidth = width + state.pixelHeight = height + if (old >= 0) layers.destroyLayer(old) + } else if (source === layers) layers.destroyLayer(id) + } + } + } + + /** Main thread. */ + private fun toggleMenu(from: Vec3) { + val menu = menuHost?.get() ?: return + if (shown(XrPanelKind.MENU)) menu.xrSetMenuOpen(false) + else { + menuFrom = from + menu.xrSetMenuOpen(true) + } + } + + /** Main thread: B on a panel goes back a step, as Back does in the 2D window. */ + private fun back(kind: XrPanelKind) { + when (kind) { + XrPanelKind.MENU -> menuHost?.get()?.xrMenuBack() + XrPanelKind.PET_CHAT -> collapseChat() + XrPanelKind.PET_HEAD -> Unit + XrPanelKind.KEYBOARD -> hideKeyboard() + } + } +} + +/** Where each panel kind was left, relative to where the user faced, so it comes back there. */ +internal object XrPlacement { + class Placed(val pose: Pose, val width: Float, val height: Float) + + private class Default(val yaw: Float, val distance: Float, val dy: Float, val width: Float, val height: Float) + + private val defaults = mapOf( + XrPanelKind.MENU to Default(0f, 0.95f, -0.12f, 0.9f, 0.6f), + XrPanelKind.PET_CHAT to Default(0.6f, 0.95f, -0.12f, 0.6f, 0.7f), + XrPanelKind.PET_HEAD to Default(0.7f, 0.75f, -0.45f, 0.12f, 0.12f), + XrPanelKind.KEYBOARD to Default(0f, 0.5f, -0.5f, 0.8f, 0.36f), + ) + + private fun prefs(context: Context) = context.getSharedPreferences("quest_xr_panels", Context.MODE_PRIVATE) + + fun place(kind: XrPanelKind, head: Pose, yaw: Float, distance: Float, dy: Float): Pose { + val angle = yawOf(head.forward) + yaw + val direction = Quat.yaw(angle).rotate(Vec3.FORWARD) + val position = head.position + direction * distance + Vec3(0f, dy, 0f) + return Pose(kind.orient(position, head.position), position) + } + + fun relative(head: Pose, position: Vec3): Triple { + val offset = position - head.position + val distance = Vec3(offset.x, 0f, offset.z).length + var yaw = yawOf(offset) - yawOf(head.forward) + while (yaw > PI) yaw -= (2 * PI).toFloat() + while (yaw < -PI) yaw += (2 * PI).toFloat() + return Triple(yaw, distance, offset.y) + } + + fun load(context: Context, kind: XrPanelKind, head: Pose): Placed { + val fallback = defaults.getValue(kind) + val saved = prefs(context).getString(kind.key, null)?.split(',')?.mapNotNull { it.toFloatOrNull() } + val values = saved?.takeIf { it.size == 5 } ?: listOf(fallback.yaw, fallback.distance, fallback.dy, fallback.width, fallback.height) + val distance = values[1].coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE) + val width = if (kind.resizable) values[3].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.width + val height = if (kind.resizable) values[4].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.height + return Placed(place(kind, head, values[0], distance, values[2].coerceIn(-1.5f, 1.5f)), width, height) + } + + fun save(context: Context, kind: XrPanelKind, head: Pose, pose: Pose, width: Float, height: Float) { + val (yaw, distance, dy) = relative(head, pose.position) + prefs(context).edit().putString(kind.key, listOf(yaw, distance, dy, width, height).joinToString(",")).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrSteamScreen.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrSteamScreen.kt new file mode 100644 index 0000000000..d797f5be9b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrSteamScreen.kt @@ -0,0 +1,16 @@ +package com.droiddeck.launcher.session.xr + +/** Whether the guest's focus report shows Steam's own screen, with no game holding a window. */ +internal object XrSteamScreen { + /** Steam's own UI and SteamVR, which have windows of their own but are not games. */ + private val STEAM_APPS = setOf(769L, 250820L) + + /** + * Gamescope lists Steam itself while its screen is up, so a report naming no app at all, as the guest + * writes when it could not collect focus or gamescope has not published it, says nothing. + */ + fun shown(focusedApp: Long?, focusableApps: List?): Boolean { + val apps = (listOfNotNull(focusedApp) + focusableApps.orEmpty()).filter { it > 0 } + return apps.isNotEmpty() && apps.all { it in STEAM_APPS } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index 52a44f34cc..8c0d4198f1 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -121,6 +121,8 @@ object StoresState { var unfinished by mutableStateOf>(emptyList()) internal set + var steamPicking by mutableStateOf(null) + fun isUnfinished(item: CatalogItem): Boolean = unfinished.any { it.store == item.store && (it.id == item.id || (it.id == null && it.folder.name == StoreInstallRoot.folderName(item.title, item.id))) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt b/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt index b44a274c50..6077ebe327 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt @@ -14,9 +14,14 @@ internal object WebCookies { } } + fun scopes(url: String, paths: List): List { + val segments = runCatching { java.net.URI(url).path }.getOrNull().orEmpty().split('/').filter { it.isNotEmpty() } + return (paths + segments.indices.map { i -> "/" + segments.take(i + 1).joinToString("/") }).distinct() + } + fun expire(urls: List, domain: String, paths: List, done: (Int) -> Unit) { val cookies = CookieManager.getInstance() - val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, paths, Uri.parse(url).host).map { url to it } } + val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, scopes(url, paths), Uri.parse(url).host).map { url to it } } if (lines.isEmpty()) { done(0) return diff --git a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt index 426d3616a9..6ee2f1b16d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetStore.kt @@ -7,6 +7,7 @@ import com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.runtime.BattleNet import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.GameStorage import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.InstalledStoreGame import com.droiddeck.launcher.stores.Store @@ -130,13 +131,13 @@ object BattleNetClient { StoresState.post { opener?.invoke(args) } } - fun library(context: Context, root: File = preferred(context)): List = - AddedGames.guestPath(context, StoreInstallRoot.storeDir(root, Store.BATTLENET))?.let { listOf("--library", it) }.orEmpty() + fun library(context: Context, root: File? = preferred(context)): List = + root?.let { AddedGames.guestPath(context, StoreInstallRoot.storeDir(it, Store.BATTLENET)) }?.let { listOf("--library", it) }.orEmpty() - internal fun preferred(context: Context): File { + internal fun preferred(context: Context): File? { val second = StoreInstallRoot.libraryRoot(context)?.absolutePath return StoreInstallRoot.targets(context).firstOrNull { it.root.absolutePath == second && (it.root.isDirectory || it.root.mkdirs()) }?.root - ?: StoreInstallRoot.internalRoot(context) + ?: StoreInstallRoot.internalRoot(context).takeIf { second == null && !GameStorage.disconnected(context) } } fun installGame(context: Context, uid: String, root: File) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt index bd8d5c1212..3da83576bb 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt @@ -44,7 +44,7 @@ object EaBackend : StoreBackend { signOuts.incrementAndGet() StoresState.post { StoresState.shelves.remove(store) } EaUpdates.available.clear() - runCatching { WebCookies.expire(EaLogin.SIGN_IN_URLS, ".ea.com", listOf("/")) {} } + EaLogin.forget {} } override fun syncLibrary(context: Context, force: Boolean) { @@ -100,9 +100,7 @@ internal class EaLogin(private val pending: EaAuth.Pending, override val userAge override fun isRedirect(url: String): Boolean = url.startsWith("qrc:", ignoreCase = true) - override fun forgetSignIn(done: () -> Unit) { - runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() } - } + override fun forgetSignIn(done: () -> Unit) = forget(done) override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? { val code = EaAuth.redirectValue(url, "code") ?: return activity.getString(R.string.stores_login_error_verification) @@ -116,7 +114,11 @@ internal class EaLogin(private val pending: EaAuth.Pending, override val userAge } companion object { - val SIGN_IN_URLS = listOf("https://accounts.ea.com", "https://signin.ea.com", "https://www.ea.com") + val SIGN_IN_URLS = listOf(EaAuth.AUTH_URL, "https://signin.ea.com/p/juno/login", "https://www.ea.com") + + fun forget(done: () -> Unit) { + runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() } + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLsx.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLsx.kt index f9e6b286a0..35e9bdb343 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLsx.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaLsx.kt @@ -67,7 +67,7 @@ object EaLsx { } @Volatile var game: Game? = null - @Volatile private var account: Account? = null + @Volatile internal var account: Account? = null /** The one session of the current launch that may act for the account. */ /** Bumped whenever the launch changes; a connection accepted under an older one is not admitted. */ @Volatile internal var generation = 0 @@ -333,10 +333,11 @@ object EaLsx { private fun now() = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")) - private fun answer(session: Session, m: Message): String? { + internal fun answer(session: Session, m: Message): String? { val g = game val who = account val person = who?.takeIf { session.trusted } + val profile = who?.takeIf { session.trusted || session.claimed } val locale = g?.locale ?: "en_US" return when (m.name) { "ChallengeResponse" -> { @@ -355,15 +356,16 @@ object EaLsx { "GetConfig" -> tag("GetConfigResponse", body = SERVICES.joinToString("") { tag("Service", "Name" to it.first, "Facility" to it.second) }) "GetProfile" -> tag( "GetProfileResponse", - "Persona" to person?.persona.orEmpty(), "SubscriberLevel" to 0, "CommerceCurrency" to "USD", "IsTrialSubscriber" to false, - "Country" to "US", "UserId" to person?.userId.orEmpty(), "GeoCountry" to "US", "AvatarId" to "", "IsSubscriber" to false, - "IsSteamSubscriber" to false, "PersonaId" to person?.personaId.orEmpty(), "IsUnderAge" to false, "UserIndex" to 0, + "Persona" to profile?.persona.orEmpty(), "SubscriberLevel" to 0, "CommerceCurrency" to "USD", "IsTrialSubscriber" to false, + "Country" to "US", "UserId" to profile?.userId.orEmpty(), "GeoCountry" to "US", "AvatarId" to "", "IsSubscriber" to false, + "IsSteamSubscriber" to false, "PersonaId" to profile?.personaId.orEmpty(), "IsUnderAge" to false, "UserIndex" to 0, ) "GetSetting" -> tag("GetSettingResponse", "Setting" to when (m.attrs["SettingId"]) { "ENVIRONMENT" -> "production" "LANGUAGE" -> locale else -> "false" }) + "GetSettings" -> tag("GetSettingsResponse", "IsIGOAvailable" to false, "IsIGOEnabled" to false, "IsTelemetryEnabled" to false, "IsManualOffline" to false) "GetGameInfo" -> tag("GetGameInfoResponse", "GameInfo" to when (m.attrs["GameInfoId"]) { "FREETRIAL" -> "false" "LANGUAGES" -> LANGUAGES @@ -403,7 +405,7 @@ object EaLsx { ) }) } - "GetPresence" -> tag("GetPresenceResponse", "UserId" to person?.userId.orEmpty(), "Presence" to "INGAME") + "GetPresence" -> tag("GetPresenceResponse", "UserId" to profile?.userId.orEmpty(), "Presence" to "INGAME") "QueryPresence" -> tag("QueryPresenceResponse", body = "") "QueryFriends" -> tag("QueryFriendsResponse", body = "") "GetBlockList" -> tag("GetBlockListResponse", "Return" to "Success", body = "") diff --git a/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamStore.kt b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamStore.kt index f0ececd00a..bbcd1f425d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/steam/SteamStore.kt @@ -6,9 +6,6 @@ import android.net.Uri import android.util.Log import android.widget.Toast import androidx.annotation.StringRes -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue import com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.session.SessionService @@ -46,8 +43,6 @@ internal object SteamStore { /** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */ private val REFUSALS = setOf(5, 15, 18, 26, 27, 63) - var picking by mutableStateOf(null) - class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) { companion object { fun of(json: JSONObject): Plan? { @@ -222,7 +217,7 @@ internal object SteamStore { toast(context, R.string.steam_store_close_steam) return } - picking = item + StoresState.steamPicking = item } fun install(context: Context, item: CatalogItem, target: SteamClient.Target) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt index 7afcaeb321..405b0b955d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt @@ -8,6 +8,9 @@ import org.json.JSONObject import java.time.Instant internal object XboxCatalog { + /** Package identity prefix of Microsoft's original Xbox releases for PC. */ + internal const val BACK_COMPAT_IDENTITY = "Xbox360BackwardCompatibil" + private val productId = Regex("[A-Z0-9]{12}") private val plans = setOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD") private val pcPlans = mapOf( @@ -148,6 +151,13 @@ internal object XboxCatalog { .flatMap { objects(it.optJSONArray("Packages")) } val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } } val installable = pc.any { installableFormat(it.optString("PackageFormat")) } + // An original Xbox game: its PC package is only Microsoft's emulator and an + // index; the game data comes from the console package, so that is its size. + val backCompat = pc.any { it.optString("PackageFamilyName").startsWith(BACK_COMPAT_IDENTITY, ignoreCase = true) } + val console = packages.filter { pkg -> + pkg.optString("PackageFormat").equals("XVC", true) || + objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Xbox" } + } // The installer needs the format, not just the fact that one exists: a // legacy container takes a different subcommand from a streamed package. val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty() @@ -172,7 +182,8 @@ internal object XboxCatalog { storeUrl = "https://www.xbox.com/games/store/$id", publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"), description = localized.optString("ProductDescription"), - sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L, + sizeBytes = if (!installable) 0L else (if (backCompat) console.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } else null) + ?.takeIf { it > 0 } ?: pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L, extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), "cloud" to flag(streams), "format" to format), ) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt index b4f9ab9cb3..c1ddd7d704 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt @@ -106,7 +106,7 @@ private fun PanelContent( onChange(settings.copy(frameGen = it)) } Text("Native engine (experimental): Google's WebRTC and DroidDeck's own compositor, so DroidDeck frame generation " + - "(DDFG) or LSFG can add frames. LSFG uses the Lossless.dll DroidDeck already uses for games. Screen effects " + + "(DDFG) or LSFG can add frames. LSFG requires Lossless Scaling installed through Steam. Screen effects " + "apply to the web engine.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 8.dp, bottom = 6.dp)) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt index 1f6cb7851d..1c88e48655 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt @@ -80,6 +80,10 @@ internal object XboxManifest { dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty()) } + /** Microsoft's original Xbox releases for PC, which run its emulator. */ + fun backCompat(folder: File): Boolean = + runCatching { read(folder).name.startsWith(XboxCatalog.BACK_COMPAT_IDENTITY, ignoreCase = true) }.getOrDefault(false) + /** * A full trust package starts its executable directly. Anything else is activated * through the Windows app model, which this runtime has no host for, so starting diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt index b4d12ba922..346a65d9b4 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt @@ -623,11 +623,11 @@ class XboxNativePlayerActivity : ComponentActivity() { XboxMenuEntry((if (current.frameGen == mode) "✓ " else "") + fgName(mode), when (mode) { XboxNativeVideo.FG_DDFG -> "DroidDeck's own frame generation (DDFG); doubles the shown frame rate" XboxNativeVideo.FG_LSFG, XboxNativeVideo.FG_LSFG3, XboxNativeVideo.FG_LSFG4 -> - "Lossless Scaling frame generation (the Lossless.dll DroidDeck uses for games); the frame-rate target caps the output" + "Lossless Scaling frame generation from the Steam installation; the frame-rate target caps the output" else -> "Show the stream's own frames only" }, choices[i]) { current = current.copy(frameGen = mode); setFrameGen(mode) } } - if (!lsfg) androidx.compose.material3.Text("LSFG appears here once DroidDeck has the Lossless.dll (frame generation settings).", + if (!lsfg) androidx.compose.material3.Text("LSFG appears here once Lossless Scaling is installed through Steam.", style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant, modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) if (current.zeroCopy) androidx.compose.material3.Text( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt index ff282615f5..1df2b17315 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt @@ -78,7 +78,7 @@ internal fun AgentEntry( is Entry.Said -> { val reply = remember(entry.text) { choices(entry.text) } Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - if (reply.text.isNotBlank()) SelectionContainer { AgentMarkdown(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) } + if (reply.text.isNotBlank()) SelectionContainer { AgentReply(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) } if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent) } } @@ -377,10 +377,11 @@ private fun CodeBox(label: String, text: String, color: Color) { internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) { val context = LocalContext.current val pal = LocalPalette.current + var viewing by remember(path) { mutableStateOf(false) } Box { if (AgentAttachments.isImage(path)) AsyncImage( model = AgentAttachments.host(context, path), contentDescription = path.substringAfterLast('/'), contentScale = ContentScale.Crop, - modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant), + modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant).clickable { viewing = true }, ) else Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.heightIn(min = 40.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 10.dp, vertical = 8.dp), @@ -396,4 +397,5 @@ internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) { Icon(Icons.Outlined.Close, stringResource(R.string.agent_remove_attachment), tint = pal.onSurfaceVariant, modifier = Modifier.size(14.dp)) } } + if (viewing) PictureViewer(AgentAttachments.host(context, path), path.substringAfterLast('/')) { viewing = false } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt index 0d85087f85..49f351a175 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt @@ -37,6 +37,106 @@ import org.commonmark.ext.gfm.tables.TableRow import org.commonmark.node.AbstractVisitor import org.commonmark.node.CustomNode import org.commonmark.node.Node +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import coil.compose.AsyncImage +import com.droiddeck.launcher.runtime.LinuxRuntime +import java.io.File + +/** Part of an agent's reply: Markdown text, or an image the agent named on a line of its own. */ +internal sealed interface ReplyPart { + data class Prose(val text: String) : ReplyPart + data class Picture(val alt: String, val path: String) : ReplyPart +} + +private val PICTURE_LINE = Regex("""^\s*!\[([^\]]*)]\(\s*(?:<(?:file://)?(/[^>]*)>|(?:file://)?(/[^)<>]*?))\s*\)\s*$""") +private val FENCE = Regex("""^ {0,3}(`{3,}|~{3,})(.*)$""") + +/** Splits [text] at lines that hold only an image of a local absolute path, outside code fences. */ +internal fun replyParts(text: String): List { + val parts = mutableListOf() + val prose = StringBuilder() + fun flush() { + if (prose.isNotBlank()) parts += ReplyPart.Prose(prose.toString().trimEnd('\n')) + prose.clear() + } + var fence: String? = null + for (line in text.lines()) { + val marker = FENCE.matchEntire(line) + val picture = if (fence == null) PICTURE_LINE.matchEntire(line) else null + val open = fence + when { + picture != null -> { + flush() + val path = picture.groupValues[2].ifEmpty { picture.groupValues[3] } + parts += ReplyPart.Picture(picture.groupValues[1].trim(), path.trim()) + continue + } + marker == null -> Unit + open == null -> fence = marker.groupValues[1] + marker.groupValues[1].let { it[0] == open[0] && it.length >= open.length } && marker.groupValues[2].isBlank() -> fence = null + } + prose.append(line).append('\n') + } + flush() + return parts +} + +/** + * Where the app reads a file the agent named by its guest path: the app's own folders and shared + * storage are bound at the same paths in the guest, everything else lives in the rootfs. + */ +internal fun agentHostFile(context: Context, guestPath: String): File { + val app = context.applicationContext + val same = listOfNotNull(app.filesDir.path, app.cacheDir.path, LinuxRuntime.sharedStorage(app)?.path) + return if (same.any { guestPath == it || guestPath.startsWith("$it/") }) File(guestPath) + else File(LinuxRuntime.rootDir(app), guestPath.removePrefix("/")) +} + +/** An agent's reply, with the images it names shown in place. */ +@Composable +internal fun AgentReply(text: String, modifier: Modifier) { + val parts = remember(text) { replyParts(text) } + if (parts.size == 1 && parts[0] is ReplyPart.Prose) { + AgentMarkdown(text, modifier) + return + } + Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) { + parts.forEach { part -> + when (part) { + is ReplyPart.Prose -> AgentMarkdown(part.text, Modifier) + is ReplyPart.Picture -> AgentPicture(part) + } + } + } +} + +@Composable +private fun AgentPicture(picture: ReplyPart.Picture) { + val context = LocalContext.current + val file = remember(picture.path) { agentHostFile(context, picture.path) } + var viewing by remember(picture.path) { mutableStateOf(false) } + if (!file.isFile) { + Text(stringResource(R.string.agent_image_missing, picture.alt.ifBlank { picture.path }), color = MaterialTheme.colorScheme.onSurfaceVariant) + return + } + AsyncImage( + model = file, contentDescription = picture.alt.ifBlank { file.name }, contentScale = ContentScale.Fit, + modifier = Modifier.widthIn(max = 560.dp).heightIn(max = 420.dp).clip(Shape12).clickable { viewing = true }, + ) + if (viewing) PictureViewer(file, picture.alt.ifBlank { file.name }) { viewing = false } +} @Composable internal fun AgentMarkdown(text: String, modifier: Modifier) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index 429db30258..439422fee7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -532,7 +532,7 @@ private fun AgentLive() { val pal = LocalPalette.current Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { if (AgentHost.liveThinking.isNotBlank()) AgentThought(AgentHost.liveThinking, live = true) - if (AgentHost.live.isNotBlank()) AgentMarkdown(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) + if (AgentHost.live.isNotBlank()) AgentReply(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) val running = AgentHost.running() Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(4.dp)) { CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp, color = pal.primary) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt index 8adadcab9c..2ded416719 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt @@ -88,7 +88,14 @@ internal object AgentPet { private set /** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */ private var floatFailed by mutableStateOf(false) - val floating get() = enabled && allowed && !floatFailed + val floating get() = enabled && allowed && !floatFailed && usesOverlayWindows(onQuest) + /** Quest's shell turns overlay windows into system panels that take input from the VR view. */ + private val onQuest = com.droiddeck.launcher.session.QuestExperimental.isSupported() + + internal fun usesOverlayWindows(quest: Boolean) = !quest + + /** On Quest the chat opens as its own panel window, which Horizon moves, resizes and closes. */ + internal fun chatInOwnWindow(quest: Boolean = onQuest) = quest /** How to close the chat open inside each DroidDeck window that has one. */ private val closeInWindow = java.util.WeakHashMap Unit>() @@ -118,7 +125,7 @@ internal object AgentPet { AgentHost.prefs(context).edit().putBoolean(KEY, on).apply() if (on) { allowed = PetWindows.allowed(context) - if (!allowed) requestFloating(context) + if (!allowed && usesOverlayWindows(onQuest)) requestFloating(context) } } @@ -251,9 +258,12 @@ private fun PetLayer(host: AgentPetHost) { val density = LocalDensity.current val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open) val openChat = { - motion.dock() - chatShown = true - chatOpen = true + if (AgentPet.chatInOwnWindow()) com.droiddeck.launcher.agent.AgentChatActivity.open(context) + else { + motion.dock() + chatShown = true + chatOpen = true + } } val closeChat = { chatOpen = false diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt index 72e5d0b635..e2381ca2a4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt @@ -21,6 +21,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -495,7 +496,13 @@ internal class PetWindows(private val context: Context) { * under it. Its contents are built while it is closed, so opening only animates. */ @Composable -internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onClosed: () -> Unit) { +internal fun PetChat( + open: Boolean, motion: PetMotion, onClose: () -> Unit, + page: @Composable ColumnScope.(AgentMenuSlot) -> Unit = { slot -> + AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = slot) + }, + onClosed: () -> Unit, +) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val density = androidx.compose.ui.platform.LocalDensity.current @@ -552,14 +559,16 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl alpha = fade.value } .clip(Shape16).background(colors.background).border(1.dp, pal.line, Shape16) - .clickable(remember { MutableInteractionSource() }, null, enabled = open) {} + // Never disabled: a disabled clickable leaves the focus tree, and the one it puts back on reopening + // sits unfocused above the still-focused editor, where key events then find no focus target. + .clickable(remember { MutableInteractionSource() }, null) {} .padding(start = 12.dp, end = 12.dp, top = 6.dp), ) { Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) { Box(Modifier.weight(1f)) { menuSlot.content?.invoke() } HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose) } - AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = menuSlot) + page(menuSlot) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPictureViewer.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPictureViewer.kt new file mode 100644 index 0000000000..3dea67d609 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPictureViewer.kt @@ -0,0 +1,113 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.calculatePan +import androidx.compose.foundation.gestures.calculateZoom +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Close +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.positionChanged +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupProperties +import coil.compose.AsyncImage +import com.droiddeck.launcher.R +import kotlin.math.abs + +private const val MAX_ZOOM = 5f +private const val TAP_ZOOM = 2.5f + +/** + * A picture over the whole window: pinch or double-tap to zoom, drag to pan. A tap, a swipe down, + * Back or B close it. It is a popup, not a dialog, because the pet's chat lives in an overlay window, + * which has no activity token to show a dialog with. + */ +@Composable +internal fun PictureViewer(model: Any, description: String?, onDismiss: () -> Unit) { + Popup( + alignment = Alignment.Center, onDismissRequest = onDismiss, + properties = PopupProperties(focusable = true, dismissOnBackPress = true, dismissOnClickOutside = false), + ) { + var size by remember { mutableStateOf(IntSize.Zero) } + var scale by remember { mutableFloatStateOf(1f) } + var offset by remember { mutableStateOf(Offset.Zero) } + fun clamp(o: Offset, s: Float): Offset { + val x = size.width * (s - 1f) / 2f + val y = size.height * (s - 1f) / 2f + return Offset(o.x.coerceIn(-x, x), o.y.coerceIn(-y, y)) + } + val fade = if (scale == 1f && size.height > 0) (1f - abs(offset.y) / size.height * 2f).coerceIn(0.3f, 1f) else 1f + Box( + Modifier.fillMaxSize().onSizeChanged { size = it }.background(Color.Black.copy(alpha = 0.94f * fade)) + .pointerInput(Unit) { + detectTapGestures( + onDoubleTap = { at -> + if (scale > 1f) { scale = 1f; offset = Offset.Zero } else { + scale = TAP_ZOOM + offset = clamp((Offset(size.width / 2f, size.height / 2f) - at) * (TAP_ZOOM - 1f), TAP_ZOOM) + } + }, + onTap = { if (scale == 1f) onDismiss() }, + ) + } + .pointerInput(Unit) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false) + do { + val event = awaitPointerEvent() + val zoom = event.calculateZoom() + val pan = event.calculatePan() + if (zoom != 1f || pan != Offset.Zero) { + val next = (scale * zoom).coerceIn(1f, MAX_ZOOM) + offset = if (next > 1f) clamp(offset * (next / scale) + pan, next) else Offset(0f, offset.y + pan.y) + scale = next + event.changes.forEach { if (it.positionChanged()) it.consume() } + } + } while (event.changes.any { it.pressed }) + if (scale == 1f) { + if (abs(offset.y) > size.height / 6f) onDismiss() else offset = Offset.Zero + } + } + }, + ) { + AsyncImage( + model = model, contentDescription = description, contentScale = ContentScale.Fit, + modifier = Modifier.fillMaxSize().graphicsLayer { + scaleX = scale; scaleY = scale; translationX = offset.x; translationY = offset.y + }, + ) + IconButton( + onClick = onDismiss, + modifier = Modifier.align(Alignment.TopEnd).padding(12.dp).size(44.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.5f)), + ) { + Icon(Icons.Outlined.Close, stringResource(R.string.common_close), tint = Color.White) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt index 25b01904d8..615d59cb61 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt @@ -46,6 +46,7 @@ import androidx.compose.ui.platform.testTag import com.droiddeck.launcher.agent.AgentSetup.Status import com.droiddeck.launcher.agent.AgentSetup.Step import com.droiddeck.launcher.core.WirelessAdbPairingService +import com.droiddeck.launcher.session.QuestExperimental @Composable internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifier, onDone: () -> Unit = {}) { @@ -104,11 +105,16 @@ internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifie var keyOpen by rememberSaveable(harness.id) { mutableStateOf(false) } val (title, hint) = labels(step, harness.name, keyed) val lab = AgentHost.lab?.takeIf { it.prepare && it.running } + val questConnection = step == Step.CONNECTION && status != Status.DONE && QuestExperimental.isSupported() val detail = when { step == Step.PREPARE && lab != null -> stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0))) keyed && status == Status.DONE && AgentSetup.detail[step] == null -> harness.providers.filter { it.id in AgentSetup.keys }.joinToString(" · ") { it.name }.ifEmpty { stringResource(R.string.agent_step_free_models) } + // The Quest hint holds the one-time commands, so it stays under the status until the step passes. + questConnection -> AgentSetup.detail[step]?.let { "$it\n$hint" } ?: hint + // The Quest hint is setup instructions; once connected, the row says what it is for. + step == Step.CONNECTION && QuestExperimental.isSupported() -> AgentSetup.detail[step] ?: stringResource(R.string.agent_step_connection_hint) else -> AgentSetup.detail[step] ?: hint } // Shown while the sign-in is pending, so it is still there after a trip to the browser for the key. @@ -121,6 +127,7 @@ internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifie Status.TODO, Status.FAILED -> CheckState.WARN }, title, detail, divider = index < steps.lastIndex && !showKey, + detailLines = if (questConnection) Int.MAX_VALUE else 2, ) { val blocked = (step in setOf(Step.SIGN_IN, Step.GITHUB, Step.BUILD_TOOLS) && AgentSetup.status[Step.INSTALL] != Status.DONE) || (step == Step.PREPARE && AgentSetup.status[Step.BUILD_TOOLS] != Status.DONE) @@ -258,7 +265,9 @@ internal fun agentStorageWarning(item: AgentStorage.Item) = when (item) { @Composable private fun labels(step: Step, harness: String, keyed: Boolean = false): Pair = when (step) { - Step.CONNECTION -> stringResource(R.string.agent_step_connection) to stringResource(R.string.agent_step_connection_hint) + Step.CONNECTION -> stringResource(R.string.agent_step_connection) to + if (QuestExperimental.isSupported()) stringResource(R.string.agent_step_connection_quest_hint, LocalContext.current.packageName) + else stringResource(R.string.agent_step_connection_hint) Step.INSTALL -> stringResource(R.string.agent_step_install, harness) to stringResource(R.string.agent_step_install_hint) Step.SIGN_IN -> stringResource(R.string.agent_step_sign_in, harness) to stringResource(if (keyed) R.string.agent_step_sign_in_key_hint else R.string.agent_step_sign_in_hint) Step.GITHUB -> stringResource(R.string.agent_step_github) to stringResource(R.string.agent_step_github_hint) @@ -267,7 +276,7 @@ private fun labels(step: Step, harness: String, keyed: Boolean = false): Pair R.string.agent_action_pair + Step.CONNECTION -> if (QuestExperimental.isSupported()) R.string.agent_action_allow else R.string.agent_action_pair Step.INSTALL -> R.string.agent_action_install Step.SIGN_IN, Step.GITHUB -> R.string.agent_action_sign_in Step.BUILD_TOOLS -> R.string.agent_action_install @@ -276,6 +285,7 @@ private fun action(step: Step): Int = when (step) { /** The pairing DroidDeck already uses for the phantom process fix; the agent reuses its key. */ private fun pair(context: android.content.Context) { + if (QuestExperimental.isSupported()) return AgentSetup.trustOnDevice(context) if (!WirelessAdbPairingService.notificationsEnabled(context)) { context.startActivity(android.content.Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS) .putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, context.packageName) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt index c9e8362c4d..38359530db 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt @@ -46,7 +46,11 @@ class BottomDesktopPanel( private val status = ComposeView(context).apply { setContent { DroidDeckTheme { BottomDesktopStatus(state.value, ::startAgain) } } } - private val keyboardHost = KeyboardHost(context) { event -> sendKey(event) } + private val keyboardHost = KeyboardHost( + context, + sendKeyEvent = { event -> sendKey(event) }, + sendText = BottomDesktop::sendText, + ) private var directTouch = SessionPrefs.bottomDesktopDirectTouch(context) private val touchMode = mutableStateOf(directTouch) private val trackpad = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), TrackpadInput()).apply { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt index fe66a06396..1524da8b92 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt @@ -338,6 +338,24 @@ internal fun sessionBarModel( internal fun deckPanelTabs(context: Context, selected: DeckPanel, onSelect: (DeckPanel) -> Unit) = BarTabs(DeckPanel.entries.map { context.getString(it.label) }, selected.ordinal) { onSelect(DeckPanel.entries[it]) } +internal fun padKeysView( + context: Context, steam: Boolean, onMenu: () -> Unit, onSteam: () -> Unit, onQam: () -> Unit, +): ComposeView = ComposeView(context).apply { + setContent { DroidDeckTheme { PadKeys(steam, onMenu, onSteam, onQam) } } +} + +@Composable +internal fun PadKeys(steam: Boolean, onMenu: () -> Unit, onSteam: () -> Unit, onQam: () -> Unit) { + Row( + Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), + horizontalArrangement = if (steam) Arrangement.SpaceBetween else Arrangement.Center, + ) { + if (steam) BarActions(null, false, onSteam, null) + BarActions(onMenu, false, null, null) + if (steam) BarActions(null, false, null, onQam) + } +} + internal fun bottomScreenBarView(context: Context, model: () -> BottomBarModel): ComposeView = ComposeView(context).apply { setContent { DroidDeckTheme { BottomScreenBar(model()) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt index d2630fa7b7..76a3c40636 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt @@ -8,11 +8,14 @@ import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.AlignHorizontalCenter import androidx.compose.material.icons.outlined.AlignHorizontalLeft import androidx.compose.material.icons.outlined.AlignHorizontalRight +import androidx.compose.material.icons.outlined.VerticalSplit import androidx.compose.material.icons.outlined.WidthFull import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -72,7 +75,8 @@ internal enum class QamFit(val id: String, @StringRes val label: Int, val icon: FULL("full", R.string.bottom_qam_layout_full, Icons.Outlined.WidthFull, 0), LEFT("left", R.string.bottom_qam_layout_left, Icons.Outlined.AlignHorizontalLeft, -1), CENTER("center", R.string.bottom_qam_layout_center, Icons.Outlined.AlignHorizontalCenter, 0), - RIGHT("right", R.string.bottom_qam_layout_right, Icons.Outlined.AlignHorizontalRight, 1); + RIGHT("right", R.string.bottom_qam_layout_right, Icons.Outlined.AlignHorizontalRight, 1), + SPLIT("split", R.string.bottom_qam_layout_split, Icons.Outlined.VerticalSplit, 0); val next: QamFit get() = entries[(ordinal + 1) % entries.size] @@ -92,6 +96,7 @@ internal enum class QamFit(val id: String, @StringRes val label: Int, val icon: internal object QamLayout { private const val WIDE_CSS = "div.BasicUI { width: 100% !important; } div[class*=\\\"tab_\\\"] { max-width: none !important; }" + private const val PARKED_CSS = " #Footer { display: none !important; }" /** Scale and left edge of the menu in a box; [align] -1, 0 or 1 places a narrower menu left, centred or right. */ fun fit(boxWidth: Float, boxHeight: Float, contentRight: Float, cssHeight: Float, align: Int = 0): Pair { @@ -102,10 +107,13 @@ internal object QamLayout { fun toCss(x: Float, y: Float, scale: Float, left: Float): Pair = (x - left) / scale to y / scale /** Makes the menu follow the panel-shaped view (Steam sizes it once, on open) and lifts each tab's 300 px cap, then measures where the content ends. */ - /** [wide] is false while the menu is shown on the top screen, where it keeps Steam's own layout. */ - fun contentScript(wide: Boolean): String = "(() => { let s = document.getElementById('dd-qam-wide'); " + + /** + * [wide] is false while the menu is shown on the top screen, where it keeps Steam's own layout. [parked] hides the + * button-hint footer Steam draws in a game, which stays an empty black strip while the controller is not on the menu. + */ + fun contentScript(wide: Boolean, parked: Boolean = wide): String = "(() => { let s = document.getElementById('dd-qam-wide'); " + "if (!s) { s = document.createElement('style'); s.id = 'dd-qam-wide'; document.head.appendChild(s); } " + - "const css = '${if (wide) WIDE_CSS else ""}'; " + + "const css = '${(if (wide) WIDE_CSS else "") + (if (parked) PARKED_CSS else "")}'; " + "if (s.textContent !== css) s.textContent = css; if (document.scrollingElement.scrollLeft) document.scrollingElement.scrollLeft = 0; " + "const w = innerWidth; let right = 0; for (const e of document.body.querySelectorAll('*')) { " + "const r = e.getBoundingClientRect(); const tab = /(^| )tab_/.test(String(e.className)); " + @@ -117,17 +125,90 @@ private const val TICK_MS = 1_000L private const val FAST_TICK_MS = 150L private const val MAX_RETRY_MS = 4_000L -/** The last frame shown, so returning to the panel shows the menu at once while the live stream reconnects. */ +/** One of Steam's menu pages streamed to the panel; the last frame is kept so returning to the panel shows it at once. */ +internal class MenuStream { + @Volatile var page: CdpPage? = null + val live = java.util.concurrent.atomic.AtomicBoolean(false) + val image = mutableStateOf(null) + val shape = mutableStateOf(null) + + fun show(frame: ImageBitmap) { + image.value = frame + live.set(true) + } + + /** Connects to [path] and starts its screencast; false when the page cannot be reached. */ + fun connect(port: Int, path: String): Boolean { + page?.close() + page = null + live.set(false) + val p = runCatching { + CdpPage(port, path) { method, params -> + if (method == "Page.screencastFrame") { + page?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId"))) + decodeFrame(params.optString("data"))?.let(::show) + } + } + }.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull() ?: return false + page = p + p.send("Page.enable") + val started = p.call("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85) + .put("maxWidth", 1920).put("maxHeight", 1440)) + if (started == null || started.has("error") || !started.has("result")) { + p.close() + page = null + return false + } + return true + } + + /** Runs [script], which returns the page's [width, height, pixel ratio, content right], and refreshes a still page. */ + fun refresh(script: String) { + val p = page ?: return + // The screencast sends frames only when the menu repaints, so a still menu needs one screenshot. + if (!live.get()) { + p.call("Page.captureScreenshot", JSONObject().put("format", "jpeg").put("quality", 85)) + ?.optJSONObject("result")?.optString("data")?.let(::decodeFrame)?.let(::show) + } + (p.evaluate(script) as? String)?.let { text -> + runCatching { + val a = JSONArray(text) + val layout = FloatArray(4) { a.getDouble(it).toFloat() } + if (!layout.contentEquals(shape.value)) shape.value = layout + } + } + } + + /** Stops the stream and runs [restore] on the page, which outlives this connection. */ + fun stop(restore: String) { + val p = page ?: return + page = null + runCatching { p.send("Page.stopScreencast") } + runCatching { p.evaluate(restore) } + p.close() + } + + fun frame(): QamFrame? { + val img = image.value + val l = shape.value + return if (img != null && l != null && l[0] > 0f) QamFrame(img, l[0], l[1], l[3].coerceIn(l[0] * 0.25f, l[0])) else null + } +} + +/** Steam's main menu beside the quick access menu; Steam's side of the hold keeps it in place and filling its view. */ +internal object MainMenuLayout { + const val CONTENT_SCRIPT = "JSON.stringify([innerWidth, innerHeight, devicePixelRatio, innerWidth])" +} + +/** Panel streams kept across visits to the panel. */ private object QamCache { - @Volatile var image: ImageBitmap? = null - @Volatile var shape: FloatArray? = null + val qam = MenuStream() + val main = MenuStream() } @Composable internal fun SteamQamPanel() { val context = LocalContext.current.applicationContext - var image by remember { mutableStateOf(QamCache.image) } - var shape by remember { mutableStateOf(QamCache.shape) } var failed by remember { mutableStateOf(false) } var slow by remember { mutableStateOf(false) } LaunchedEffect(Unit) { @@ -135,78 +216,67 @@ internal fun SteamQamPanel() { slow = true } val fit = QamFit.current(context) - val holder = remember { arrayOfNulls(1) } + val qam = QamCache.qam + val mainMenu = QamCache.main val owner = remember { SteamQam.newOwner() } val relay = remember { intArrayOf(0) } - val live = remember { java.util.concurrent.atomic.AtomicBoolean(false) } + val mainPath = remember { arrayOfNulls(1) } val aspect = remember { floatArrayOf(0f) } val measure = Modifier.fillMaxSize().onSizeChanged { if (it.height > 0) aspect[0] = it.width.toFloat() / it.height } - val show = { frame: ImageBitmap -> image = frame; QamCache.image = frame; live.set(true) } LaunchedEffect(Unit) { withContext(Dispatchers.IO) { var misses = 0 + // The main menu page backs off on its own, so Quick Access stays available while its neighbour cannot connect. + var mainMisses = 0 + var mainRetryAt = 0L + fun split() = QamFit.current(context) == QamFit.SPLIT // The lease is renewed on its own, so slow discovery or a retry backoff never lets the held menu lapse. val renew = launch { while (isActive) { - if (SessionState.phase == SessionPhase.READY && aspect[0] > 0f) SteamQam.hold(context, aspect[0], owner) + if (SessionState.phase == SessionPhase.READY && aspect[0] > 0f) SteamQam.hold(context, aspect[0], owner, split()) delay(TICK_MS) } } try { while (isActive) { // Holding the menu before Steam's first frame keeps gamescope from presenting it. - if (SessionState.phase != SessionPhase.READY) { + if (SessionState.phase != SessionPhase.READY || aspect[0] == 0f) { delay(FAST_TICK_MS) continue } - if (aspect[0] == 0f) { - delay(FAST_TICK_MS) - continue - } - val held = SteamQam.hold(context, aspect[0], owner) + val split = split() + val held = SteamQam.hold(context, aspect[0], owner, split) ensureActive() var reached = held != null if (held?.open == SteamQam.QUICK_ACCESS) { - var page = holder[0] - if (page == null || page.closed) { - page?.close() - live.set(false) - page = SteamQam.target(context)?.let { t -> + if (qam.page?.closed != false) { + val t = SteamQam.target(context) + if (t != null) { if (relay[0] != 0 && relay[0] != t.port) SteamQam.stopRelay(context, relay[0]) relay[0] = t.port - runCatching { - CdpPage(t.port, t.path) { method, params -> - if (method == "Page.screencastFrame") { - holder[0]?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId"))) - decodeFrame(params.optString("data"))?.let(show) - } - } - }.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull() + mainPath[0] = t.mainPath + qam.connect(t.port, t.path) + mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT) } - holder[0] = page ensureActive() - page?.send("Page.enable") - val started = page?.call("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85) - .put("maxWidth", 1920).put("maxHeight", 1440)) - if (page != null && (started == null || started.has("error") || !started.has("result"))) { - page.close() - page = null - holder[0] = null - } } - // The screencast sends frames only when the menu repaints, so a still menu needs one screenshot. - if (!live.get()) { - page?.call("Page.captureScreenshot", JSONObject().put("format", "jpeg").put("quality", 85)) - ?.optJSONObject("result")?.optString("data")?.let(::decodeFrame)?.let(show) - } - reached = page != null - val wide = !held.top && QamFit.current(context) == QamFit.FULL - (page?.evaluate(QamLayout.contentScript(wide)) as? String)?.let { text -> - runCatching { - val a = JSONArray(text) - val layout = floatArrayOf(a.getDouble(0).toFloat(), a.getDouble(1).toFloat(), a.getDouble(2).toFloat(), a.getDouble(3).toFloat()) - if (!layout.contentEquals(shape)) { shape = layout; QamCache.shape = layout } + reached = qam.page?.closed == false + val wide = !held.top && (QamFit.current(context) == QamFit.FULL || split) + qam.refresh(QamLayout.contentScript(wide, parked = !held.top)) + val path = mainPath[0] + if (split && path != null) { + val now = android.os.SystemClock.elapsedRealtime() + if (mainMenu.page?.closed != false && now >= mainRetryAt) { + if (mainMenu.connect(relay[0], path)) { + mainMisses = 0 + } else { + mainMisses++ + mainRetryAt = now + minOf(TICK_MS shl minOf(mainMisses - 1, 2), MAX_RETRY_MS) + } } + mainMenu.refresh(MainMenuLayout.CONTENT_SCRIPT) + } else if (!split) { + mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT) } } failed = !reached @@ -214,7 +284,7 @@ internal fun SteamQamPanel() { misses = if (reached) 0 else misses + 1 val wait = when { !reached -> minOf(TICK_MS shl minOf(misses - 1, 2), MAX_RETRY_MS) - live.get() -> TICK_MS + qam.live.get() && (!split || mainMenu.live.get() || mainMenu.page?.closed != false) -> TICK_MS else -> FAST_TICK_MS } val used = QamFit.current(context) @@ -225,35 +295,46 @@ internal fun SteamQamPanel() { } finally { withContext(NonCancellable) { renew.cancelAndJoin() - val page = holder[0] - holder[0] = null - runCatching { page?.send("Page.stopScreencast") } - // The page outlives this connection, so the widened layout would otherwise stay on the top screen. - runCatching { page?.evaluate(QamLayout.contentScript(wide = false)) } - page?.close() + // The pages outlive these connections, so the widened layouts would otherwise stay on the top screen. + qam.stop(QamLayout.contentScript(wide = false)) + mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT) SteamQam.release(context, relay[0], owner) } } } } - val img = image - val l = shape - val f = remember(img, l) { - if (img != null && l != null && l[0] > 0f) QamFrame(img, l[0], l[1], l[3].coerceIn(l[0] * 0.25f, l[0])) else null - } - if (f == null) { + val qamFrame = qam.frame() + if (qamFrame == null) { Box(measure) { if (slow) PanelNote(stringResource(if (failed) R.string.bottom_qam_unavailable else R.string.achievements_reading)) } return } - BoxWithConstraints(measure.background(f.fill)) { + if (fit != QamFit.SPLIT) { + MenuCanvas(qamFrame, fit.align, measure) { qam.page } + return + } + // Each side is as wide as its menu at the shared scale, so neither is shrunk nor padded with empty space. + val mainFrame = mainMenu.frame() + val mainWidth = mainFrame?.cssWidth ?: SteamQam.MAIN_CSS_WIDTH.toFloat() + Row(measure) { + val left = Modifier.weight(mainWidth).fillMaxHeight() + if (mainFrame != null) MenuCanvas(mainFrame, -1, left) { mainMenu.page } + else Box(left.background(qamFrame.fill)) + MenuCanvas(qamFrame, -1, Modifier.weight(qamFrame.cssWidth).fillMaxHeight()) { qam.page } + } +} + +/** Draws [f] scaled into the box, placed by [align], and forwards touches on it to [page]. */ +@Composable +private fun MenuCanvas(f: QamFrame, align: Int, modifier: Modifier, page: () -> CdpPage?) { + BoxWithConstraints(modifier.background(f.fill)) { val density = LocalDensity.current val boxW = with(density) { maxWidth.toPx() } val boxH = with(density) { maxHeight.toPx() } - val (scale, left) = QamLayout.fit(boxW, boxH, f.contentRight, f.cssHeight, fit.align) + val (scale, left) = QamLayout.fit(boxW, boxH, f.contentRight, f.cssHeight, align) Canvas( - Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH, fit) { + Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH, align) { var touching = false var target: CdpPage? = null try { @@ -268,7 +349,7 @@ internal fun SteamQamPanel() { PointerEventType.Release -> "touchEnd" else -> null }?.takeIf { it == "touchStart" || touching } ?: continue - if (type == "touchStart") target = holder[0] + if (type == "touchStart") target = page() touching = type != "touchEnd" val points = if (type == "touchEnd") JSONArray() else JSONArray().put(JSONObject().put("x", x.toDouble()).put("y", y.toDouble())) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt index 6745afaa01..3e8b6b1d1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt @@ -199,7 +199,6 @@ internal fun SessionDrawerPreview(secondScreens: List) { secondScreenDisplays = secondScreens, selectedSecondScreenDisplay = secondScreens.firstOrNull()?.id ?: -1, onSecondScreenDisplay = {}, - onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt b/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt index 59c87675e9..3810161619 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt @@ -7,13 +7,16 @@ import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn @@ -35,6 +38,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role @@ -90,6 +94,29 @@ internal fun DrawerEntryHint(steam: Boolean, inverted: Boolean, onOpen: () -> Un } } +/** A Quest has no system Back gesture, so a laser drag in from the right edge stands in for it. */ +@Composable +internal fun DrawerEdgeSwipe(onBack: () -> Unit) { + val density = LocalDensity.current + val threshold = with(density) { 48.dp.toPx() } + val strip = with(density) { 12.toDp() } + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) { + Box( + Modifier.fillMaxHeight().width(strip).testTag("drawer-edge") + .pointerInput(Unit) { + var travelled = 0f + detectHorizontalDragGestures( + onDragStart = { travelled = 0f }, + onDragEnd = { if (travelled <= -threshold) onBack() }, + ) { change, amount -> + change.consume() + travelled += amount + } + }, + ) + } +} + @Composable internal fun DrawerCornerTap(onOpen: () -> Unit) { Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout), contentAlignment = Alignment.TopEnd) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DrawerSections.kt b/app/src/main/java/com/droiddeck/launcher/ui/DrawerSections.kt new file mode 100644 index 0000000000..fd6839d134 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DrawerSections.kt @@ -0,0 +1,142 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.ExpandMore +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionPrefs + +/** + * Inside the session menu every top-level settings group folds to its header and a summary of its values. + * Groups start folded; a group the player opens or folds stays that way across sessions. + */ +internal object DrawerSectionState { + private val chosen = mutableStateMapOf() + + fun load(context: Context) { + if (DevPreview.drawer != null) return + chosen.clear() + chosen.putAll(SessionPrefs.drawerSections(context)) + } + + fun isOpen(key: String) = chosen[key] ?: false + + fun toggle(context: Context, key: String) { + chosen[key] = !isOpen(key) + if (DevPreview.drawer == null) SessionPrefs.setDrawerSections(context, chosen.toMap()) + } +} + +internal class DrawerSections(val context: Context, val track: (String) -> Modifier) + +internal val LocalDrawerSections = compositionLocalOf { null } + +@Composable +internal fun DrawerSection( + sections: DrawerSections, key: String, title: String, summary: String?, tag: String?, + content: @Composable ColumnScope.() -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val open = DrawerSectionState.isOpen(key) + val source = remember { MutableInteractionSource() } + val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value + val rotation by animateFloatAsState(if (open) 180f else 0f, Motion.tw(180), label = "sectionArrow") + val state = stringResource(if (open) R.string.widgets_expanded else R.string.widgets_collapsed) + val toggle = { DrawerSectionState.toggle(sections.context, key) } + val shape = RoundedCornerShape(14.dp) + Column( + Modifier.fillMaxWidth().padding(top = 6.dp).clip(shape) + .background(colors.surface).border(1.dp, if (open) pal.line2 else pal.line, shape), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp) + .then(sections.track("section-$key")) + .testTag("drawer-section-$key") + .background(if (hot) pal.signal.copy(alpha = 0.12f) else androidx.compose.ui.graphics.Color.Transparent) + .glideBorder(hot, shape, pal.signal) + .hoverable(source) + .clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = toggle) + .controllerConfirm(onClick = toggle) + .semantics { contentDescription = title; stateDescription = state } + .padding(start = 12.dp, end = 8.dp, top = 6.dp, bottom = 6.dp), + ) { + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Text(title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, + color = if (open) colors.onBackground else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false)) + if (tag != null) Text( + tag, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1, + modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(pal.signal.copy(alpha = 0.14f)) + .padding(horizontal = 6.dp, vertical = 2.dp), + ) + } + if (!open && !summary.isNullOrEmpty()) Text( + summary, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(top = 2.dp), + ) + } + Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = colors.onSurfaceVariant, + modifier = Modifier.size(22.dp).rotate(rotation)) + } + AnimatedVisibility(open, enter = expandVertically(Motion.tw(200)) + fadeIn(Motion.tw(160)), + exit = shrinkVertically(Motion.tw(160)) + fadeOut(Motion.tw(120))) { + Column(Modifier.fillMaxWidth()) { + Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) + // Only top-level groups fold; groups and dialogs opened from inside one draw normally. + CompositionLocalProvider(LocalDrawerSections provides null) { content() } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt index 0028a55972..df1a7d6e53 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt @@ -26,7 +26,8 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri fun on(key: String) = cfg[key] == "1" fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback - SettingsGroup(stringResource(R.string.drawer_hud)) { + SettingsGroup(stringResource(R.string.drawer_hud), key = "performance-hud", + detail = stringResource(if (a.hudOn) R.string.widgets_on else R.string.widgets_off)) { ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud) if (a.hudOn) ToggleRow( host, "hud-only-during-game", stringResource(R.string.hud_only_during_game), @@ -62,7 +63,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri if (a.dashboardAvailable && a.secondScreenDisplays.isNotEmpty()) BottomStripSettings(host, track) if (!a.hudOn) return - SettingsGroup(stringResource(R.string.hud_group_look)) { + SettingsGroup(stringResource(R.string.hud_group_look), key = "performance-hud-look") { SliderRow(stringResource(R.string.hud_scale), null, int("hudScale", 100), 50..150, step = 5, format = { "$it%" }, modifier = track("hud-scale")) { a.onHudSetting("hudScale", it.toString()) } SliderRow(stringResource(R.string.drawer_hud_opacity), null, int("hudOpacity", 80), 0..100, step = 5, format = { "$it%" }, @@ -85,7 +86,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri } var editing by remember { mutableStateOf(false) } - SettingsGroup(stringResource(R.string.hud_group_metrics)) { + SettingsGroup(stringResource(R.string.hud_group_metrics), key = "performance-hud-metrics") { ActionRow(stringResource(R.string.hud_group_metrics), null, stringResource(R.string.common_edit), onClick = { editing = true }, modifier = track("hud-readings")) val rows = DroidDeckHudSize.rowsFor(DroidDeckHudSize.from(cfg["hudSize"]), cfg) @@ -103,7 +104,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri ) } - if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps)) { + if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps), key = "performance-hud-temps") { ChoiceRow(host, "hud-temp-unit", stringResource(R.string.hud_temp_unit), null, listOf("c" to "°C", "f" to "°F"), if (cfg["tempUnit"].equals("f", true)) "f" else "c", chipModifier = track("hud-temp-unit")) { a.onHudSetting("tempUnit", it) } @@ -129,7 +130,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri } } - SettingsGroup(stringResource(R.string.hud_group_more)) { + SettingsGroup(stringResource(R.string.hud_group_more), key = "performance-hud-more") { ActionRow(stringResource(R.string.hud_export), stringResource(R.string.hud_export_hint), stringResource(R.string.hud_export_button), onClick = a.onHudExport, modifier = track("hud-export")) ActionRow(stringResource(R.string.hud_reset), null, stringResource(R.string.hud_reset_button), @@ -145,7 +146,7 @@ private fun BottomStripSettings(host: MenuHost, track: (String) -> Modifier) { var hudOn by remember { mutableStateOf(SessionPrefs.bottomHud(context)) } var onTabs by remember { mutableStateOf(SessionPrefs.bottomStripOnTabs(context)) } var shown by remember { mutableStateOf(SessionPrefs.bottomStripMetrics(context)) } - SettingsGroup(stringResource(R.string.bottom_hud_group)) { + SettingsGroup(stringResource(R.string.bottom_hud_group), key = "performance-bottom-hud") { ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), null, hudOn, chipModifier = track("bottom-hud")) { on -> hudOn = on diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt index 83f2e05436..bc8576b287 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -1,52 +1,371 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.withFrameNanos +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp import com.droiddeck.launcher.R import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.gpu.Lossless @Composable internal fun FrameGenMenu( - host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State, + mode: FrameGen.Mode, + lossless: Lossless.State, onPick: (FrameGen.Mode) -> Unit, - onImportLossless: () -> Unit, gameProfileId: String? = null, hasGameOverride: Boolean = false, onResetGame: () -> Unit = {}, + focusModifier: Modifier = Modifier, + legacyButtons: Boolean = false, + listLayout: Boolean = false, + sessionHost: MenuHost? = null, ) { + val sessionEngineAnchor = remember { FocusRequester() } + val need = stringResource(R.string.lsfg_needs_steam) + val selectedEngine = mode.engine.takeIf { it != FrameGen.ENGINE_OFF } + val offLabel = FrameGen.label(LocalContext.current, FrameGen.Mode.OFF) + val colors = MaterialTheme.colorScheme val context = LocalContext.current - AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = stringResource(R.string.frame_gen_title)) { firstItemFocus -> - val need = when { - lossless.ready -> null - lossless.owned -> stringResource(R.string.lsfg_needs_install) - else -> stringResource(R.string.lsfg_needs_steam) + var pacerEnabled by remember { mutableStateOf(FrameGen.pacerEnabled(context)) } + val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG", FrameGen.ENGINE_ZEROFG to "ZeroFG") + + if (legacyButtons) { + val context = LocalContext.current + val options = buildList { + add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) + (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) } + (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, it)) } + (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) } + FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) } } - @Composable - fun item(m: FrameGen.Mode, enabled: Boolean = true, detail: String? = null, focus: FocusRequester? = null) = - MenuItem(FrameGen.label(context, m), checked = mode == m, enabled = enabled, detail = detail, focusRequester = focus) { - onPick(m); host.open = null + Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) { + options.forEachIndexed { index, option -> + val selected = mode == option || + (option.engine == FrameGen.ENGINE_OFF && selectedEngine == null) + val enabled = option.engine != FrameGen.ENGINE_LSFG || lossless.ready || selected + val pick = { onPick(option) } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = (if (index == 0) focusModifier else Modifier).fillMaxWidth() + .padding(top = if (index == 0) 0.dp else 6.dp) + .controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(FrameGen.label(context, option)) } } - item(FrameGen.Mode.OFF, focus = firstItemFocus) - if (gameProfileId != null) { - MenuItem(stringResource(R.string.comp_game_use_general), checked = !hasGameOverride) { + if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) { + Text( + need, + color = colors.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(top = 6.dp), + ) + } + if (gameProfileId != null) { + val resetGame = onResetGame + OutlinedButton( + onClick = resetGame, + modifier = Modifier.fillMaxWidth().padding(top = 6.dp) + .controllerConfirm(onClick = resetGame), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + ) { + Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓") + } + } + } + return + } + + Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) { + if (sessionHost != null) { + SessionFrameGenEngine( + sessionHost, mode, listOf(FrameGen.ENGINE_OFF to offLabel) + engines, + lossless.ready, need, focusModifier, sessionEngineAnchor, onPick, + ) + } else { + OutlinedButton( + onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) }, + modifier = Modifier.fillMaxWidth().controllerConfirm( + onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) }, + ), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selectedEngine == null) colors.primary else colors.onSurface, + ), + ) { Text(offLabel) } + + if (listLayout) { + Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + engines.forEach { (engine, label) -> + val selected = selectedEngine == engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready + val pick = { + onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } + } + } + } else { + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + val focusIndex = engines.indexOfFirst { (engine, _) -> + selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready + } + engines.forEachIndexed { index, (engine, label) -> + val selected = selectedEngine == engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready + val pick = { + onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = (if (index == focusIndex) focusModifier else Modifier) + .weight(1f).controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } + } + } + } + } + + val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready + if (listLayout) { + Column( + Modifier.fillMaxWidth().padding(top = 8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + (2..4).forEach { multiplier -> + val selected = mode.multiplier == multiplier && mode.target == 0 + val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) } + OutlinedButton( + onClick = pickMultiplier, + enabled = multiplierEnabled, + modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier) + .frameGenFocus(sessionHost), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, + contentColor = if (selected) colors.secondary else colors.onSurface, + ), + ) { Text("${multiplier}×") } + } + } + } else { + Row( + Modifier.fillMaxWidth().padding(top = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + (2..4).forEach { multiplier -> + val selected = mode.multiplier == multiplier && mode.target == 0 + val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) } + OutlinedButton( + onClick = pickMultiplier, + enabled = multiplierEnabled, + modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier) + .frameGenFocus(sessionHost), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, + contentColor = if (selected) colors.secondary else colors.onSurface, + ), + ) { Text("${multiplier}×") } + } + } + } + + val togglePacer = { + val enabled = !pacerEnabled + FrameGen.setPacer(context, enabled) + pacerEnabled = enabled + } + OutlinedButton( + onClick = togglePacer, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp) + .controllerConfirm(onClick = togglePacer).frameGenFocus(sessionHost), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (pacerEnabled) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (pacerEnabled) colors.primary else colors.onSurface, + ), + ) { + Text("ZeroPacer" + if (pacerEnabled) " ✓" else "") + } + + + if (selectedEngine == FrameGen.ENGINE_LSFG) { + Row( + Modifier.fillMaxWidth().padding(top = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + FrameGen.ADAPTIVE_TARGETS.forEach { target -> + val adaptiveMode = FrameGen.Mode(FrameGen.ENGINE_LSFG, target = target) + val selected = mode.target == target + val pickTarget = { onPick(adaptiveMode) } + OutlinedButton( + onClick = pickTarget, + enabled = lossless.ready, + modifier = Modifier.weight(1f).controllerConfirm( + enabled = lossless.ready, + onClick = pickTarget, + ).frameGenFocus(sessionHost), + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, + contentColor = if (selected) colors.secondary else colors.onSurface, + ), + ) { + Text(FrameGen.label(LocalContext.current, adaptiveMode)) + } + } + } + } + + if (sessionHost == null && selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) { + Text(need, color = colors.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(top = 6.dp)) + } + + if (gameProfileId != null && (sessionHost == null || hasGameOverride)) { + val input = LocalInputModeManager.current + val resetGame = { + if (sessionHost != null && input.inputMode == InputMode.Keyboard) { + sessionEngineAnchor.requestFocus() + } onResetGame() - host.open = null } + OutlinedButton( + onClick = resetGame, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp) + .testTag("framegen-use-global").controllerConfirm(onClick = resetGame) + .frameGenFocus(sessionHost), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + ) { + Text(if (sessionHost != null) stringResource(R.string.frame_gen_use_global) + else stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓") + } } - for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_DDFG, m)) - val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } + - FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) } - lsfg.forEachIndexed { i, m -> item(m, enabled = lossless.ready, detail = need.takeIf { i == 0 }) } - if (lossless.owned) { - val using = when (lossless.source) { - Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam) - Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import) - Lossless.Source.NONE -> null + } +} + +@Composable +private fun Modifier.frameGenFocus(sessionHost: MenuHost?): Modifier = + if (sessionHost != null) focusGlide(RoundedCornerShape(percent = 50)) else this + +@Composable +private fun SessionFrameGenEngine( + host: MenuHost, + mode: FrameGen.Mode, + options: List>, + losslessReady: Boolean, + losslessNote: String, + focusModifier: Modifier, + anchor: FocusRequester, + onPick: (FrameGen.Mode) -> Unit, +) { + val label = stringResource(R.string.frame_gen_engine) + val selectedLabel = options.firstOrNull { (engine, _) -> engine == mode.engine }?.second + ?: options.first().second + val key = "frame-generation-engine" + val open = host.open == key + val input = LocalInputModeManager.current + var anchorFocused by remember { mutableStateOf(false) } + val selectedOption = remember { FocusRequester() } + var keyboardOpened by remember { mutableStateOf(false) } + val initial = options.firstOrNull { (engine, _) -> engine == mode.engine }?.first + ?: FrameGen.ENGINE_OFF + val close = { if (host.open == key) host.open = null } + + // Keep the options in the drawer's focus tree. A separate popup window can + // steal focus from the controller before Compose can focus the selected row. + LaunchedEffect(open) { + if (!keyboardOpened || (!open && host.open != null)) return@LaunchedEffect + val target = if (open) selectedOption else anchor + withFrameNanos { } + target.requestFocus() + if (!open) keyboardOpened = false + } + + val blockedSelection = !losslessReady && mode.engine == FrameGen.ENGINE_LSFG + SettingsRow(label, losslessNote.takeIf { blockedSelection && !open }, highlighted = open) { + ValueChip( + selectedLabel, open, + modifier = focusModifier.focusRequester(anchor).onFocusChanged { anchorFocused = it.isFocused } + .heightIn(min = 48.dp).testTag("setting-$key") + .semantics { contentDescription = label; stateDescription = selectedLabel }, + ) { + if (open) close() + else { + keyboardOpened = anchorFocused || input.inputMode == InputMode.Keyboard + host.open = key + } + } + } + if (open) { + Column(Modifier.fillMaxWidth().padding(horizontal = 8.dp).controllerBack(close)) { + options.forEach { (engine, text) -> + val selected = engine == mode.engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || losslessReady + MenuItem( + label = text, checked = selected, enabled = enabled, + detail = losslessNote.takeIf { engine == FrameGen.ENGINE_LSFG && !losslessReady }, + focusRequester = selectedOption.takeIf { engine == initial }, + modifier = Modifier.heightIn(min = 48.dp).testTag("framegen-engine:$engine"), + ) { + close() + if (!selected) { + onPick(if (engine == FrameGen.ENGINE_OFF) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) + else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + } } - MenuItem(stringResource(R.string.lsfg_import), checked = false, detail = using) { host.open = null; onImportLossless() } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index efe3587660..917a46e71d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -177,6 +177,12 @@ class FrontEndState( val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER, val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM, val launcherFullscreen: Boolean = true, + val launcherFrost: Boolean = false, + val frostWallpaper: Boolean = true, + val frostCards: Boolean = true, + val frostTransparency: Int = FROST_WALLPAPER_DEFAULT, + val frostCardTransparency: Int = FROST_DEFAULT, + val frostSupported: Boolean = false, val controllerHaptics: Boolean = true, val downloadSource: String = DownloadSource.MODE_AUTO, val downloadMirror: String = "", @@ -240,7 +246,6 @@ class FrontEndActions( val onVkBridgeSafe: (Boolean) -> Unit = {}, val onBridgeProtonDxvk: (Boolean) -> Unit = {}, val onFrameGenPick: (FrameGen.Mode) -> Unit, - val onImportLossless: () -> Unit, val onProtons: () -> Unit, val onComponents: (focusContent: Boolean) -> Unit, val onGameComponents: (Library.SteamGame) -> Unit = { onComponents(true) }, @@ -284,6 +289,11 @@ class FrontEndActions( val onLauncherOrientation: (Int) -> Unit = {}, val onHomePage: (String) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {}, + val onLauncherFrost: (Boolean) -> Unit = {}, + val onFrostWallpaper: (Boolean) -> Unit = {}, + val onFrostCards: (Boolean) -> Unit = {}, + val onFrostTransparency: (Int) -> Unit = {}, + val onFrostCardTransparency: (Int) -> Unit = {}, val onControllerHaptics: (Boolean) -> Unit = {}, val onAnimationsEnabled: (Boolean) -> Unit = {}, val onLowStorageWarning: (Boolean) -> Unit = {}, @@ -446,6 +456,15 @@ internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusR } } +internal suspend fun holdFocus(held: () -> Boolean, target: () -> FocusRequester?) { + val since = MainTabSteps.otherKeys + repeat(RAIL_HOLD_FRAMES) { frame -> + androidx.compose.runtime.withFrameNanos { } + if (MainTabSteps.otherKeys != since) return + if (frame == 0 || !held()) runCatching { target()?.requestFocus() } + } +} + internal suspend fun focusSoon(target: () -> FocusRequester) { repeat(30) { androidx.compose.runtime.withFrameNanos { } @@ -693,7 +712,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } } androidx.compose.foundation.layout.BoxWithConstraints( - modifier = Modifier.fillMaxSize().background(colors.background) + modifier = Modifier.fillMaxSize().background(if (LocalFrost.current != null) Color.Transparent else colors.background) .windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars) .onFocusChanged { anyFocused = it.hasFocus }, ) { @@ -775,10 +794,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com val stepScope = androidx.compose.runtime.rememberCoroutineScope() val pageKeyNow = androidx.compose.runtime.rememberUpdatedState(s.pageKey) var railHold by remember { mutableStateOf(null) } + val stepView = androidx.compose.ui.platform.LocalView.current val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int -> if (!processSettingsPageVisible) { val keys = navigationKeys(s) keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key -> + releaseFocusedTextField(stepView) + OpenMenus.leaveAll(withPage = true) PageSwipe.direction = step if (s.dualScreen) { onRailSelect(key); return@let } showRailPage(key, false) @@ -847,7 +869,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } } com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } } com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } } - com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } } + com.droiddeck.launcher.stores.StoresState.steamPicking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.StoresState.steamPicking = null } } } StepsLayer(screenAt) UiZooSheet() SessionDrawerPreview(s.secondScreenDisplays) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 1954c933b3..e314d8d70d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -1,6 +1,9 @@ package com.droiddeck.launcher.ui import androidx.compose.ui.platform.LocalContext +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.FocusRequester import android.os.Build @@ -50,6 +53,7 @@ import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @@ -103,7 +107,7 @@ internal object SetupTabs { } @Composable -internal fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) { +internal fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, detailLines: Int = 2, action: (@Composable () -> Unit)? = null) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val tint = when (state) { @@ -135,7 +139,7 @@ internal fun CheckRow(state: CheckState, title: String, detail: String?, divider } Column(modifier = Modifier.weight(1f)) { Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) - if (detail != null) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis) + if (detail != null) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = detailLines, overflow = TextOverflow.Ellipsis) } if (action != null) action() } @@ -152,6 +156,20 @@ internal fun SetupPanel( ) { val host = rememberMenuHost() val ctx = LocalContext.current + val frostRow = s.frostSupported && s.theme != Themes.TRUE_BLACK + var steamOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "steam")) } + var desktopOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "desktop")) } + val lifecycleOwner = LocalLifecycleOwner.current + DisposableEffect(lifecycleOwner, ctx) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + steamOrientation = SessionPrefs.orientation(ctx, "steam") + desktopOrientation = SessionPrefs.orientation(ctx, "desktop") + } + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + } var hideHomeFromRecents by remember { mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.hideHomeFromRecents(ctx)) } var processLimitBusy by remember { mutableStateOf(false) } var processLimitMessage by remember { mutableStateOf(null) } @@ -251,7 +269,7 @@ internal fun SetupPanel( val listing = searching && query.isNotBlank() val fixed = tab == CONTROLLER_TAB && !listing Column(modifier = Modifier.weight(1f).fillMaxWidth().then(if (fixed) Modifier else Modifier.verticalScroll(rememberScrollState())).padding(bottom = if (fixed) 0.dp else 24.dp)) { - if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) } + if (listing) SettingsSearchResults(query, frostRow) { section -> pick(section.ordinal) } else when (tab) { OVERVIEW_TAB -> { OnboardingCard(limitBlocks, a.onShowPhantomGate) @@ -398,7 +416,8 @@ internal fun SetupPanel( listOfNotNull( gpu.displayName(ctx), s.installed?.let { stringResource(R.string.setup_ready_runtime, it) }, - stringResource(R.string.setup_ready_limit_off).takeIf { !limitBlocks }, + stringResource(R.string.setup_ready_limit_off) + .takeIf { !limitBlocks && s.phantomProcessStatus != PhantomProcessStatus.UNCOUNTED }, s.offlineAccount?.takeIf { it.isNotEmpty() }?.let { stringResource(R.string.setup_ready_signed_in, it) }, ).joinToString(" · "), open = showChecks, onDetails = { showChecks = !showChecks }, @@ -447,6 +466,35 @@ internal fun SetupPanel( if (s.theme == Themes.GRADIENT) GradientColorRows() if (s.theme == Themes.CUSTOM) CustomColorRows() if (s.theme == Themes.TRUE_BLACK) HighlightColorRow() + if (frostRow) { + ToggleRow( + host, "launcher-frost", stringResource(R.string.setup_frosted_background), + stringResource(R.string.setup_frosted_background_hint), s.launcherFrost, onChange = a.onLauncherFrost, + ) + if (s.launcherFrost) { + val ctx = androidx.compose.ui.platform.LocalContext.current + val percent: (Int) -> String = { ctx.getString(R.string.ctrl_percent, it) } + ToggleRow( + host, "launcher-frost-wallpaper", stringResource(R.string.setup_frosted_wallpaper), null, + s.frostWallpaper, onChange = a.onFrostWallpaper, + ) + SliderRow( + stringResource(R.string.setup_frost_transparency), stringResource(R.string.setup_frost_transparency_hint), + s.frostTransparency, 0..FROST_MAX, step = FROST_STEP, enabled = s.frostWallpaper, format = percent, + onChange = a.onFrostTransparency, + ) + ToggleRow( + host, "launcher-frost-cards", stringResource(R.string.setup_frosted_cards), + stringResource(if (s.frostWallpaper) R.string.setup_frosted_cards_hint else R.string.setup_frosted_cards_needs_wallpaper), + s.frostCards, enabled = s.frostWallpaper, onChange = a.onFrostCards, + ) + SliderRow( + stringResource(R.string.setup_frost_card_transparency), stringResource(R.string.setup_frost_card_transparency_hint), + s.frostCardTransparency, 0..FROST_MAX, step = FROST_STEP, enabled = s.frostWallpaper && s.frostCards, format = percent, + onChange = a.onFrostCardTransparency, + ) + } + } ChoiceRow( host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint), com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent -> @@ -516,7 +564,27 @@ internal fun SetupPanel( ChoiceRow( host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint), SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }, - s.orientation, onPick = a.onOrientation, + s.orientation, onPick = { value -> + a.onOrientation(value) + steamOrientation = SessionPrefs.orientation(ctx, "steam") + desktopOrientation = SessionPrefs.orientation(ctx, "desktop") + }, + ) + ChoiceRow( + host, "orientation-steam", stringResource(R.string.setup_session_orientation) + " (Steam)", stringResource(R.string.setup_session_orientation_hint), + SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }, + steamOrientation, onPick = { value -> + steamOrientation = value + SessionPrefs.setOrientation(ctx, "steam", value) + }, + ) + ChoiceRow( + host, "orientation-desktop", stringResource(R.string.setup_session_orientation) + " (Desktop)", stringResource(R.string.setup_session_orientation_hint), + SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }, + desktopOrientation, onPick = { value -> + desktopOrientation = value + SessionPrefs.setOrientation(ctx, "desktop", value) + }, ) ToggleRow( host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen), @@ -643,7 +711,7 @@ internal fun SetupPanel( ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) { AgentPet.set(agentContext, it) } - if (AgentPet.enabled && !AgentPet.allowed) ActionRow( + if (AgentPet.enabled && !AgentPet.allowed && AgentPet.usesOverlayWindows(com.droiddeck.launcher.session.QuestExperimental.isSupported())) ActionRow( stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint), stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) }, ) @@ -792,7 +860,7 @@ internal fun ReadinessCard( @Composable private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) { - FrameGenMenu(host, s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless) + FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, legacyButtons = true) } @Composable @@ -819,6 +887,33 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m -> Box(m) { GameSettingsCard(host, game, steamScope) } } else null + val frameGenMenuContent: @Composable () -> Unit = { + FrameGenMenu( + mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen, + lossless = s.lossless, + onPick = { mode -> + val key = frameGenProfileKey + if (key == null) { + a.onFrameGenPick(mode) + } else { + com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode) + gameFrameGenMode = mode + gameFrameGenOverride = true + } + }, + legacyButtons = true, + gameProfileId = frameGenProfileKey, + hasGameOverride = gameFrameGenOverride, + onResetGame = { + val key = frameGenProfileKey + if (key != null) { + com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key) + gameFrameGenMode = com.droiddeck.launcher.gpu.FrameGen.mode(context) + gameFrameGenOverride = false + } + }, + ) + } val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> { add { m -> val back = stringResource(R.string.hop_from_games) @@ -840,33 +935,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost ) { host.open = if (host.open == "fg") null else "fg" } - FrameGenMenu( - host = host, - mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen, - lossless = s.lossless, - onPick = { mode -> - val key = frameGenProfileKey - if (key == null) { - a.onFrameGenPick(mode) - } else { - com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode) - gameFrameGenMode = mode - gameFrameGenOverride = true - } - }, - onImportLossless = a.onImportLossless, - gameProfileId = frameGenProfileKey, - hasGameOverride = gameFrameGenOverride, - onResetGame = { - val key = frameGenProfileKey - if (key != null) { - com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key) - gameFrameGenMode = - com.droiddeck.launcher.gpu.FrameGen.mode(context) - gameFrameGenOverride = false - } - } - ) + } } if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) } @@ -898,6 +967,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost repeat(columns - row.size) { Spacer(Modifier.weight(1f)) } } } + if (host.open == "fg") { + Box(Modifier.fillMaxWidth().padding(top = 4.dp)) { + frameGenMenuContent() + } + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 6d64f033b9..5415293cfb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -235,7 +235,7 @@ internal fun GameDetail( steppedTo = null return@LaunchedEffect } - focusSoon { tabFocus.getValue(t) } + holdFocus({ onStrip }) { tabFocus.getValue(t) } steppedTo = null } fun cycle(step: Int) { @@ -243,7 +243,7 @@ internal fun GameDetail( val at = tabs.indexOf(tab).coerceAtLeast(0) val next = tabs[(at + step + tabs.size) % tabs.size] picked = next - if (inPage) steppedTo = next + steppedTo = next } val art: Any? = game?.hero ?: item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover val artModel: Any? = if (art is String) cardArtRequest(art, item?.tallImageUrl) else art @@ -396,7 +396,7 @@ private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) { } @Composable -private fun GameTabBar( +internal fun GameTabBar( tabs: List, selected: Int, onSelect: (Int) -> Unit, modifier: Modifier = Modifier, focusRequesters: List? = null, bumpers: Boolean = true, compact: Boolean = false, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt index 877cad9240..ba44249ca9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlassesPanel.kt @@ -23,6 +23,9 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.draw.clip @@ -31,6 +34,7 @@ import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.sp import androidx.compose.runtime.getValue +import com.droiddeck.launcher.session.SessionPrefs import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor @@ -67,6 +71,21 @@ internal val GlassesIcon: ImageVector by lazy { }.build() } +@Composable +internal fun rememberShowGlassesShortcut(): Boolean { + val context = LocalContext.current + var show by remember(context) { mutableStateOf(SessionPrefs.showGlassesShortcut(context)) } + DisposableEffect(context) { + val preferences = context.getSharedPreferences("session", android.content.Context.MODE_PRIVATE) + val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key -> + if (key == "showGlassesShortcut") show = SessionPrefs.showGlassesShortcut(context) + } + preferences.registerOnSharedPreferenceChangeListener(listener) + onDispose { preferences.unregisterOnSharedPreferenceChangeListener(listener) } + } + return show +} + @Composable internal fun rememberGlasses(): Pair { val g by Glasses.state.collectAsState() @@ -88,7 +107,7 @@ internal fun VrControllerGroups(host: MenuHost, track: (String) -> Modifier = { androidx.compose.runtime.LaunchedEffect(Unit) { com.droiddeck.launcher.input.VrControllers.load(context) } val c by com.droiddeck.launcher.input.VrControllers.settings.collectAsState() val emulate = com.droiddeck.launcher.input.VrControllers.Emulate.entries - SettingsGroup(stringResource(R.string.vr_controllers_group)) { + SettingsGroup(stringResource(R.string.vr_controllers_group), key = "vr-controllers") { ChoiceRow(host, "vr-emulate", stringResource(R.string.vr_controllers_emulate), stringResource(R.string.vr_controllers_emulate_hint), emulate.map { it to stringResource(when (it) { com.droiddeck.launcher.input.VrControllers.Emulate.OFF -> R.string.vr_controllers_off @@ -133,6 +152,7 @@ internal fun GlassesGroups( ) { val display = tab == null || tab == GlassesTab.DISPLAY val vr = tab == null || tab == GlassesTab.VR + val showShortcut = rememberShowGlassesShortcut() val picture = GlassesRendering.picture(s, g.sbs, steamVrRunning) val usesGlasses = GlassesRendering.usesGlasses(g, outputActive, steamVrRunning) val spatialTracking = g.spatialConnected && s.positionalTracking @@ -142,13 +162,13 @@ internal fun GlassesGroups( val directView = usesGlasses && picture == GlassesRendering.Picture.STEREO val menuScreen = !inSession && g.usable && s.gameOnGlasses && s.screen3dof if (g.canControl && onRecenter != null && s.headTracking && (virtualScreen || menuScreen || (directView && steamVrRunning))) { - SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true) { + SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true, key = "vr-glasses-quick") { ActionRow(stringResource(R.string.glasses_recenter), if (virtualScreen || menuScreen) stringResource(R.string.glasses_recenter_screen_hint) else null, stringResource(R.string.cardboard_recenter_button), onRecenter) } } - if (display) SettingsGroup(g.model) { + if (display) SettingsGroup(g.model, key = "vr-glasses") { if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource( if (g.supportsDisplayModeControl) R.string.glasses_xreal_experimental else R.string.glasses_pro2_experimental)) {} val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(), @@ -168,9 +188,15 @@ internal fun GlassesGroups( } ToggleRow(host, "glasses-game", stringResource(R.string.glasses_game_on), stringResource(R.string.glasses_game_on_hint), s.gameOnGlasses, chipModifier = track("glasses-game")) { Glasses.setGameOnGlasses(it) } + if (inSession) { + val context = androidx.compose.ui.platform.LocalContext.current + ToggleRow(host, "glasses-shortcut", stringResource(R.string.glasses_show_shortcut), + stringResource(R.string.glasses_show_shortcut_hint), showShortcut, + chipModifier = track("glasses-shortcut")) { SessionPrefs.setShowGlassesShortcut(context, it) } + } } if (display && g.canControl && g.supportsDisplayModeControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) { - SettingsGroup(stringResource(R.string.glasses_display_mode)) { + SettingsGroup(stringResource(R.string.glasses_display_mode), key = "vr-glasses-mode") { if (g.sbsSupport == GlassesState.SBS_FAILS && !g.sbs) { ActionRow(stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_failed), stringResource(R.string.stores_dl_retry), { Glasses.set3d(true) }) @@ -182,12 +208,12 @@ internal fun GlassesGroups( val profiles = if (inSession) listOf(GlassesDisplayModes.profile(g.sbs, false)) else listOf(GlassesDisplayProfile.TWO_D, GlassesDisplayProfile.THREE_D) for (profile in profiles) SettingsGroup(stringResource(if (profile == GlassesDisplayProfile.TWO_D) - R.string.glasses_output_2d else R.string.glasses_output_3d)) { + R.string.glasses_output_2d else R.string.glasses_output_3d), key = "vr-glasses-output-${profile.name.lowercase()}") { GlassesResolutionRow(host, g, s, profile, track) if ((profile == GlassesDisplayProfile.THREE_D) == g.sbs) GlassesRefreshRow(host, g, s, track) } } - if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group)) { + if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group), key = "vr-glasses-picture") { ChoiceRow(host, "glasses-picture", stringResource(R.string.glasses_picture), stringResource(R.string.glasses_picture_hint), listOf( GlassesSettings.PICTURE_AUTO to stringResource(R.string.glasses_picture_auto), @@ -213,7 +239,7 @@ internal fun GlassesGroups( format = { SpatialMeasurements.distance(it / 10f) }, modifier = track("glasses-distance")) { Glasses.setScreenDistanceDm(it) } } } - if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr)) { + if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr), key = "vr-glasses-steamvr") { steamVr() if (g.supportsDisplayModeControl) ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d), stringResource(R.string.glasses_auto3d_hint), s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) } @@ -226,7 +252,7 @@ internal fun GlassesGroups( format = { "$it°" }, modifier = track("glasses-vr-fov")) { Glasses.setVrFovDeg(it) } } if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) { - SettingsGroup(stringResource(R.string.glasses_head_tracking)) { + SettingsGroup(stringResource(R.string.glasses_head_tracking), key = "vr-glasses-tracking") { val trackingHint = when { inSession && !usesGlasses -> R.string.glasses_screen_no_output spatialVr -> R.string.glasses_head_tracking_spatial_vr_hint @@ -240,13 +266,13 @@ internal fun GlassesGroups( chipModifier = track("glasses-tracking")) { Glasses.setHeadTracking(it) } } val calibration by Glasses.calibration.collectAsState() - if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration)) { + if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration), key = "vr-glasses-calibration") { GlassesCalibrationControls(calibration, onStart = Glasses::startCalibration, onCancel = Glasses::cancelCalibration, onReset = Glasses::resetCalibration, onDone = { onRecenter?.invoke() }) } } - if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware)) { + if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware), key = "vr-glasses-hardware") { if (g.brightnessMax > 0) SliderRow(stringResource(R.string.glasses_brightness), null, g.brightness.coerceAtLeast(0), 0..g.brightnessMax, step = 1, modifier = track("glasses-brightness")) { Glasses.setBrightness(it) } if (g.volumeMax > 0) SliderRow(stringResource(R.string.glasses_volume), null, g.volume.coerceAtLeast(0), 0..g.volumeMax, step = 1, @@ -259,7 +285,7 @@ internal fun GlassesGroups( androidx.compose.runtime.LaunchedEffect(Unit) { HandTracking.load(context) } if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) { if (g.spatialConnected) { - SettingsGroup(stringResource(R.string.glasses_experimental)) { + SettingsGroup(stringResource(R.string.glasses_experimental), key = "vr-glasses-experimental") { val spatial by SpatialTracking.status.collectAsState() ToggleRow(host, "glasses-position", stringResource(R.string.glasses_position), stringResource(R.string.glasses_position_hint), s.positionalTracking, chipModifier = track("glasses-position")) { Glasses.setPositionalTracking(it) } @@ -282,7 +308,7 @@ internal fun GlassesGroups( s.joyConTracking, enabled = s.positionalTracking, chipModifier = track("glasses-joycons")) { Glasses.setJoyConTracking(it) } } } - if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group)) { + if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group), key = "vr-hand-camera") { HandCameraRows(host, track, inSession) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlassesSetupPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlassesSetupPanel.kt index 8b2378ae4d..ced0d6b579 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GlassesSetupPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlassesSetupPanel.kt @@ -21,12 +21,20 @@ internal fun GlassesSetupPanel() { val (glasses, settings) = rememberGlasses() val host = rememberMenuHost() val tabs = glassesTabs(glasses) + val context = androidx.compose.ui.platform.LocalContext.current + val showShortcut = rememberShowGlassesShortcut() var selectedTab by rememberSaveable { mutableStateOf(GlassesTab.DISPLAY) } val tab = selectedTab.takeIf { selected -> tabs.any { it.first == selected } } ?: GlassesTab.DISPLAY LaunchedEffect(tab, glasses.present, glasses.canControl, glasses.model) { host.open = null } Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) { Note(stringResource(R.string.setup_glasses_scope)) + SettingsGroup(stringResource(R.string.glasses_shortcut_group), key = "glasses-shortcut") { + ToggleRow(host, "glasses-shortcut", stringResource(R.string.glasses_show_shortcut), + stringResource(R.string.glasses_show_shortcut_hint), showShortcut) { + com.droiddeck.launcher.session.SessionPrefs.setShowGlassesShortcut(context, it) + } + } if (!glasses.present && !glasses.hasDisplay && !glasses.canControl) { Note(stringResource(R.string.setup_glasses_connect)) } else { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt index c13bebef13..7000bb936f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt @@ -76,7 +76,7 @@ internal fun WindowDialog( content: @Composable () -> Unit, ) { if (!LocalPresentationWindow.current) { - Dialog(onDismissRequest, properties, content) + Dialog(onDismissRequest, properties) { SolidSurfaces(content) } return } Popup( @@ -87,7 +87,7 @@ internal fun WindowDialog( Modifier.fillMaxSize().background(androidx.compose.ui.graphics.Color.Black.copy(alpha = 0.6f)) .tapOutside { if (properties.dismissOnClickOutside) onDismissRequest() }, contentAlignment = Alignment.Center, - ) { content() } + ) { SolidSurfaces(content) } } } @@ -150,7 +150,7 @@ internal fun GlidePopup( ) { Popup(popupPositionProvider, onDismissRequest, properties) { if (properties.focusable) TrackKeyWindow() - FocusGlideHost(content = content) + SolidSurfaces { FocusGlideHost(content = content) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt index 2fe1346034..1274945a3b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -174,14 +174,15 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe detail = if (library.usersOfBindings(b.id).size > 1) stringResource(R.string.input_shared_detail, b.name, library.usersOfBindings(b.id).size) else "${profile.name} · ${roleLabel(role)}", onSave = { action -> if (update { l -> + val currentPreset = l.preset(editing.preset) val geometry = if (!editing.click && elementProperties != null && layout != null) l.withLayout(layout.copy(elements = layout.elements.map { if (it.id == elementProperties!!.id) elementProperties!!.copy(name = elementProperties!!.name.trim().ifBlank { it.name }) else it })) else l geometry.withPreset(when { - editing.element != null && editing.click -> b.copy(clicks = b.clicks + (editing.element.id to action)) - editing.element != null -> b.copy(elements = b.elements + (editing.element.id to action)) - editing.key != null -> b.copy(keys = b.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action)) - else -> b.copy(controls = b.controls + (editing.control to action)) + editing.element != null && editing.click -> currentPreset.copy(clicks = currentPreset.clicks + (editing.element.id to action)) + editing.element != null -> currentPreset.copy(elements = currentPreset.elements + (editing.element.id to action)) + editing.key != null -> currentPreset.copy(keys = currentPreset.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action)) + else -> currentPreset.copy(controls = currentPreset.controls + (editing.control to action)) }) }) edit = null }) } else if (!surface) key(page, profileId, role) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index f06c43851c..e0d0207ff3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -44,6 +44,7 @@ import com.droiddeck.launcher.session.SessionPrefs import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.hypot +import kotlin.math.max import kotlin.math.min @SuppressLint("ViewConstructor") @@ -63,6 +64,7 @@ class InputSurfaceView( private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) } private var artworkDpad = emptyList() private val artworkDpadBounds = RectF() + private var crossDpads = emptyList, RectF>>() private var requestedLayout = customLayout init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) } @@ -185,6 +187,7 @@ class InputSurfaceView( private fun renderCustom(pad: PadBridge?) { artworkDpad = emptyList() + crossDpads = emptyList() val canvas = object : ViewGroup(context) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val layout = customLayout @@ -203,6 +206,7 @@ class InputSurfaceView( child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight) } updateArtworkDpad(this) + updateCrossDpad(this) } override fun dispatchDraw(canvas: Canvas) { @@ -244,11 +248,39 @@ class InputSurfaceView( canvas.getChildAt(index) as? HoldButton } val previous = artworkDpad - artworkDpad = if (crossed(buttons)) buttons else emptyList() + artworkDpad = if (crossed(buttons, artworkDpadBounds)) buttons else emptyList() if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() } } - private fun crossed(buttons: List): Boolean { + private fun updateCrossDpad(canvas: ViewGroup) { + val buttons = (0 until canvas.childCount).map(canvas::getChildAt).filterIsInstance() + val (ups, rights, downs, lefts) = DIRECTIONS.map { direction -> buttons.filter { (it.tag as? InputSurfaceElement)?.control == direction } } + crossDpads = ups.flatMap { up -> rights.flatMap { right -> downs.flatMap { down -> + lefts.mapNotNull { left -> listOf(up, right, down, left).let { arms -> hole(arms)?.let { arms to it } } } } } } + } + + private fun hole(buttons: List): RectF? { + val (up, right, down, left) = buttons + val hole = RectF(left.right.toFloat(), up.bottom.toFloat(), right.left.toFloat(), down.top.toFloat()) + val across = max(up.left, down.left) to min(up.right, down.right) + val along = max(left.top, right.top) to min(left.bottom, right.bottom) + return hole.takeIf { + !it.isEmpty && across.first < across.second && along.first < along.second && + across.first < it.right && across.second > it.left && along.first < it.bottom && along.second > it.top + } + } + + private fun crossTarget(x: Float, y: Float): HoldButton? { + val first = crossDpads.firstOrNull()?.first?.first() ?: return null + val hx = x - (originX(first) - first.left) + val hy = y - (originY(first) - first.top) + return crossDpads.filter { (arms, hole) -> arms.all { it.visibility == VISIBLE } && hole.contains(hx, hy) } + .flatMap { it.first }.distinct().minByOrNull { arm -> + hypot(max(max(arm.left - hx, hx - arm.right), 0f), max(max(arm.top - hy, hy - arm.bottom), 0f)) + } + } + + private fun crossed(buttons: List, bounds: RectF): Boolean { if (buttons.size != DIRECTIONS.size) return false val (up, right, down, left) = buttons val centerX = (left.left + right.right) / 2f @@ -258,7 +290,7 @@ class InputSurfaceView( kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f || kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f || up.bottom >= down.top || left.right >= right.left) return false - artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat()) + bounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat()) return true } @@ -284,6 +316,7 @@ class InputSurfaceView( val views = (canvas.childCount - 1 downTo 0).map(canvas::getChildAt).filter { it.visibility == VISIBLE } views.firstOrNull { !(it is StickView && it.adaptive) && hits(it, x, y, 0f) }?.let { return it } views.filter { it is HoldButton && hits(it, x, y, slack(it)) }.minByOrNull { distance(it, x, y) }?.let { return it } + crossTarget(x, y)?.let { return it } if (views.any { it is HoldButton && hits(it, x, y, slack(it) + ADAPTIVE_CLEARANCE_PX) }) return null return views.filter { it is StickView && it.adaptive && it !in owners.values && (hits(it, x, y, 0f) || it.captures(x - originX(it), y - originY(it))) } .minByOrNull { distance(it, x, y) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LauncherFrost.kt b/app/src/main/java/com/droiddeck/launcher/ui/LauncherFrost.kt new file mode 100644 index 0000000000..91f2cdf402 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/LauncherFrost.kt @@ -0,0 +1,130 @@ +package com.droiddeck.launcher.ui + +import android.app.Activity +import android.graphics.drawable.ColorDrawable +import android.os.Build +import android.os.PowerManager +import android.view.WindowManager +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.compositeOver +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.graphics.luminance +import java.util.function.Consumer + +internal val LocalFrost = staticCompositionLocalOf { null } + +internal const val FROST_MAX = 100 +internal const val FROST_STEP = 10 +internal const val FROST_DEFAULT = 50 +internal const val FROST_WALLPAPER_DEFAULT = 80 +private const val FROST_TEXT_LIFT = 0.5f +private const val FROST_LIFT_STEPS = 5 +private const val FROST_TINT_MAX = 0.9f +private const val FROST_SEARCH_STEPS = 12 +private const val FROST_BLUR_DP = 28 + +private class FrostScale(val solid: Float, val default: Float, val clear: Float) { + fun at(percent: Int): Float { + val t = percent.coerceIn(0, FROST_MAX) / FROST_DEFAULT.toFloat() + return if (t <= 1f) solid + (default - solid) * t else default + (clear - default) * (t - 1f) + } +} + +private val TINT_DARK = FrostScale(0.9f, 0.58f, 0.32f) +private val TINT_LIGHT = FrostScale(0.94f, 0.7f, 0.48f) +private val CARD_DARK = FrostScale(1f, 0.6f, 0.3f) +private val CARD_LIGHT = FrostScale(1f, 0.74f, 0.45f) +private val TEXT_LIFT_MAX = FrostScale(FROST_TEXT_LIFT, FROST_TEXT_LIFT, 1f) + +class FrostChoice( + val transparency: Int = FROST_WALLPAPER_DEFAULT, + val cards: Boolean = false, + val cardTransparency: Int = FROST_DEFAULT, +) + +internal class FrostLook(val veil: Color, val lift: Float, val cardAlpha: Float) + +internal fun frostLook(palette: Palette, choice: FrostChoice): FrostLook { + val light = palette.background.luminance() > 0.5f + val cardAlpha = if (!choice.cards) 1f else (if (light) CARD_LIGHT else CARD_DARK).at(choice.cardTransparency) + val maxLift = maxOf(TEXT_LIFT_MAX.at(choice.transparency), if (choice.cards) TEXT_LIFT_MAX.at(choice.cardTransparency) else 0f) + // Android reports only the wallpaper's main colours, and any part of it can sit behind text. + fun readable(alpha: Float, lift: Float): Boolean = listOf(Color.Black, Color.White).all { behind -> + val page = palette.background.copy(alpha = alpha).compositeOver(behind) + val card = palette.surface.copy(alpha = cardAlpha).compositeOver(page) + val hint = lerp(palette.onSurfaceVariant, palette.onBackground, lift) + minOf(ThemeColors.contrast(hint, page), ThemeColors.contrast(hint, card)) >= ThemeColors.MIN_CONTRAST + } + var low = 0f + var high = FROST_TINT_MAX + if (readable(low, maxLift)) high = low + else if (!readable(high, maxLift)) high = 1f + else repeat(FROST_SEARCH_STEPS) { + val mid = (low + high) / 2 + if (readable(mid, maxLift)) high = mid else low = mid + } + val lifts = (0..FROST_LIFT_STEPS).map { FROST_TEXT_LIFT + (maxLift - FROST_TEXT_LIFT) * it / FROST_LIFT_STEPS } + val tint = maxOf((if (light) TINT_LIGHT else TINT_DARK).at(choice.transparency), kotlin.math.ceil(high * 255f) / 255f) + val alpha = if (lifts.any { readable(tint, it) }) tint else 1f + val lift = lifts.firstOrNull { readable(alpha, it) } ?: maxLift + return FrostLook(palette.background.copy(alpha = alpha), lift, cardAlpha) +} + +internal fun Palette.frosted(look: FrostLook): Palette = Palette( + id, label, detail, + background = background, + surface = if (look.cardAlpha < 1f) surface.copy(alpha = look.cardAlpha) else surface, + surfaceVariant = if (look.cardAlpha < 1f) surfaceVariant.copy(alpha = look.cardAlpha) else surfaceVariant, + line = line, line2 = line2, + onBackground = onBackground, onSurfaceVariant = lerp(onSurfaceVariant, onBackground, look.lift), + primary = primary, primary2 = primary2, onPrimary = onPrimary, signal = signal, + good = good, error = error, warning = warning, +) + + +internal class LauncherFrost(private val activity: Activity) { + var available by mutableStateOf(false) + private set + var prepared = false + private set + + private var stopListening: (() -> Unit)? = null + + val supported: Boolean + get() = Build.VERSION.SDK_INT >= 31 && + (available || activity.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true) + + fun start() { + if (Build.VERSION.SDK_INT < 31 || stopListening != null) return + val windows = activity.windowManager + val blur = Consumer { available = it } + available = windows.isCrossWindowBlurEnabled + windows.addCrossWindowBlurEnabledListener(blur) + stopListening = { windows.removeCrossWindowBlurEnabledListener(blur) } + } + + fun stop() { + stopListening?.invoke() + stopListening = null + } + + // A window made see-through after its first frame keeps drawing over its old frames, so this runs before setContent. + fun prepare(on: Boolean) { + prepared = on && Build.VERSION.SDK_INT >= 31 + if (prepared) activity.window.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT)) + } + + fun show(on: Boolean) { + if (!prepared || Build.VERSION.SDK_INT < 31) return + val window = activity.window + val flags = WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER or WindowManager.LayoutParams.FLAG_BLUR_BEHIND + if (on) window.addFlags(flags) else window.clearFlags(flags) + window.attributes = window.attributes.apply { + blurBehindRadius = if (on) (FROST_BLUR_DP * activity.resources.displayMetrics.density).toInt() else 0 + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index 4a7575d275..20e61f1d1f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -17,6 +17,7 @@ import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row @@ -204,9 +205,9 @@ internal object LibraryDisplay { val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f) var level by mutableIntStateOf(DEFAULT_LEVEL) private set - var title by mutableStateOf(true) + var title by mutableStateOf(false) private set - var size by mutableStateOf(true) + var size by mutableStateOf(false) private set fun load(context: android.content.Context) { @@ -531,13 +532,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val grid = remember { LazyGridState() } val detailScroll = rememberScrollState() var cycled by remember { mutableIntStateOf(0) } - var gridFocused by remember { mutableStateOf(false) } LaunchedEffect(source, sort) { grid.scrollToItem(0) } LaunchedEffect(cycled) { if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect - focusWithinFrames({ gridFocused }) { - if (ff.firstTileAttached > 0) ff.firstTile else ff.items["libchip:$source"] ?: FocusRequester.Default - } + val chip = "libchip:$source" + holdFocus({ ff.last == chip }) { ff.items[chip] } } CardDetailHost( open, detailScroll, @@ -563,7 +562,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, else { focusManager.clearFocus(force = true); onSelect(it) } }, searchCleared = open != null, - onFocus = { gridFocused = it }, + onFocus = {}, soundMode = soundMode, wallArt = { wallTiles(all.filterNot(concealed).mapNotNull { entryArt(it, tall = true) }) }, emptyText = when { @@ -753,20 +752,23 @@ private fun LibraryGrid( } } } + val manage = !soundMode && !s.shortcutPicker LazyVerticalGrid( columns = if (listMode) GridCells.Fixed(1) else remember(baseWidth, level) { LevelCells(baseWidth, level) }, state = grid, - modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup().bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }).onSizeChanged { - val gap = with(density) { 10.dp.roundToPx() } - columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level) - gridH = it.height - }, + modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup() + .then(if (sourceChipsShown(sources, manage)) Modifier.bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }) else Modifier) + .onSizeChanged { + val gap = with(density) { 10.dp.roundToPx() } + columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level) + gridH = it.height + }, horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), ) { val header: @Composable () -> Unit = { LibraryHeader(s, a, if (soundMode) total else visible.size + hiddenUninstalled, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections, source = source) } - val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage = !soundMode && !s.shortcutPicker) } + val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage) } item(key = if (soundMode) "header" else "filters", span = { GridItemSpan(maxLineSpan) }) { Box(Modifier.onSizeChanged { chipsH = it.height }) { Rise(0) { if (soundMode) header() else filters() } } } @@ -908,10 +910,13 @@ private fun LibraryHeader( if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() } } +private fun sourceChipsShown(sources: List, manage: Boolean): Boolean = + (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN + @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable -private fun LibraryFilters(sources: List, source: String, onSource: (String) -> Unit, manage: Boolean) { - val chips = (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN +internal fun LibraryFilters(sources: List, source: String, onSource: (String) -> Unit, manage: Boolean) { + val chips = sourceChipsShown(sources, manage) if (!chips && !manage) return val pal = LocalPalette.current val keys = if (chips) listOf(LIBRARY_ALL) + sources else emptyList() @@ -927,42 +932,54 @@ private fun LibraryFilters(sources: List, source: String, onSource: (Str horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp), ) { - Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { - for (id in keys) { - val store = Store.byId(id) - val dot = sourceDot(id) - val label = when (id) { - LIBRARY_ALL -> stringResource(R.string.stores_tab_all) - Library.ADDED -> stringResource(R.string.library_custom_games) - LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites) - LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden) - else -> store?.shortLabel ?: sourceLabel(id) - } - androidx.compose.runtime.key(id) { - val reveal = remember { BringIntoViewRequester() } - LaunchedEffect(source) { if (source == id) reveal.bringIntoView() } - StoreChip( - label = label, on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal, - modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id") - .onGloballyPositioned { bounds[id] = it.boundsInParent() }, - lead = { - if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape)) - else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp)) - }, - onFocused = { focused = it }, - paneKey = "libchip:$id", - ) { onSource(id) } + BoxWithConstraints(Modifier.weight(1f)) { + if (sourceTabsAsMenu(maxWidth, keys.size)) { + TabMenu( + keys.map { librarySourceChipLabel(it) }, keys.indexOf(source), { onSource(keys[it]) }, + chipModifier = Modifier.paneItem("libchip:$source"), + leading = { i, _ -> LibrarySourceMark(sourceDot(keys[i])) }, + ) + } else Box(Modifier.edgeFade(scroll).horizontalScroll(scroll)) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { + for (id in keys) { + val dot = sourceDot(id) + androidx.compose.runtime.key(id) { + val reveal = remember { BringIntoViewRequester() } + LaunchedEffect(source) { if (source == id) reveal.bringIntoView() } + StoreChip( + label = librarySourceChipLabel(id), on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal, + modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id") + .onGloballyPositioned { bounds[id] = it.boundsInParent() }, + lead = { LibrarySourceMark(dot) }, + onFocused = { focused = it }, + paneKey = "libchip:$id", + ) { onSource(id) } + } } } + if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } - if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } if (manage) ManageStoresChip() } } } +@Composable +private fun librarySourceChipLabel(id: String): String = when (id) { + LIBRARY_ALL -> stringResource(R.string.stores_tab_all) + Library.ADDED -> stringResource(R.string.library_custom_games) + LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites) + LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden) + else -> Store.byId(id)?.shortLabel ?: sourceLabel(id) +} + +@Composable +private fun LibrarySourceMark(dot: Color?) { + if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape)) + else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp)) +} + @Composable private fun sourceTitle(src: String): String = when (src) { LIBRARY_ALL -> stringResource(R.string.library_all_games) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index 66f6ea110a..6769798ad9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -711,6 +711,10 @@ internal fun SheetChips( Modifier.fillMaxWidth().onFocusChanged { within = it.hasFocus }, contentAlignment = Alignment.CenterStart, ) { + if (tabsAsMenu(maxWidth, labels.size)) { + TabMenu(labels, selected, onPick, focus = chips) + return@BoxWithConstraints + } val equal = !width.isSpecified && maxWidth / labels.size.coerceAtLeast(1) >= 96.dp val least = if (width.isSpecified) maxOf(width, 64.dp) else 64.dp val scroll = rememberScrollState() 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 3509d0a83d..2f0cc48a1f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -62,6 +62,7 @@ class ModeSettings( val hdrReason: String?, val hdrDisplay: Boolean = true, val zeroCopy: Boolean = true, + val producerAcquireFences: Boolean? = null, val gpuDrivers: String? = null, val upscaler: Int = 0, val upscaleSharpness: Int = 75, @@ -86,7 +87,8 @@ class ModeSettings( val fexPreset: String? = null, val forceSsbs: Boolean = false, val syncBackend: String? = null, - val picturePosition: String? = null, + val picturePositionLandscape: String? = null, + val picturePositionPortrait: String? = null, val integerScaling: Boolean? = null, val stretch16x9: Boolean? = null, val avoidNotch: Boolean? = null, @@ -125,6 +127,7 @@ class ModeSettingsActions( val onResolutionPortrait: (String) -> Unit = {}, val onHdr: (Boolean) -> Unit, val onZeroCopy: (Boolean) -> Unit = {}, + val onProducerAcquireFences: (Boolean) -> Unit = {}, val onGpuDrivers: () -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, @@ -150,7 +153,7 @@ class ModeSettingsActions( val onFexPreset: (String) -> Unit = {}, val onForceSsbs: (Boolean) -> Unit = {}, val onSyncBackend: (String) -> Unit = {}, - val onPicturePosition: (String) -> Unit = {}, + val onPicturePosition: (Boolean, String) -> Unit = { _, _ -> }, val onIntegerScaling: (Boolean) -> Unit = {}, val onStretch16x9: (Boolean) -> Unit = {}, val onAvoidNotch: (Boolean) -> Unit = {}, @@ -260,15 +263,16 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: ResolutionRow(host, "resolution-portrait", stringResource(R.string.display_resolution_portrait), s.resolutionPortrait, portraitChoice, com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE, if (sessionDisplay.isLink(s.resolution)) portraitChoice else sessionDisplay.orientCustom(s.resolution, true), - s.panelSize, a.onResolutionPortrait, portrait = true) - s.picturePosition?.let { position -> - ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null, - listOf("top" to stringResource(R.string.display_position_top), - "bottom" to stringResource(R.string.display_position_bottom), - "left" to stringResource(R.string.display_position_left), - "right" to stringResource(R.string.display_position_right), - "center" to stringResource(R.string.display_position_center)), - position, onPick = a.onPicturePosition) + s.panelSize, a.onResolutionPortrait, portrait = true, + defaultChoice = if (s.mode == SessionService.MODE_STEAM) sessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION + else sessionDisplay.DEFAULT_RESOLUTION) + s.picturePositionLandscape?.let { position -> + PicturePositionRow(host, position, key = "picture-position-landscape", + labelRes = R.string.display_picture_position_landscape) { a.onPicturePosition(false, it) } + } + s.picturePositionPortrait?.let { position -> + PicturePositionRow(host, position, key = "picture-position-portrait", + labelRes = R.string.display_picture_position_portrait) { a.onPicturePosition(true, it) } } if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) || com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) { @@ -284,6 +288,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch) } ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy) + s.producerAcquireFences?.let { enabled -> + ToggleRow(host, "producer-acquire-fences", stringResource(R.string.producer_acquire_fences), + stringResource(R.string.producer_acquire_fences_summary), checked = enabled, + onChange = a.onProducerAcquireFences) + } } SettingsGroup(stringResource(R.string.display_image_scaling)) { s.integerScaling?.let { enabled -> @@ -735,3 +744,22 @@ internal fun CustomFollowScaleDialog(initial: Float?, onSave: (Float) -> Unit, o dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } + +@Composable +internal fun PicturePositionRow( + host: MenuHost, position: String, + chipModifier: Modifier = Modifier, + key: String = "picture-position", + @androidx.annotation.StringRes labelRes: Int = R.string.display_picture_position, + onPick: (String) -> Unit, +) { + ChoiceRow(host, key, stringResource(labelRes), null, + listOf( + "center" to stringResource(R.string.display_position_center), + "top" to stringResource(R.string.display_position_top), + "bottom" to stringResource(R.string.display_position_bottom), + "left" to stringResource(R.string.display_position_left), + "right" to stringResource(R.string.display_position_right), + ), + position, chipModifier = chipModifier, onPick = onPick) +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index 2fa5d01cbd..dcf1050ee7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -116,10 +116,7 @@ internal object NavTabs { fun more(s: FrontEndState) = listed(s).filter { place(s, it) == TabPlace.MORE } - fun bar(s: FrontEndState): List { - val shown = listed(s).filter { place(s, it) == TabPlace.BAR } - return if (more(s).isEmpty()) shown else shown + MORE - } + fun bar(s: FrontEndState): List = listed(s).filter { place(s, it) == TabPlace.BAR } + MORE fun setHidden(context: Context, key: String, hide: Boolean) { hidden = if (hide && hideable(key)) hidden + key else hidden - key diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt index 5c40727031..bd63dce034 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt @@ -8,6 +8,9 @@ import com.droiddeck.launcher.input.PcKey import androidx.compose.ui.res.stringResource import android.view.KeyEvent import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -69,6 +72,9 @@ fun PcKeyboard( sendKey: (Int, Boolean) -> Unit, onAndroidKeyboard: () -> Unit, onClose: () -> Unit, + heightFraction: Float? = null, + showButtons: Boolean = true, + hoverFeedback: Boolean = false, ) { val pal = LocalPalette.current val colors = MaterialTheme.colorScheme @@ -76,31 +82,40 @@ fun PcKeyboard( var capsOn by remember { mutableStateOf(false) } val firstKey = remember { FocusRequester() } val shifted = (mods[42] ?: MOD_OFF) != MOD_OFF || (mods[54] ?: MOD_OFF) != MOD_OFF + // Keys go to wherever sendKey points now, but a held key is let go where it went down. + val currentSend by androidx.compose.runtime.rememberUpdatedState(sendKey) + val heldAt = remember { mutableMapOf Unit>() } + fun down(code: Int) { + val send = currentSend + heldAt[code] = send + send(code, true) + } + fun up(code: Int) = (heldAt.remove(code) ?: currentSend)(code, false) fun releaseOnceModifiers() { - for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF } + for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { up(code); mods[code] = MOD_OFF } } fun press(key: PcKey) { if (key.code in PC_MODIFIERS) { when (mods[key.code] ?: MOD_OFF) { - MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE } + MOD_OFF -> { down(key.code); mods[key.code] = MOD_ONCE } MOD_ONCE -> mods[key.code] = MOD_LOCKED - else -> { sendKey(key.code, false); mods[key.code] = MOD_OFF } + else -> { up(key.code); mods[key.code] = MOD_OFF } } return } - sendKey(key.code, true) + down(key.code) } fun release(key: PcKey) { if (key.code in PC_MODIFIERS) return - sendKey(key.code, false) + up(key.code) if (key.code == 58) capsOn = !capsOn releaseOnceModifiers() } androidx.compose.runtime.DisposableEffect(Unit) { - onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) } + onDispose { for (code in heldAt.keys.toList()) up(code) } } - LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } } + LaunchedEffect(Unit) { if (!hoverFeedback) runCatching { firstKey.requestFocus() } } val prefsContext = LocalContext.current remember { PcKeyboardPrefs.load(prefsContext) } @@ -108,7 +123,7 @@ fun PcKeyboard( val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() } BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) { - val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size) + val rowHeight = ((maxHeight * (heightFraction ?: (PcKeyboardPrefs.size / 100f)) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size) .coerceIn(20.dp, 56.dp) Box( Modifier.fillMaxWidth() @@ -122,9 +137,11 @@ fun PcKeyboard( Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(24.dp)) { Text(stringResource(R.string.drawer_pc_keyboard), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant) Spacer(Modifier.weight(1f)) - HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard) - Spacer(Modifier.width(8.dp)) - HeaderButton(stringResource(R.string.pckb_hide), onClose) + if (showButtons) { + HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard) + Spacer(Modifier.width(8.dp)) + HeaderButton(stringResource(R.string.pckb_hide), onClose) + } } rows.forEachIndexed { r, row -> Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) { @@ -139,7 +156,7 @@ fun PcKeyboard( } key(key.code) { KeyCap( - label, key.weight, lit, locked = state == MOD_LOCKED, + label, key.weight, lit, locked = state == MOD_LOCKED, hoverFeedback = hoverFeedback, modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier, onDown = { press(key) }, onUp = { release(key) }, ) @@ -154,25 +171,35 @@ fun PcKeyboard( @Composable private fun RowScope.KeyCap( - label: String, weight: Float, lit: Boolean, locked: Boolean, + label: String, weight: Float, lit: Boolean, locked: Boolean, hoverFeedback: Boolean, modifier: Modifier, onDown: () -> Unit, onUp: () -> Unit, ) { val pal = LocalPalette.current val src = remember { MutableInteractionSource() } val focused by src.collectIsFocusedAsState() + val hovered by src.collectIsHoveredAsState() + val (pointedAt, laser) = com.droiddeck.launcher.session.xr.rememberXrPointed() + val pointed = hoverFeedback && (hovered || laser.value) var down by remember { mutableStateOf(false) } val fill by animateColorAsState( when { down -> pal.signal.copy(alpha = 0.55f) lit -> pal.signal.copy(alpha = if (locked) 0.45f else 0.28f) + pointed -> Color.White.copy(alpha = 0.2f) else -> Color.White.copy(alpha = 0.07f) - }, Motion.tw(160), label = "keyFill", + }, Motion.tw(if (down) 40 else 160), label = "keyFill", + ) + val scale by animateFloatAsState( + if (!hoverFeedback) 1f else if (down) 0.9f else if (pointed) 1.06f else 1f, Motion.tw(if (down) 40 else 140), label = "keyScale", ) Box( contentAlignment = Alignment.Center, modifier = modifier.weight(weight).fillMaxHeight() + .then(pointedAt) + .graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale } .background(fill, RoundedCornerShape(7.dp)) - .glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f)) + .glideBorder(if (hoverFeedback) pointed || down else focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f)) + .then(if (hoverFeedback) Modifier.hoverable(src) else Modifier) .pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PenSettingsGroup.kt b/app/src/main/java/com/droiddeck/launcher/ui/PenSettingsGroup.kt index 646c8cfcc6..772c6cc27c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PenSettingsGroup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PenSettingsGroup.kt @@ -11,7 +11,7 @@ internal fun PenSettingsGroup( host: MenuHost, pen: SessionPrefs.Pen, track: (String) -> Modifier = { Modifier }, onPick: (key: String, value: String) -> Unit, ) { - SettingsGroup(stringResource(R.string.mode_pen)) { + SettingsGroup(stringResource(R.string.mode_pen), key = "controller-pen") { ChoiceRow(host, "pen", stringResource(R.string.mode_pen), null, listOf(SessionPrefs.PEN_MOUSE to stringResource(R.string.mode_pen_mouse), SessionPrefs.PEN_TOUCH to stringResource(R.string.mode_pen_touch)), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt index 0c3947f986..69aa3c6f97 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt @@ -49,6 +49,7 @@ fun PerformancePage( prootNoSeccomp: Boolean, prootFastPath: Boolean, nativeUserland: Boolean, + desktopAsUser: Boolean, cursorComposite: Boolean, guestHostname: String, phantomWarning: String?, @@ -67,6 +68,7 @@ fun PerformancePage( onProotNoSeccomp: (Boolean) -> Unit, onProotFastPath: (Boolean) -> Unit, onNativeUserland: (Boolean) -> Unit, + onDesktopAsUser: (Boolean) -> Unit, onCursorComposite: (Boolean) -> Unit, onGuestHostname: (String) -> Unit, onClientCore: (Int, Boolean) -> Unit, @@ -194,6 +196,12 @@ fun PerformancePage( modifier = Modifier.width(220.dp).focusGlide(), ) } + ToggleRow( + host, "desktopasuser", stringResource(R.string.perf_desktop_as_user), + stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native), + desktopAsUser && nativeUserland, enabled = nativeUserland, + onChange = onDesktopAsUser, + ) } if (phantomWarning != null) { Spacer(Modifier.height(16.dp)) @@ -218,7 +226,7 @@ fun PerformancePage( @Composable internal fun GpuClockGroup(host: MenuHost, on: Boolean, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) { - SettingsGroup(stringResource(R.string.perf_gpu)) { + SettingsGroup(stringResource(R.string.perf_gpu), key = "performance-gpu") { ToggleRow( host, "gpuclock", stringResource(R.string.perf_gpuclock), null, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt index ca9ca5976c..34121eb342 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt @@ -16,12 +16,14 @@ fun ResolutionRow( panel: Pair, onPick: (String) -> Unit, chipModifier: Modifier = Modifier, portrait: Boolean = false, + defaultChoice: String = SessionDisplay.DEFAULT_RESOLUTION, ) { val custom = "custom" val linked = stored == link val size = SessionDisplay.resolveChoice(panel, choice, portrait) val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait) - val choices = SessionDisplay.resolutionOptions(panel) + val presets = SessionDisplay.resolutionOptions(panel) + val choices = if (defaultChoice == SessionDisplay.DEFAULT_RESOLUTION) presets else listOf(defaultChoice) + presets val customFollow = !linked && SessionDisplay.isFollow(choice) && choice !in choices val selected = if (linked) link else if (SessionDisplay.isFollow(choice)) choice else if (size == screen) SessionDisplay.MATCH_SCREEN else choice @@ -36,7 +38,7 @@ fun ResolutionRow( else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen) else if (SessionDisplay.isFollow(value)) stringResource(R.string.display_follow_screen_scaled, SessionDisplay.formatScale(SessionDisplay.followScale(value) ?: 1f)) + " (${dimensions.first}×${dimensions.second})" - else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}") + else if (value == defaultChoice) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}") else "${dimensions.first}×${dimensions.second}" } + listOf(SessionDisplay.FOLLOW_CUSTOM to stringResource(R.string.display_follow_screen_scaled, if (customFollow) SessionDisplay.formatScale(SessionDisplay.followScale(choice) ?: 1f) else "…" diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt index 20c942dea6..d61e51bdd7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.ui import android.content.Context +import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.compose.foundation.gestures.awaitEachGesture @@ -48,10 +49,18 @@ internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Fl val insideX = x >= origin[0] - margin && x <= origin[0] + field.width + margin val insideY = y >= origin[1] - margin && y <= origin[1] + field.height + margin if (insideX && insideY) return + releaseTextField(field) +} + +internal fun releaseTextField(field: EditText) { field.clearFocus() (field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0) } +internal fun releaseFocusedTextField(view: View) { + (view.rootView.findFocus() as? EditText)?.let(::releaseTextField) +} + /** A dialog's touches never reach the activity, so a dialog holding a search field counts its taps and releases the field itself. */ internal fun Modifier.releaseTextFieldOnTap(): Modifier = composed { val view = LocalView.current 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 73df657efe..508c0f4ea9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -22,9 +22,11 @@ import androidx.compose.material.icons.outlined.Tune import androidx.lifecycle.setViewTreeLifecycleOwner import androidx.lifecycle.setViewTreeViewModelStoreOwner import androidx.savedstate.setViewTreeSavedStateRegistryOwner +import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.DeckPanel import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.PadBridge +import com.droiddeck.launcher.wayland.WaylandCompositor import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.SessionActivity import com.droiddeck.launcher.session.BottomDesktop @@ -396,6 +398,7 @@ class SecondScreenPresentation( val layout = panelLayout(mode) val controls = InputSurfaceView(context, pad, layout?.elements.orEmpty(), surfaceStyle = layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) + controls.alpha = ControllerPrefs.onScreenOpacity(context) / 100f controlsView = controls root.addView(controls, weightParams()) attachKeyboard() @@ -490,12 +493,19 @@ class SecondScreenPresentation( } private fun attachKeyboard() { - val host = KeyboardHost(context) { event -> - val handled = sessionActivity.dispatchKeyEvent(event) - if (fieldKeyboard && event.action == KeyEvent.ACTION_UP && - (event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() } - handled - } + val host = KeyboardHost( + context, + sendKeyEvent = { event -> + val handled = sessionActivity.dispatchImeKeyEvent(event) + if (fieldKeyboard && event.action == KeyEvent.ACTION_UP && + (event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() } + handled + }, + sendText = { text -> + WaylandCompositor.textInputCommit(text) + if (fieldKeyboard && text == "\r") root.post { closeFieldKeyboard() } + }, + ) host.onImeChanged = { visible -> if (!visible && keyboardShown.value) keyboardClosed() } keyboardHost = host root.addView(host, ViewGroup.LayoutParams(1, 1)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index b2bc10c8a4..f9e8924c8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -6,21 +6,28 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.session.SessionPrefs +/** HUD holds the Performance page and GAMES the Game page; the names stay because saved page orders use them. */ internal enum class SessionDrawerPage(val firstControl: String) { - CONTROLLER("input-profile"), - GLASSES("glasses-game"), - DISPLAY("fg"), - HUD("hud"), - EFFECTS("look"), - GAMES("anisotropy"), - AGENT("agent-input"), - SESSION("suspend"), + CONTROLLER("section-controller-input"), + HUD("section-performance-pacing"), + FRAMEGEN("fg"), + DISPLAY("section-display"), + EFFECTS("section-effects-look"), + GAMES("section-game-profile"), + VR("section-vr-steamvr"), + SESSION("pause"), MORE("more-edit"), - VR("steamvr"), + ACHIEVEMENTS("achievements"), + AGENT("agent-input"), } internal object DrawerPages { - var order by mutableStateOf(SessionDrawerPage.entries.toList()) + private val defaultOrder = SessionDrawerPage.entries.toMutableList().apply { + remove(SessionDrawerPage.VR) + add(indexOf(SessionDrawerPage.MORE) + 1, SessionDrawerPage.VR) + }.toList() + + var order by mutableStateOf(defaultOrder) private set var hidden by mutableStateOf(emptySet()) private set @@ -37,6 +44,7 @@ internal object DrawerPages { } fun arrange(saved: List): List { + if (saved.isEmpty()) return defaultOrder val all = SessionDrawerPage.entries val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList() for (page in all.filterNot { it in out }) { @@ -60,27 +68,27 @@ internal object DrawerPages { } fun reset(context: Context) { - order = SessionDrawerPage.entries.toList() + order = defaultOrder hidden = emptySet() if (DevPreview.drawer != null) return SessionPrefs.setDrawerPageOrder(context, order.map { it.name }) SessionPrefs.setDrawerPageHidden(context, emptySet()) } - fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty() + fun isDefault() = order == defaultOrder && hidden.isEmpty() } internal fun offeredDrawerPages( - hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, + hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, ): List = DrawerPages.order.filter { - (hasGlasses || it != SessionDrawerPage.GLASSES) && + (hasAchievements || it != SessionDrawerPage.ACHIEVEMENTS) && (hasAgent || it != SessionDrawerPage.AGENT) } internal fun sessionDrawerPages( - hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, -): List = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden } + hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, +): List = offeredDrawerPages(hasAchievements, hasAgent).filter { it !in DrawerPages.hidden } /** The pages shown as tabs: everything up to and including the More tab. */ internal fun List.strip(): List { 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 de4e460b30..da18b4e166 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -18,9 +18,11 @@ import androidx.compose.ui.input.key.type import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection import kotlin.math.roundToInt import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay @@ -37,6 +39,7 @@ import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.Keyboard import androidx.compose.material.icons.outlined.AutoFixHigh import androidx.compose.material.icons.outlined.ExpandMore +import androidx.compose.material.icons.outlined.EmojiEvents import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.MoreHoriz import androidx.compose.material.icons.automirrored.outlined.ArrowBack @@ -88,6 +91,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Slider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -95,6 +99,7 @@ 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.vector.ImageVector import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.unit.Dp import androidx.compose.runtime.rememberUpdatedState @@ -107,6 +112,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.input.ControllerPrefs import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Spring @@ -152,6 +158,7 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.res.stringResource +import androidx.compose.ui.res.vectorResource import androidx.compose.ui.platform.LocalContext import com.droiddeck.launcher.R import com.droiddeck.launcher.core.FexPreset @@ -175,12 +182,13 @@ import java.util.Locale internal val SessionDrawerPage.title: Int get() = when (this) { SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller - SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses SessionDrawerPage.DISPLAY -> R.string.drawer_page_display - SessionDrawerPage.HUD -> R.string.drawer_hud - SessionDrawerPage.VR -> R.string.vr_title + SessionDrawerPage.HUD -> R.string.drawer_page_performance + SessionDrawerPage.FRAMEGEN -> R.string.frame_gen_title + SessionDrawerPage.VR -> R.string.drawer_page_vr SessionDrawerPage.EFFECTS -> R.string.drawer_page_effects - SessionDrawerPage.GAMES -> R.string.game_settings_title + SessionDrawerPage.GAMES -> R.string.drawer_page_game + SessionDrawerPage.ACHIEVEMENTS -> R.string.achievements_title SessionDrawerPage.AGENT -> R.string.rail_agent SessionDrawerPage.SESSION -> R.string.mode_session SessionDrawerPage.MORE -> R.string.drawer_page_more @@ -188,12 +196,13 @@ internal val SessionDrawerPage.title: Int get() = when (this) { internal val SessionDrawerPage.icon get() = when (this) { SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports - SessionDrawerPage.GLASSES -> GlassesIcon SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows SessionDrawerPage.HUD -> Icons.Outlined.Speed + SessionDrawerPage.FRAMEGEN -> Icons.Outlined.Layers SessionDrawerPage.VR -> VrHeadsetIcon SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh SessionDrawerPage.GAMES -> Icons.Outlined.Layers + SessionDrawerPage.ACHIEVEMENTS -> Icons.Outlined.EmojiEvents SessionDrawerPage.AGENT -> Icons.Outlined.Terminal SessionDrawerPage.SESSION -> Icons.Outlined.Settings SessionDrawerPage.MORE -> Icons.Outlined.MoreHoriz @@ -205,9 +214,15 @@ private class DrawerFocus { var focused by mutableStateOf(null) private set + private val sectionOrder = mutableMapOf>() + private fun requester(key: String) = requesters.getOrPut(key) { FocusRequester() } - fun track(page: SessionDrawerPage, key: String): Modifier = Modifier.focusRequester(requester(key)).onFocusChanged { + fun sections(page: SessionDrawerPage): List = sectionOrder[page]?.toList().orEmpty() + + fun track(page: SessionDrawerPage, key: String): Modifier = Modifier.focusRequester(requester(key)).also { + if (key.startsWith("section-")) sectionOrder.getOrPut(page) { LinkedHashSet() }.add(key) + }.onFocusChanged { if (it.isFocused) { last[page] = key focused = key @@ -258,6 +273,8 @@ class DrawerActions( val upscaleSharpness: Int = 75, val integerScaling: Boolean = false, val onIntegerScaling: (Boolean) -> Unit = {}, + val picturePosition: String = "center", + val onPicturePosition: (String) -> Unit = {}, val gameZoomAvailable: Boolean = false, val gameZoom: Float = 1.0f, val onGameZoom: (Float) -> Unit = {}, @@ -305,7 +322,6 @@ class DrawerActions( val hdr: Boolean = false, val hdrAvailable: Boolean = false, val onHdr: (Boolean) -> Unit = {}, - val onImportLossless: () -> Unit, val onKeyboard: () -> Unit, val onHardwareKeyboard: () -> Unit, val wowChatShown: Boolean = false, @@ -313,12 +329,15 @@ class DrawerActions( val onWowChat: (String?) -> Unit = {}, val onSteamMenu: (() -> Unit)?, val onQam: (() -> Unit)?, - val onAchievements: (() -> Unit)? = null, + val controllerConnected: Boolean = false, + val achievementsGame: com.droiddeck.launcher.stores.StoreAchievements.Game? = null, + val achievementsTitle: String? = null, val achievementsProgress: Pair? = null, val onOsc: (String) -> Unit, val onEditSteamTouch: (() -> Unit)? = null, val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null, val onControllerSize: (Int) -> Unit = {}, + val onControllerOpacity: (Int) -> Unit = {}, val onRumble: (Boolean) -> Unit = {}, val onSuspendPolicy: (String) -> Unit, val onSteamDownloadsInBackground: (Boolean) -> Unit = {}, @@ -378,6 +397,8 @@ class DrawerActions( val quickButtons: Map = emptyMap(), val onQuickButton: (com.droiddeck.launcher.input.InputCommand, Boolean) -> Unit = { _, _ -> }, val onUnfoldedControls: (Boolean) -> Unit = {}, + val deckPanel: com.droiddeck.launcher.input.DeckPanel? = null, + val onDeckPanel: (com.droiddeck.launcher.input.DeckPanel) -> Unit = {}, val unfoldedControlsWithController: Boolean = false, val onUnfoldedControlsWithController: (Boolean) -> Unit = {}, val onShareLogs: () -> Unit, @@ -418,7 +439,7 @@ class DrawerActions( @Composable internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions, docked: Boolean = false, backRequest: Int = 0, onLayerChange: (Boolean) -> Unit = {}) { - val pages = sessionDrawerPages(a.glassesPresent) + val pages = sessionDrawerPages(a.achievementsGame != null) val page = requestedPage.takeIf { it in pages } ?: pages.first() var managing by rememberSaveable { mutableStateOf(false) } var releaseSignal by remember { mutableStateOf(0) } @@ -428,11 +449,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont val pal = LocalPalette.current val host = rememberMenuHost() val (glasses, glassesSettings) = rememberGlasses() - val glassesPages = glassesTabs(glasses) + (GlassesTab.CONTROLLERS to stringResource(R.string.vr_controllers_tab)) - var selectedGlassesTab by rememberSaveable { mutableStateOf(GlassesTab.DISPLAY) } - val glassesTab = selectedGlassesTab.takeIf { key -> glassesPages.any { it.first == key } } ?: GlassesTab.DISPLAY - var androidAppsExpanded by rememberSaveable { mutableStateOf(false) } - var advancedEffectsExpanded by rememberSaveable { mutableStateOf(false) } + remember { DrawerSectionState.load(drawerContext) } var appToChooseDisplay by remember { mutableStateOf(null) } var confirmStop by remember { mutableStateOf(false) } var sheetCoords by remember { mutableStateOf(null) } @@ -440,10 +457,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont var savedWidth by remember { mutableStateOf(SessionPrefs.drawerWidthDp(widthContext)) } var stopCoords by remember { mutableStateOf(null) } val pageScroll = remember { SessionDrawerPage.entries.associateWith { ScrollState(0) } } - LaunchedEffect(glassesTab) { - if (page == SessionDrawerPage.GLASSES) host.open = null - pageScroll.getValue(SessionDrawerPage.GLASSES).scrollTo(0) - } val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil") val focus = remember { DrawerFocus() } val inputModeManager = LocalInputModeManager.current @@ -472,6 +485,13 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false } + LaunchedEffect(host.open) { + if (host.open == "frame-generation") repeat(24) { + androidx.compose.runtime.withFrameNanos { } + focus.request("frame-generation") + if (focus.focused == "frame-generation") return@LaunchedEffect + } + } LaunchedEffect(a.selectedGameProfileId) { if (host.open == "fex") host.open = null } @@ -492,7 +512,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (open && !controllerActive) focusManager.clearFocus(force = true) } var focusedPage by remember { mutableStateOf(page) } - LaunchedEffect(open, page, glassesTab, controllerActive, host.open, appToChooseDisplay, confirmStop) { + LaunchedEffect(open, page, controllerActive, host.open, appToChooseDisplay, confirmStop) { if (!open) { host.open = null confirmStop = false @@ -501,24 +521,19 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (host.open != null || appToChooseDisplay != null || confirmStop) return@LaunchedEffect val turned = page != focusedPage focusedPage = page - val first = when { - page == SessionDrawerPage.GLASSES -> "glasses-tab-$glassesTab" - page == SessionDrawerPage.SESSION && a.isHomeApp -> "apps" - else -> page.firstControl - } if (turned) focus.forget(page) - val target = focus.target(page) ?: first + val target = focus.target(page) ?: page.firstControl repeat(24) { androidx.compose.runtime.withFrameNanos { } focus.request(target) if (focus.focused == target) return@LaunchedEffect } focus.forget(page) - focus.request(first) - if (first != page.firstControl) repeat(4) { + // Which sections a page shows depends on the session, so the first one shown takes focus. + for (key in listOf(page.firstControl) + focus.sections(page)) repeat(2) { androidx.compose.runtime.withFrameNanos { } - if (focus.focused == first) return@LaunchedEffect - focus.request(page.firstControl) + focus.request(key) + if (focus.focused == key) return@LaunchedEffect } } } @@ -587,13 +602,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont focus.track(page, "screen").testTag("drawer-screen-picker"), ) } else if (roomyHeader) Spacer(Modifier.weight(1f)) - SteamActionPill( - stringResource(if (a.paused) R.string.resume_session else R.string.stores_dl_pause), - if (a.paused) Icons.Outlined.PlayArrow else Icons.Outlined.Pause, focus.track(page, "pause"), - ) { host.open = null; if (a.paused) a.onResume() else a.onPause() } - if (a.pipSupported) SteamActionPill( - stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"), - ) { host.open = null; a.onPip() } val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null val qamInteraction = remember { MutableInteractionSource() } var qamStartedOnPress by remember { mutableStateOf(false) } @@ -626,12 +634,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } } - a.onAchievements?.let { show -> - DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) { - host.open = null; show() - } - } - Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(top = 6.dp), @@ -646,14 +648,10 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) } if (managing) ManageDrawerPages( - offeredDrawerPages(a.glassesPresent), + offeredDrawerPages(a.achievementsGame != null), Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp), releaseSignal, ) { managing = false } else { - if (page == SessionDrawerPage.GLASSES) SegmentedTabs( - glassesPages, glassesTab, modifier = Modifier.fillMaxWidth().padding(top = 8.dp), - tabModifier = { key -> focus.track(page, "glasses-tab-$key").testTag("glasses-tab-$key") }, - ) { selectedGlassesTab = it } // The agent's chat scrolls itself and keeps its composer at the bottom, so it takes the height left. if (page == SessionDrawerPage.AGENT) AgentPageWithControls( Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp), @@ -663,378 +661,25 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont showControlsWithoutKeyboard = true, ) else Column( modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)), - ) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) { + ) { + val track: (String) -> Modifier = { key -> focus.track(page, key) } + val sections = remember(page) { DrawerSections(drawerContext, track) } + CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true, LocalDrawerSections provides sections) { when (page) { - SessionDrawerPage.HUD -> DroidDeckHudSettings(host, a) { key -> focus.track(page, key) } - SessionDrawerPage.DISPLAY -> { - SettingsGroup(stringResource(R.string.drawer_page_display)) { - if (a.gameZoomAvailable) SettingsRow( - stringResource(R.string.game_zoom_title), - stringResource(R.string.game_zoom_hint), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - val zoomOutEnabled = a.gameZoom > 1.0f - val zoomInEnabled = a.gameZoom < 3.0f - val zoomResetEnabled = a.gameZoom > 1.0f - val zoomOut = { a.onGameZoom((a.gameZoom - 0.25f).coerceAtLeast(1.0f)) } - val zoomIn = { a.onGameZoom((a.gameZoom + 0.25f).coerceAtMost(3.0f)) } - val zoomReset = { a.onGameZoom(1.0f) } - - OutlinedButton( - onClick = zoomOut, - enabled = zoomOutEnabled, - modifier = focus.track(page, "game-zoom-out").width(42.dp) - .controllerConfirm(enabled = zoomOutEnabled, onClick = zoomOut), - contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp), - ) { Text("−") } - Text("${(a.gameZoom * 100.0f).toInt()}%", fontSize = 12.sp) - OutlinedButton( - onClick = zoomIn, - enabled = zoomInEnabled, - modifier = focus.track(page, "game-zoom-in").width(42.dp) - .controllerConfirm(enabled = zoomInEnabled, onClick = zoomIn), - contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp), - ) { Text("+") } - OutlinedButton( - onClick = zoomReset, - enabled = zoomResetEnabled, - modifier = focus.track(page, "game-zoom-reset").width(48.dp) - .controllerConfirm(enabled = zoomResetEnabled, onClick = zoomReset), - contentPadding = PaddingValues(horizontal = 2.dp, vertical = 0.dp), - ) { Text("1×") } - } - } - val fgOpen = host.open == "fg" - val offLabel = stringResource(R.string.frame_gen_off) - val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) - SettingsRow( - stringResource(R.string.frame_gen_title), - if (a.frameGenTargetGameId != null) - "${stringResource(R.string.frame_gen_scope_game)} · ${a.frameGenTargetGameName ?: "ID ${a.frameGenTargetGameId}"}" - else stringResource(R.string.frame_gen_scope_global), - highlighted = fgOpen - ) { - Box { - ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" } - FrameGenMenu( - host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless, - gameProfileId = a.frameGenTargetGameId, - hasGameOverride = a.hasGameOverride, - onResetGame = a.onFrameGenReset, - ) - } - } - if (a.direct) SliderRow( - stringResource(R.string.drawer_frame_limit), stringResource(R.string.drawer_frame_limit_note), - a.fpsLimit.takeIf { it > 0 } ?: SessionPrefs.FPS_LIMIT_OFF, - SessionPrefs.FPS_LIMIT_OFF..SessionPrefs.FPS_LIMIT_MAX, step = 5, - format = { if (it <= SessionPrefs.FPS_LIMIT_OFF) offLabel else it.toString() }, - modifier = focus.track(page, "fps-limit"), - onChange = { a.onFpsLimit(if (it <= SessionPrefs.FPS_LIMIT_OFF) 0 else it) }) - if (a.steam && !a.direct && a.onQam != null) SettingsRow( - stringResource(R.string.drawer_frame_limit), stringResource(R.string.drawer_frame_limit_steam_hint), - ) { - DrawerOutlineButton(stringResource(R.string.drawer_open_steam_qam), modifier = focus.track(page, "fps-limit-steam")) { - host.open = null - a.onQam?.invoke() - } - } - } - SettingsGroup(stringResource(R.string.setup_orientation)) { - ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null, - SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }, - a.orientation, chipModifier = focus.track(page, "orientation"), onPick = a.onOrientation) - } - SettingsGroup(stringResource(R.string.display_image_scaling)) { - if (a.steam) SettingsRow(stringResource(R.string.display_integer_scaling), null) { - PadTextButton( - onClick = { a.onIntegerScaling(!a.integerScaling) } - ) { - Text(stringResource( - if (a.integerScaling) R.string.display_scaling_integer - else R.string.display_scaling_fit - )) - } - } - ChoiceRow(host, "upscaler", stringResource(R.string.display_filter), null, - SessionPrefs.upscalerChoices(LocalContext.current), a.upscaler, - note = stringResource(R.string.display_filter_note), - chipModifier = focus.track(page, "upscaler"), onPick = a.onUpscaler) - if (SessionPrefs.upscalerHasSharpness(a.upscaler)) SliderRow( - stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5, - format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), onChange = a.onUpscaleSharpness) - } - SecondScreenGroup(host, a) { key -> focus.track(page, key) } - } - SessionDrawerPage.EFFECTS -> { - ScreenEffectsGroup(host, a, advancedEffectsExpanded, - onAdvancedToggle = { advancedEffectsExpanded = !advancedEffectsExpanded }) { key -> focus.track(page, key) } - } - SessionDrawerPage.VR -> { - SteamVrGroup(a) { key -> focus.track(page, key) } - if (!a.glassesOutput) CardboardGroup(host, a) { key -> focus.track(page, key) } - } - SessionDrawerPage.CONTROLLER -> { - SettingsGroup(stringResource(R.string.drawer_page_controller)) { - InputQuickSettings(host, desktop = a.desktop, onChanged = a.onInputSelection, onEdit = a.onInputSettings) { key -> focus.track(page, key) } - } - SettingsGroup(stringResource(R.string.input_device_settings)) { - a.padType?.let { type -> - ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), stringResource(R.string.input_virtual_controller_hint), - listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck), - SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam), - SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4), - SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense), - SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)), - type, chipModifier = focus.track(page, "pad-type"), onPick = a.onPadType) - } - a.controller?.let { c -> - SliderRow(stringResource(R.string.ctrl_size), null, c.size, 80..125, step = 5, - format = { "$it%" }, modifier = focus.track(page, "controller-size"), - onChange = a.onControllerSize) - ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble, - chipModifier = focus.track(page, "rumble"), onChange = a.onRumble) - } - } - SettingsGroup(stringResource(R.string.input_touchscreen)) { - ChoiceRow(host, "touch", stringResource(R.string.input_touchscreen), stringResource(R.string.input_touchscreen_hint), - listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), - a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch) - if (a.touchActive == SessionPrefs.TOUCH_PAD) - RelativeMouseRow(host, a, focus.track(page, "relative-mouse")) - if (a.touchActive == SessionPrefs.TOUCH_DIRECT) - ToggleRow(host, "direct-cursor", stringResource(R.string.input_touch_cursor), - stringResource(R.string.input_touch_cursor_hint), a.directCursor, - chipModifier = focus.track(page, "direct-cursor"), onChange = a.onDirectCursor) - when (a.touchActive) { - SessionPrefs.TOUCH_GESTURES -> ActionRow(stringResource(R.string.gesture_settings), null, - stringResource(R.string.ctrl_edit), a.onGestureSettings, - modifier = focus.track(page, "gesture-settings")) - SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.input_touch_hold), stringResource(R.string.input_touch_hold_hint), - listOf(MOUSE_BEHAVIOR_NONE to stringResource(R.string.gesture_hold_left), - MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_right_click), - MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_right)), - a.directHoldBehavior, chipModifier = focus.track(page, "long-press"), - onPick = a.onDirectHoldBehavior) - } - } - a.pen?.let { PenSettingsGroup(host, it, track = { key -> focus.track(page, key) }, onPick = a.onPen) } - SettingsGroup(stringResource(R.string.input_screen_visibility)) { - ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null, - if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)) - else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), - if (!a.steam && a.oscMode == SessionPrefs.OSC_STEAM_TOUCH) SessionPrefs.OSC_AUTO else a.oscMode, - chipModifier = focus.track(page, "osc"), onPick = a.onOsc) - a.adaptiveSticks?.let { on -> - ToggleRow(host, "adaptive-sticks", stringResource(R.string.ctrl_adaptive), null, on, - chipModifier = focus.track(page, "adaptive-sticks"), onChange = a.onAdaptiveSticks) - } - if (a.showFloatingSteamControls) { - ToggleRow(host, "rear-buttons", stringResource(R.string.osc_rear_buttons), null, a.oscRearButtons, - chipModifier = focus.track(page, "rear-buttons"), onChange = a.onOscRearButtons) - ToggleRow(host, "trackpads", stringResource(R.string.osc_trackpads), null, a.oscTrackpads, - chipModifier = focus.track(page, "trackpads"), onChange = a.onOscTrackpads) - } - for ((button, shown) in a.quickButtons) { - val key = "quick-${button.name.lowercase()}" - ToggleRow(host, key, stringResource(quickButtonLabel(button)), null, shown, - chipModifier = focus.track(page, key)) { a.onQuickButton(button, it) } - } - a.onEditSteamTouch?.let { edit -> - ActionRow(stringResource(R.string.osc_steam_layout), stringResource(R.string.osc_steam_layout_hint), stringResource(R.string.ctrl_edit), edit) - } - if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), - stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, - chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls) - if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller", - stringResource(R.string.unfolded_controls_with_controller), - stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController, - chipModifier = focus.track(page, "unfolded-controls-with-controller"), - onChange = a.onUnfoldedControlsWithController) - } - SettingsGroup(stringResource(R.string.shortcuts_title)) { - if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold), - stringResource(R.string.back_hold_hint), a.backHold, - chipModifier = focus.track(page, "back-hold"), onChange = a.onBackHold) - if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.input_back_taps), stringResource(R.string.input_back_taps_hint), - listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)), - a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted) - if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null, - SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) }, - a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs) - PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") }) - if (a.secondScreenDisplays.isNotEmpty()) ToggleRow(host, "docked-menu-controller", stringResource(R.string.drawer_docked_menu_controller), - null, a.dockedMenuController, - chipModifier = focus.track(page, "docked-menu-controller"), onChange = a.onDockedMenuController) - ToggleRow(host, "corner-tap", stringResource(R.string.drawer_corner_tap), - stringResource(R.string.drawer_corner_tap_hint), a.cornerTap, - chipModifier = focus.track(page, "corner-tap"), onChange = a.onCornerTap) - } - SettingsGroup(stringResource(R.string.drawer_latency)) { - ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency), - stringResource(R.string.drawer_low_latency_hint), a.lowLatency, - chipModifier = focus.track(page, "low-latency"), onChange = a.onLowLatency) - ToggleRow(host, "evdev-mouse", stringResource(R.string.drawer_evdev_mouse), - null, a.evdevMouse, - chipModifier = focus.track(page, "evdev-mouse"), onChange = a.onEvdevMouse) - if (a.touchActive != SessionPrefs.TOUCH_PAD) - RelativeMouseRow(host, a, focus.track(page, "relative-mouse")) - } - SettingsGroup(stringResource(R.string.drawer_keyboard)) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) { - DrawerOutlineButton(stringResource(R.string.drawer_pc_keyboard), modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "hardware"))) { - host.open = null; a.onHardwareKeyboard() - } - DrawerOutlineButton(stringResource(R.string.drawer_android_keyboard), modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "android"))) { - host.open = null; a.onKeyboard() - } - } - if (a.wowChatShown) ChoiceRow( - host, "wow-chat", stringResource(R.string.wow_chat_title), null, - listOf( - null to stringResource(R.string.wow_chat_ask), - SessionPrefs.WOW_CHAT_VOICE to stringResource(R.string.wow_chat_voice), - SessionPrefs.WOW_CHAT_KEYBOARD to stringResource(R.string.pckb_android), - ), - a.wowChat, chipModifier = focus.track(page, "wow-chat"), onPick = a.onWowChat, - ) - val keyboardContext = LocalContext.current - remember { PcKeyboardPrefs.load(keyboardContext) } - SliderRow( - stringResource(R.string.pckb_size), stringResource(R.string.pckb_size_hint), - PcKeyboardPrefs.size, SessionPrefs.PC_KEYBOARD_SIZE_RANGE, step = 1, - format = { "$it%" }, modifier = focus.track(page, "pckb-size"), - onChange = { PcKeyboardPrefs.setSize(keyboardContext, it) }) - SliderRow( - stringResource(R.string.pckb_opacity), stringResource(R.string.pckb_opacity_hint), - PcKeyboardPrefs.opacity, SessionPrefs.PC_KEYBOARD_OPACITY_RANGE, step = 5, - format = { "$it%" }, modifier = focus.track(page, "pckb-opacity"), - onChange = { PcKeyboardPrefs.setOpacity(keyboardContext, it) }) - MultiRow( - host, "pckb-hidden", stringResource(R.string.pckb_hidden_keys), - stringResource(R.string.pckb_hidden_keys_hint), - listOf( - 0 to stringResource(R.string.pckb_group_function), - 1 to stringResource(R.string.pckb_group_nav), - 2 to stringResource(R.string.pckb_group_arrows), - ), - PC_KEY_GROUP_IDS.filterValues { it in PcKeyboardPrefs.hiddenKeys }.keys, - onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) }) - } - } - SessionDrawerPage.GLASSES -> if (glassesTab == GlassesTab.CONTROLLERS) { - VrControllerGroups(host) { key -> focus.track(page, key) } - } else { - GlassesGroups(host, glasses, glassesSettings, { key -> focus.track(page, key) }, onRecenter = a.onGlassesRecenter, - tab = glassesTab, outputActive = a.glassesOutput, steamVrRunning = a.steamVr == SteamVr.Status.RUNNING, - steamVr = { SteamVrRow(a) }) - } - SessionDrawerPage.GAMES -> { - if (a.steam || a.direct) SelectedGameProfileGroup(host, a) { key -> focus.track(page, key) } - Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp, - color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) - TextureFilteringGroup(host, a) { key -> focus.track(page, key) } - if (a.steam || a.direct) DrawerUpscalerGroup(host, a) { key -> focus.track(page, key) } - if (a.steam || a.direct) SettingsGroup(stringResource(R.string.game_settings_title)) { - DrawerFexPresetRow(host, a, focus.track(page, "fex")) - DrawerNoSteamRow(host, a, focus.track(page, "no-steam")) - GameEnvironmentRow( - modifier = focus.track(page, "game-env"), - showHint = false, - initialScope = a.selectedGameProfileId?.toString().orEmpty(), - ) - } - ComponentsDrawerPage(host, a) { key -> focus.track(page, key) } - ComponentDownloadsDrawerGroup( - host = host, - catalog = a.componentCatalog, - catalogAt = a.componentCatalogAt, - checking = a.componentCatalogChecking, - packages = a.components?.packages.orEmpty(), - downloads = a.componentDownloads, - onRefresh = a.onComponentCatalogRefresh, - onDownload = a.onComponentDownload, - track = { key -> focus.track(page, key) }, - ) + SessionDrawerPage.CONTROLLER -> DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track) + SessionDrawerPage.HUD -> DrawerPerformancePage(host, a, track) + SessionDrawerPage.FRAMEGEN -> DrawerFrameGenPage(host, a, track) + SessionDrawerPage.DISPLAY -> DrawerDisplayPage(host, a, track) + SessionDrawerPage.EFFECTS -> ScreenEffectsGroup(host, a, track) + SessionDrawerPage.GAMES -> DrawerGamePage(host, a, track) + SessionDrawerPage.VR -> DrawerVrPage(host, a, glasses, glassesSettings, track) + SessionDrawerPage.SESSION -> DrawerSessionPage(host, a, track) { app -> + host.open = null + if (a.secondScreenDisplays.isEmpty()) a.onLaunchAndroidApp(app, null) else appToChooseDisplay = app } + SessionDrawerPage.MORE -> DrawerMorePage(host, pages.inMore(), a, { host.open = null; onPageChange(it) }, { host.open = null; managing = true }, track) + SessionDrawerPage.ACHIEVEMENTS -> a.achievementsGame?.let { DrawerAchievementsPage(it, a.achievementsTitle, track) } SessionDrawerPage.AGENT -> Unit - SessionDrawerPage.MORE -> DrawerMorePage(host, pages.inMore(), { host.open = null; onPageChange(it) }, { host.open = null; managing = true }) { key -> focus.track(page, key) } - SessionDrawerPage.SESSION -> { - SettingsGroup(stringResource(R.string.drawer_support)) { - SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) { - DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs"), - progress = com.droiddeck.launcher.session.SessionLogShare.progress) { - host.open = null - a.onShareLogs() - } - } - } - if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps)) { - SettingsRow(stringResource(R.string.drawer_launch_app), null) { - DrawerOutlineButton(if (androidAppsExpanded) stringResource(R.string.common_hide) else stringResource(R.string.common_show), modifier = focus.track(page, "apps")) { - androidAppsExpanded = !androidAppsExpanded - } - } - if (androidAppsExpanded) { - if (a.androidApps.isEmpty()) { - Text(stringResource(R.string.drawer_no_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(stringResource(R.string.drawer_session_behavior)) { - if (a.micAvailable) ToggleRow(host, "microphone", stringResource(R.string.mode_mic), - stringResource(R.string.drawer_mic_hint), a.micEnabled, - chipModifier = focus.track(page, "microphone"), onChange = a.onMicEnabled) - ChoiceRow( - host, "suspend", stringResource(R.string.mode_suspend), - null, - listOf( - SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto), - SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual), - SessionPrefs.SUSPEND_NEVER to stringResource(R.string.common_never), - ) + if (a.steam) listOf( - SessionPrefs.SUSPEND_NATIVE to stringResource(R.string.mode_suspend_native), - ) else emptyList(), - a.suspendPolicy, - note = stringResource(if (a.steam) R.string.mode_suspend_steam_note else R.string.mode_suspend_note), - chipModifier = focus.track(page, "suspend"), - onPick = a.onSuspendPolicy, - ) - if (a.steam && a.suspendPolicy != SessionPrefs.SUSPEND_NEVER) ToggleRow( - host, "background-downloads", stringResource(R.string.mode_background_downloads), - stringResource(R.string.mode_background_downloads_hint), - a.steamDownloadsInBackground, - onChange = a.onSteamDownloadsInBackground, - ) - } - if (a.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) { - ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null, - a.pipAutoEnter, onChange = a.onPipAutoEnter) - } - Column(Modifier.fillMaxWidth().padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - if (!a.isHomeApp) DrawerActionButton(stringResource(R.string.drawer_background), Icons.AutoMirrored.Outlined.ExitToApp, - modifier = focus.track(page, "background")) { host.open = null; a.onBackground() } - } - } } } } } @@ -1079,6 +724,437 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } +@Composable +private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: Boolean, track: (String) -> Modifier) { + val on = stringResource(R.string.widgets_on) + val off = stringResource(R.string.widgets_off) + val padTag = if (padConnected) stringResource(R.string.drawer_tag_controller) else null + val noPadTag = if (padConnected) null else stringResource(R.string.drawer_tag_no_controller) + SettingsGroup(stringResource(R.string.drawer_section_input), key = "controller-input") { + InputQuickSettings(host, desktop = a.desktop, onChanged = a.onInputSelection, onEdit = a.onInputSettings, track = track) + } + val c = a.controller + val padTypes = listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck), + SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam), + SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4), + SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense), + SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)) + val rumbleLabel = stringResource(R.string.ctrl_rumble) + if (a.padType != null || c != null) SettingsGroup( + stringResource(R.string.input_device_settings), key = "controller-pad", tag = padTag, + detail = summary(a.padType?.let { padTypes.labelOf(it) }, c?.let { "$rumbleLabel ${if (it.rumble) on else off}" }), + ) { + a.padType?.let { type -> + ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), stringResource(R.string.input_virtual_controller_hint), + padTypes, type, chipModifier = track("pad-type"), onPick = a.onPadType) + } + c?.let { + ToggleRow(host, "rumble", rumbleLabel, null, it.rumble, chipModifier = track("rumble"), onChange = a.onRumble) + } + } + val oscChoices = if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)) + else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)) + val oscValue = if (!a.steam && a.oscMode == SessionPrefs.OSC_STEAM_TOUCH) SessionPrefs.OSC_AUTO else a.oscMode + SettingsGroup(stringResource(R.string.input_screen_visibility), key = "controller-osc", tag = noPadTag, + detail = summary(oscChoices.labelOf(oscValue), c?.let { "${it.size}%" })) { + ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null, oscChoices, oscValue, chipModifier = track("osc"), onPick = a.onOsc) + c?.let { + SliderRow(stringResource(R.string.ctrl_size), null, it.size, 80..125, step = 5, + format = { v -> "$v%" }, modifier = track("controller-size"), onChange = a.onControllerSize) + SliderRow(stringResource(R.string.ctrl_opacity), null, it.onScreenOpacity, ControllerPrefs.onScreenOpacityRange, step = 5, + format = { v -> "$v%" }, modifier = track("controller-opacity").testTag("controller-opacity"), + onChange = a.onControllerOpacity) + } + a.adaptiveSticks?.let { adaptive -> + ToggleRow(host, "adaptive-sticks", stringResource(R.string.ctrl_adaptive), null, adaptive, + chipModifier = track("adaptive-sticks"), onChange = a.onAdaptiveSticks) + } + if (a.showFloatingSteamControls) { + ToggleRow(host, "rear-buttons", stringResource(R.string.osc_rear_buttons), null, a.oscRearButtons, + chipModifier = track("rear-buttons"), onChange = a.onOscRearButtons) + ToggleRow(host, "trackpads", stringResource(R.string.osc_trackpads), null, a.oscTrackpads, + chipModifier = track("trackpads"), onChange = a.onOscTrackpads) + } + for ((button, shown) in a.quickButtons) { + val key = "quick-${button.name.lowercase()}" + ToggleRow(host, key, stringResource(quickButtonLabel(button)), null, shown, + chipModifier = track(key)) { a.onQuickButton(button, it) } + } + a.onEditSteamTouch?.let { edit -> + ActionRow(stringResource(R.string.osc_steam_layout), stringResource(R.string.osc_steam_layout_hint), stringResource(R.string.ctrl_edit), edit, + modifier = track("steam-touch-layout")) + } + if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), + stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, + chipModifier = track("unfolded-controls"), onChange = a.onUnfoldedControls) + a.deckPanel?.let { panel -> + ChoiceRow(host, "deck-panel", stringResource(R.string.ctrl_layout), null, + com.droiddeck.launcher.input.DeckPanel.entries.map { it to stringResource(it.label) }, panel, + chipModifier = track("deck-panel"), onPick = a.onDeckPanel) + } + if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller", + stringResource(R.string.unfolded_controls_with_controller), + stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController, + chipModifier = track("unfolded-controls-with-controller"), + onChange = a.onUnfoldedControlsWithController) + } + val touchChoices = listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)) + SettingsGroup(stringResource(R.string.input_touchscreen), key = "controller-touch", tag = noPadTag, detail = touchChoices.labelOf(a.touchMode)) { + ChoiceRow(host, "touch", stringResource(R.string.input_touchscreen), stringResource(R.string.input_touchscreen_hint), + touchChoices, a.touchMode, chipModifier = track("touch"), onPick = a.onTouch) + if (a.touchActive == SessionPrefs.TOUCH_PAD) RelativeMouseRow(host, a, track("relative-mouse")) + if (a.touchActive == SessionPrefs.TOUCH_DIRECT) + ToggleRow(host, "direct-cursor", stringResource(R.string.input_touch_cursor), + stringResource(R.string.input_touch_cursor_hint), a.directCursor, + chipModifier = track("direct-cursor"), onChange = a.onDirectCursor) + when (a.touchActive) { + SessionPrefs.TOUCH_GESTURES -> ActionRow(stringResource(R.string.gesture_settings), null, + stringResource(R.string.ctrl_edit), a.onGestureSettings, modifier = track("gesture-settings")) + SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.input_touch_hold), stringResource(R.string.input_touch_hold_hint), + listOf(MOUSE_BEHAVIOR_NONE to stringResource(R.string.gesture_hold_left), + MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_right_click), + MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_right)), + a.directHoldBehavior, chipModifier = track("long-press"), onPick = a.onDirectHoldBehavior) + } + } + a.pen?.let { PenSettingsGroup(host, it, track = track, onPick = a.onPen) } + SettingsGroup(stringResource(R.string.drawer_section_mouse), key = "controller-mouse", + detail = "${stringResource(R.string.drawer_evdev_mouse)} ${if (a.evdevMouse) on else off}") { + ToggleRow(host, "evdev-mouse", stringResource(R.string.drawer_evdev_mouse), null, a.evdevMouse, + chipModifier = track("evdev-mouse"), onChange = a.onEvdevMouse) + if (a.touchActive != SessionPrefs.TOUCH_PAD) RelativeMouseRow(host, a, track("relative-mouse")) + } + val backOrders = listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)) + SettingsGroup(stringResource(R.string.shortcuts_title), key = "controller-shortcuts", + detail = if (a.steam) summary(backOrders.labelOf(a.backActionsInverted), stringResource(R.string.back_tap_ms, a.backDoubleTapMs)) else null) { + if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold), + stringResource(R.string.back_hold_hint), a.backHold, + chipModifier = track("back-hold"), onChange = a.onBackHold) + if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.input_back_taps), stringResource(R.string.input_back_taps_hint), + backOrders, a.backActionsInverted, chipModifier = track("back-actions"), onPick = a.onBackActionsInverted) + if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null, + SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) }, + a.backDoubleTapMs, chipModifier = track("back-double-tap"), onPick = a.onBackDoubleTapMs) + PhysicalShortcutRows(modifierFor = { track("physical-shortcut-${it.name}") }) + if (a.secondScreenDisplays.isNotEmpty()) ToggleRow(host, "docked-menu-controller", stringResource(R.string.drawer_docked_menu_controller), + null, a.dockedMenuController, + chipModifier = track("docked-menu-controller"), onChange = a.onDockedMenuController) + ToggleRow(host, "corner-tap", stringResource(R.string.drawer_corner_tap), + stringResource(R.string.drawer_corner_tap_hint), a.cornerTap, + chipModifier = track("corner-tap"), onChange = a.onCornerTap) + } + val keyboardContext = LocalContext.current + remember { PcKeyboardPrefs.load(keyboardContext) } + SettingsGroup(stringResource(R.string.drawer_section_keyboard_layout), key = "controller-keyboard", + detail = summary("${PcKeyboardPrefs.size}%", "${PcKeyboardPrefs.opacity}%")) { + if (a.wowChatShown) ChoiceRow( + host, "wow-chat", stringResource(R.string.wow_chat_title), null, + listOf( + null to stringResource(R.string.wow_chat_ask), + SessionPrefs.WOW_CHAT_VOICE to stringResource(R.string.wow_chat_voice), + SessionPrefs.WOW_CHAT_KEYBOARD to stringResource(R.string.pckb_android), + ), + a.wowChat, chipModifier = track("wow-chat"), onPick = a.onWowChat, + ) + SliderRow( + stringResource(R.string.pckb_size), stringResource(R.string.pckb_size_hint), + PcKeyboardPrefs.size, SessionPrefs.PC_KEYBOARD_SIZE_RANGE, step = 1, + format = { "$it%" }, modifier = track("pckb-size"), + onChange = { PcKeyboardPrefs.setSize(keyboardContext, it) }) + SliderRow( + stringResource(R.string.pckb_opacity), stringResource(R.string.pckb_opacity_hint), + PcKeyboardPrefs.opacity, SessionPrefs.PC_KEYBOARD_OPACITY_RANGE, step = 5, + format = { "$it%" }, modifier = track("pckb-opacity"), + onChange = { PcKeyboardPrefs.setOpacity(keyboardContext, it) }) + MultiRow( + host, "pckb-hidden", stringResource(R.string.pckb_hidden_keys), + stringResource(R.string.pckb_hidden_keys_hint), + listOf( + 0 to stringResource(R.string.pckb_group_function), + 1 to stringResource(R.string.pckb_group_nav), + 2 to stringResource(R.string.pckb_group_arrows), + ), + PC_KEY_GROUP_IDS.filterValues { it in PcKeyboardPrefs.hiddenKeys }.keys, + onToggle = { id, shown -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), shown) }) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(top = 12.dp)) { + DrawerOutlineButton(stringResource(R.string.drawer_pc_keyboard), modifier = Modifier.weight(1f).height(48.dp).then(track("hardware"))) { + host.open = null; a.onHardwareKeyboard() + } + DrawerOutlineButton(stringResource(R.string.drawer_android_keyboard), modifier = Modifier.weight(1f).height(48.dp).then(track("android"))) { + host.open = null; a.onKeyboard() + } + } +} + +@Composable +private fun DrawerPerformancePage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + val offLabel = stringResource(R.string.frame_gen_off) + val limit = if (a.direct && a.fpsLimit > 0) "${stringResource(R.string.drawer_frame_limit)} ${a.fpsLimit}" else null + SettingsGroup(stringResource(R.string.drawer_section_pacing), key = "performance-pacing", detail = summary(limit)) { + if (a.direct) SliderRow( + stringResource(R.string.drawer_frame_limit), stringResource(R.string.drawer_frame_limit_note), + a.fpsLimit.takeIf { it > 0 } ?: SessionPrefs.FPS_LIMIT_OFF, + SessionPrefs.FPS_LIMIT_OFF..SessionPrefs.FPS_LIMIT_MAX, step = 5, + format = { if (it <= SessionPrefs.FPS_LIMIT_OFF) offLabel else it.toString() }, + modifier = track("fps-limit"), + onChange = { a.onFpsLimit(if (it <= SessionPrefs.FPS_LIMIT_OFF) 0 else it) }) + if (a.steam && !a.direct && a.onQam != null) SettingsRow( + stringResource(R.string.drawer_frame_limit), stringResource(R.string.drawer_frame_limit_steam_hint), + ) { + DrawerOutlineButton(stringResource(R.string.drawer_open_steam_qam), modifier = track("fps-limit-steam")) { + host.open = null + a.onQam?.invoke() + } + } + if (a.blackFrameInsertionAvailable) ToggleRow(host, "bfi", stringResource(R.string.drawer_bfi), + stringResource(R.string.drawer_bfi_note), a.blackFrameInsertion, + chipModifier = track("bfi"), onChange = a.onBlackFrameInsertion) + ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency), + stringResource(R.string.drawer_low_latency_hint), a.lowLatency, + chipModifier = track("low-latency"), onChange = a.onLowLatency) + } + DroidDeckHudSettings(host, a, track) +} + + + +@Composable +private fun DrawerFrameGenSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) + val scope = if (a.frameGenTargetGameId != null) + "${stringResource(R.string.frame_gen_scope_game)} · ${a.frameGenTargetGameName ?: "ID ${a.frameGenTargetGameId}"}" + else stringResource(R.string.frame_gen_scope_global) + + SettingsGroup(stringResource(R.string.frame_gen_title), compact = true, key = "frame-generation", detail = summary(fgLabel, scope)) { + FrameGenMenu( + mode = a.frameGen, + lossless = a.lossless, + onPick = a.onFrameGenPick, + + gameProfileId = a.frameGenTargetGameId, + hasGameOverride = a.hasGameOverride, + onResetGame = a.onFrameGenReset, + focusModifier = track("frame-generation"), + sessionHost = host, + ) + } +} + +@Composable +private fun DrawerFrameGenPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + DrawerFrameGenSettings(host, a, track) +} + + +@Composable +private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + val orientations = SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) } + SettingsGroup(stringResource(R.string.drawer_page_display), key = "display", + detail = summary(if (a.gameZoomAvailable) "${(a.gameZoom * 100.0f).toInt()}%" else null, orientations.labelOf(a.orientation))) { + if (a.gameZoomAvailable) GameZoomRow(a.gameZoom, track, a.onGameZoom) + ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null, + orientations, a.orientation, chipModifier = track("orientation"), onPick = a.onOrientation) + if (a.steam) PicturePositionRow(host, a.picturePosition, track("picture-position"), onPick = a.onPicturePosition) + } + val filters = SessionPrefs.upscalerChoices(LocalContext.current) + val integer = stringResource(if (a.integerScaling) R.string.display_scaling_integer else R.string.display_scaling_fit) + SettingsGroup(stringResource(R.string.display_image_scaling), key = "display-scaling", + detail = summary(filters.labelOf(a.upscaler), integer.takeIf { a.steam })) { + if (a.steam) SettingsRow(stringResource(R.string.display_integer_scaling), null) { + PadTextButton(onClick = { a.onIntegerScaling(!a.integerScaling) }, modifier = track("integer-scaling")) { Text(integer) } + } + ChoiceRow(host, "upscaler", stringResource(R.string.display_filter), null, filters, a.upscaler, + note = stringResource(R.string.display_filter_note), + chipModifier = track("upscaler"), onPick = a.onUpscaler) + if (SessionPrefs.upscalerHasSharpness(a.upscaler)) SliderRow( + stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5, + format = { "$it%" }, modifier = track("upscale-sharpness"), onChange = a.onUpscaleSharpness) + } + SecondScreenGroup(host, a, track) +} + +private const val GAME_ZOOM_MIN = 100 +private const val GAME_ZOOM_MAX = 300 +private const val GAME_ZOOM_STEP = 25 +private const val GAME_ZOOM_INTERVALS = (GAME_ZOOM_MAX - GAME_ZOOM_MIN) / GAME_ZOOM_STEP + +@Composable +internal fun GameZoomRow( + zoom: Float, + track: (String) -> Modifier, + onZoom: (Float) -> Unit, +) { + val source = remember { MutableInteractionSource() } + val focused by source.collectIsFocusedAsState() + val label = stringResource(R.string.game_zoom_title) + val percent = (zoom * 100f).roundToInt().coerceIn(GAME_ZOOM_MIN, GAME_ZOOM_MAX) + val value = stringResource(R.string.game_zoom_value, percent) + fun detent(value: Float): Int = ((value - GAME_ZOOM_MIN) / GAME_ZOOM_STEP).roundToInt() + val selectedDetent = detent(percent.toFloat()) + val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl + val pal = LocalPalette.current + val colors = MaterialTheme.colorScheme + + fun chooseDetent(index: Int) { + val next = GAME_ZOOM_MIN + index.coerceIn(0, GAME_ZOOM_INTERVALS) * GAME_ZOOM_STEP + if (next != percent) onZoom(next / 100f) + } + Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) { + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + Text(value, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, + color = colors.onSurface, modifier = Modifier.testTag("game-zoom-value")) + } + Slider( + value = (GAME_ZOOM_MIN + selectedDetent * GAME_ZOOM_STEP).toFloat(), + onValueChange = { chooseDetent(detent(it)) }, + valueRange = GAME_ZOOM_MIN.toFloat()..GAME_ZOOM_MAX.toFloat(), + steps = GAME_ZOOM_INTERVALS - 1, + interactionSource = source, + modifier = track("game-zoom-slider").fillMaxWidth().heightIn(min = 48.dp) + .glideBorder(focused, RoundedCornerShape(10.dp), pal.signal) + .testTag("game-zoom-slider") + .semantics { contentDescription = label; stateDescription = value } + .onPreviewKeyEvent { event -> + val delta = when (event.key) { + Key.DirectionLeft -> if (rtl) 1 else -1 + Key.DirectionRight -> if (rtl) -1 else 1 + else -> return@onPreviewKeyEvent false + } + if (event.type == KeyEventType.KeyDown && event.nativeKeyEvent.repeatCount == 0) { + chooseDetent(selectedDetent + delta) + } + true + }, + ) + } + Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) +} + +@Composable +private fun DrawerGamePage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + val colors = MaterialTheme.colorScheme + if (a.steam || a.direct) SelectedGameProfileGroup(host, a, track) + if (a.steam || a.direct) SettingsGroup(stringResource(R.string.drawer_section_compat), key = "game-compat") { + DrawerFexPresetRow(host, a, track("fex")) + DrawerNoSteamRow(host, a, track("no-steam")) + GameEnvironmentRow( + modifier = track("game-env"), + showHint = false, + initialScope = a.selectedGameProfileId?.toString().orEmpty(), + ) + Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp, + color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)) + } + TextureFilteringGroup(host, a, track) + if (a.steam || a.direct) DrawerUpscalerGroup(host, a, track) + ComponentsDrawerPage(host, a, track) + ComponentDownloadsDrawerGroup( + host = host, + catalog = a.componentCatalog, + catalogAt = a.componentCatalogAt, + checking = a.componentCatalogChecking, + packages = a.components?.packages.orEmpty(), + downloads = a.componentDownloads, + onRefresh = a.onComponentCatalogRefresh, + onDownload = a.onComponentDownload, + track = track, + ) +} + +@Composable +private fun DrawerVrPage(host: MenuHost, a: DrawerActions, glasses: com.droiddeck.launcher.glasses.GlassesState, + glassesSettings: com.droiddeck.launcher.glasses.GlassesSettings, track: (String) -> Modifier) { + val running = a.steamVr == SteamVr.Status.RUNNING + if (a.glassesPresent) { + GlassesGroups(host, glasses, glassesSettings, track, onRecenter = a.onGlassesRecenter, + outputActive = a.glassesOutput, steamVrRunning = running) + VrControllerGroups(host, track) + } + SteamVrGroup(a, track) + if (!a.glassesOutput) CardboardGroup(host, a, track) +} + +@Composable +private fun DrawerSessionPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) { + val colors = MaterialTheme.colorScheme + Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + DrawerActionButton(stringResource(if (a.paused) R.string.resume_session else R.string.drawer_pause_game), + if (a.paused) Icons.Outlined.PlayArrow else Icons.Outlined.Pause, modifier = track("pause")) { + host.open = null + if (a.paused) a.onResume() else a.onPause() + } + if (a.pipSupported) DrawerActionButton(stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, modifier = track("pip")) { + host.open = null + a.onPip() + } + } + val suspendChoices = listOf( + SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto), + SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual), + SessionPrefs.SUSPEND_NEVER to stringResource(R.string.common_never), + ) + if (a.steam) listOf(SessionPrefs.SUSPEND_NATIVE to stringResource(R.string.mode_suspend_native)) else emptyList() + SettingsGroup(stringResource(R.string.drawer_session_behavior), key = "session-behavior", + detail = summary(stringResource(R.string.mode_suspend) + " " + suspendChoices.labelOf(a.suspendPolicy).orEmpty())) { + if (a.micAvailable) ToggleRow(host, "microphone", stringResource(R.string.mode_mic), + stringResource(R.string.drawer_mic_hint), a.micEnabled, + chipModifier = track("microphone"), onChange = a.onMicEnabled) + ChoiceRow( + host, "suspend", stringResource(R.string.mode_suspend), null, suspendChoices, a.suspendPolicy, + note = stringResource(if (a.steam) R.string.mode_suspend_steam_note else R.string.mode_suspend_note), + chipModifier = track("suspend"), onPick = a.onSuspendPolicy, + ) + if (a.steam && a.suspendPolicy != SessionPrefs.SUSPEND_NEVER) ToggleRow( + host, "background-downloads", stringResource(R.string.mode_background_downloads), + stringResource(R.string.mode_background_downloads_hint), a.steamDownloadsInBackground, + chipModifier = track("background-downloads"), onChange = a.onSteamDownloadsInBackground, + ) + if (a.pipSupported) ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null, + a.pipAutoEnter, chipModifier = track("pip-auto"), onChange = a.onPipAutoEnter) + } + if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps), key = "session-apps", + detail = a.androidApps.take(3).joinToString(", ") { it.label }) { + if (a.androidApps.isEmpty()) { + Text(stringResource(R.string.drawer_no_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 = track("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))) + } + }, + ) { onLaunch(app) } + } + } + // Players reach for Share logs while something is going wrong, so Support never folds. + CompositionLocalProvider(LocalDrawerSections provides null) { SettingsGroup(stringResource(R.string.drawer_support)) { + SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) { + DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = track("share-logs"), + progress = com.droiddeck.launcher.session.SessionLogShare.progress) { + host.open = null + a.onShareLogs() + } + } + } } + if (!a.isHomeApp) Column(Modifier.fillMaxWidth().padding(top = 12.dp)) { + DrawerActionButton(stringResource(R.string.drawer_background), Icons.AutoMirrored.Outlined.ExitToApp, + modifier = track("background")) { host.open = null; a.onBackground() } + } +} + +private fun List>.labelOf(value: T): String? = firstOrNull { it.first == value }?.second + +private fun summary(vararg parts: String?): String = parts.filterNot { it.isNullOrEmpty() }.joinToString(" · ") + @Composable private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier = Modifier, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme @@ -1220,7 +1296,16 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List Unit /** The pages kept inside More, and the way into arranging which pages sit on the strip and which here. */ @Composable -private fun DrawerMorePage(host: MenuHost, pages: List, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) { +private fun DrawerMorePage(host: MenuHost, pages: List, a: DrawerActions, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - SettingsGroup(stringResource(R.string.drawer_page_more)) { + // The list of pages is the page itself, so it never folds. + CompositionLocalProvider(LocalDrawerSections provides null) { SettingsGroup(stringResource(R.string.drawer_page_more)) { if (pages.isEmpty()) Text( stringResource(R.string.drawer_more_empty), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp), @@ -1289,23 +1375,23 @@ private fun DrawerMorePage(host: MenuHost, pages: List, onOpe ) { Icon(item.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) Text(stringResource(item.title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f)) + if (item == SessionDrawerPage.ACHIEVEMENTS) a.achievementsProgress?.takeIf { it.second > 0 }?.let { (done, total) -> + Text(stringResource(R.string.achievements_count_short, done, total), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal) + } } } - } + } } Spacer(Modifier.height(10.dp)) DrawerOutlineButton(stringResource(R.string.drawer_manage_pages), modifier = track("more-edit").testTag("drawer-more-edit"), onClick = onEdit) } @Composable -private fun ScreenEffectsGroup( - host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit, - track: (String) -> Modifier, -) { +private fun ScreenEffectsGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { val e = a.effects val preset = ScreenEffectLooks.match(e, a.upscaler) - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - SettingsGroup(stringResource(R.string.drawer_effects)) { + val lookLabel = preset?.let { stringResource(it.label) } ?: stringResource(R.string.drawer_look_custom) + SettingsGroup(stringResource(R.string.drawer_effects), key = "effects-look", + detail = summary(lookLabel, a.screenEffectsTargets.labelOf(a.screenEffectsTarget))) { ChoiceRow( host, "effects-profile", stringResource(R.string.screen_effects_target), stringResource(R.string.screen_effects_target_hint), a.screenEffectsTargets, @@ -1359,31 +1445,13 @@ private fun ScreenEffectsGroup( if (a.hdrAvailable) ToggleRow(host, "hdr", stringResource(R.string.mode_hdr), null, a.hdr, chipModifier = track("hdr"), onChange = a.onHdr) else ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) } - if (a.blackFrameInsertionAvailable) ToggleRow(host, "bfi", stringResource(R.string.drawer_bfi), - stringResource(R.string.drawer_bfi_note), a.blackFrameInsertion, - chipModifier = track("bfi"), onChange = a.onBlackFrameInsertion) } - val source = remember { MutableInteractionSource() } - val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value - val rotation by animateFloatAsState(if (advancedExpanded) 180f else 0f, Motion.tw(180), label = "advancedArrow") - val description = stringResource(if (advancedExpanded) R.string.widgets_expanded else R.string.widgets_collapsed) - val toggle = { host.open = null; onAdvancedToggle() } - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), - modifier = track("effects-advanced").fillMaxWidth().padding(top = 12.dp).heightIn(min = 48.dp) - .glideBorder(hot, RoundedCornerShape(8.dp), pal.signal) - .hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = toggle) - .controllerConfirm(onClick = toggle).semantics { stateDescription = description }.padding(horizontal = 4.dp), - ) { - Text(stringResource(R.string.drawer_effects_advanced).uppercase(), fontSize = 12.sp, - fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant) - Box(Modifier.weight(1f).height(1.dp).background(pal.line)) - Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = colors.onSurfaceVariant, - modifier = Modifier.size(22.dp).rotate(rotation)) - } - AnimatedVisibility(advancedExpanded) { - Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(colors.surface).border(1.dp, pal.line, RoundedCornerShape(14.dp))) { + val tuned = listOfNotNull( + stringResource(R.string.drawer_cas).takeIf { e.cas }, stringResource(R.string.drawer_deband).takeIf { e.deband }, + ) + SettingsGroup(stringResource(R.string.drawer_section_tuning), key = "effects-tune", + tag = if (preset == null) stringResource(R.string.drawer_tag_custom) else null, detail = summary(*tuned.toTypedArray())) { + run { ToggleRow(host, "cas", stringResource(R.string.drawer_cas), null, e.cas, chipModifier = track("cas")) { a.onEffects(e.copy(cas = it)) } if (e.cas) SliderRow(stringResource(R.string.drawer_cas_level), null, e.casLevel, 0..100, step = 5, format = { "$it%" }, modifier = track("cas-level")) { a.onEffects(e.copy(casLevel = it)) } @@ -1405,7 +1473,8 @@ private fun ScreenEffectsGroup( @Composable private fun CardboardGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { val c = a.cardboard - SettingsGroup(stringResource(R.string.cardboard_title)) { + SettingsGroup(stringResource(R.string.cardboard_title), key = "vr-cardboard", + detail = stringResource(if (c.enabled) R.string.widgets_on else R.string.widgets_off)) { ToggleRow(host, "cardboard", stringResource(R.string.cardboard_mode), stringResource(R.string.cardboard_mode_hint), c.enabled, chipModifier = track("cardboard")) { a.onCardboard(c.copy(enabled = it)) } if (!c.enabled) return@SettingsGroup @@ -1438,7 +1507,8 @@ private fun CardboardGroup(host: MenuHost, a: DrawerActions, track: (String) -> @Composable private fun SteamVrGroup(a: DrawerActions, track: (String) -> Modifier) { - SettingsGroup(stringResource(R.string.steamvr_title)) { + SettingsGroup(stringResource(R.string.steamvr_title), key = "vr-steamvr", + tag = if (a.steamVr == SteamVr.Status.RUNNING) stringResource(R.string.drawer_tag_running) else null) { val vrLabel = stringResource(R.string.cardboard_steamvr) val enterLabel = stringResource(if (a.immersiveSteamVr) R.string.steamvr_enter else R.string.cardboard_steamvr_start) @Composable fun button(label: String, text: String, action: String) { @@ -1564,7 +1634,8 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) val swapsGame = a.gameSwapAvailable || a.gameOnBottom val hasSecondScreen = a.secondScreenDisplays.isNotEmpty() if (!hasSecondScreen && !choosesDisplay && !swapsGame) return - SettingsGroup(stringResource(R.string.drawer_second_screen)) { + SettingsGroup(stringResource(R.string.drawer_second_screen), key = "display-second", + tag = if (hasSecondScreen) stringResource(R.string.drawer_tag_attached) else null) { if (hasSecondScreen) ChoiceRow(host, "dual-screen-mode", stringResource(R.string.setup_dual_screen_sessions), null, listOf( com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto), @@ -1644,7 +1715,8 @@ private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (Stri val lodBiasChoices: List> = (if (inherited) listOf(null to stringResource(R.string.comp_game_use_general)) else emptyList()) + SessionPrefs.textureLodBiasChoices(LocalContext.current).map { (value, label) -> value as String? to label } - SettingsGroup(stringResource(R.string.drawer_texture)) { + SettingsGroup(stringResource(R.string.drawer_texture), key = "game-textures", + detail = summary(anisotropyChoices.labelOf(a.textureAnisotropy), lodBiasChoices.labelOf(a.textureLodBias))) { ChoiceRow(host, "anisotropy", stringResource(R.string.drawer_anisotropy), null, anisotropyChoices, a.textureAnisotropy, chipModifier = track("anisotropy"), onPick = a.onTextureAnisotropy) ChoiceRow(host, "texture-sharpness", stringResource(R.string.drawer_texture_sharpness), null, @@ -1706,7 +1778,7 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S val options: List> = listOf(null to stringResource(R.string.comp_scope_general)) + a.gameProfiles.map { (id, name) -> Pair(id, name) } val profile = a.selectedGameProfile - SettingsGroup(stringResource(R.string.drawer_selected_profile)) { + SettingsGroup(stringResource(R.string.drawer_selected_profile), key = "game-profile", detail = options.labelOf(a.selectedGameProfileId)) { DrawerStackedChoice( host = host, key = "game-profile", @@ -1845,7 +1917,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin val colors = MaterialTheme.colorScheme val snap = a.components if (snap == null) { - SettingsGroup(stringResource(R.string.drawer_page_components)) { + SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") { Text(stringResource(R.string.comp_reading), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(14.dp)) } return @@ -1855,7 +1927,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin } if (a.selectedGameProfileId != null) { if (gameProfile == null) { - SettingsGroup(stringResource(R.string.drawer_page_components)) { + SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") { Text( stringResource(R.string.comp_reading), fontSize = 13.sp, @@ -1865,7 +1937,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin } return } - SettingsGroup(stringResource(R.string.drawer_page_components)) { + SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") { DrawerStackedChoice( host = host, key = "game-cmp-proton", @@ -1918,7 +1990,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin } val running = snap.protons.filter { it.inUseByGame } val view = snap.protons.firstOrNull { it.proton.id == a.defaultProtonId } ?: running.firstOrNull() ?: snap.protons.firstOrNull() - SettingsGroup(stringResource(R.string.drawer_running_now)) { + SettingsGroup(stringResource(R.string.drawer_running_now), key = "game-running-now") { val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value val pal = LocalPalette.current @@ -1948,13 +2020,13 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin } } if (view == null) { - SettingsGroup(stringResource(R.string.drawer_page_components)) { + SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") { Text(stringResource(R.string.drawer_no_proton), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(14.dp)) } return } val p = view.proton - SettingsGroup(stringResource(R.string.drawer_page_components)) { + SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") { DrawerStackedChoice( host, "cmp-proton", stringResource(R.string.comp_proton), listOfNotNull( @@ -2011,7 +2083,8 @@ internal fun ComponentDownloadsDrawerGroup( val colors = MaterialTheme.colorScheme val installed = packages.map { it.file }.toSet() val nightlyPicked = remember { mutableStateMapOf() } - SettingsGroup(stringResource(R.string.drawer_component_downloads)) { + SettingsGroup(stringResource(R.string.drawer_component_downloads), key = "game-downloads", + tag = if (downloads.isNotEmpty()) stringResource(R.string.drawer_tag_downloading) else null) { Text(stringResource(R.string.drawer_component_downloads_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) SettingsRow(stringResource(R.string.comp_nightlies_checked, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index a47da769fc..5983063e1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -39,6 +39,7 @@ internal class SettingsEntry( val words: List = emptyList(), val developer: Boolean = false, val tab: String? = null, + val frost: Boolean = false, ) { val within: Int? get() = section?.title ?: tab?.let { railLabelIcon(it).first } ?: group @@ -89,6 +90,7 @@ internal object SettingsIndex { s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"), s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"), s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"), + s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"), s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"), SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")), @@ -99,6 +101,10 @@ internal object SettingsIndex { s(SettingsSection.GLASSES, R.string.setup_tab_glasses, "xreal", "viture", "vr", "ar"), s(SettingsSection.LAUNCHER, R.string.setup_theme, "color", "dark"), + SettingsEntry( + SettingsPlace.SETTINGS, R.string.setup_frosted_background, section = SettingsSection.LAUNCHER, frost = true, + words = listOf("blur", "wallpaper", "background", "cards", "transparent", "transparency", "opacity", "glass"), + ), s(SettingsSection.LAUNCHER, R.string.setup_app_scale, "size", "zoom"), s(SettingsSection.LAUNCHER, R.string.setup_launcher_icon), s(SettingsSection.LAUNCHER, R.string.setup_animations), @@ -150,6 +156,6 @@ internal object SettingsIndex { sh(R.string.stores_tab_library, R.string.stores_tab_library, "second library", "sd card", "steam library"), ) - fun search(context: Context, query: String): List = - entries.filter { (!it.developer || DeveloperTools.on) && it.matches(context, query) } + fun search(context: Context, query: String, frost: Boolean = false): List = + entries.filter { (!it.developer || DeveloperTools.on) && (!it.frost || frost) && it.matches(context, query) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt index 0a4ab5590c..e195b4ee8e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt @@ -96,9 +96,9 @@ internal fun SettingsPillSearch( } @Composable -internal fun SettingsSearchResults(query: String, onOpen: (SettingsSection) -> Unit) { +internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (SettingsSection) -> Unit) { val ctx = LocalContext.current - val found = remember(query) { SettingsIndex.search(ctx, query) } + val found = remember(query, frost) { SettingsIndex.search(ctx, query, frost) } if (found.isEmpty()) { Note(stringResource(R.string.settings_search_none, query.trim())) return 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 e6bda83fa5..5d09490e39 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -87,6 +87,7 @@ 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.node.currentValueOf import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectTapGestures @@ -152,14 +153,43 @@ internal fun Modifier.blockTouches(): Modifier = pointerInput(Unit) { detectTapG internal fun Modifier.tapOutside(onTap: () -> Unit): Modifier = pointerInput(onTap) { detectTapGestures(onTap = { onTap() }) } -internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event -> - val keyEvent = event.nativeKeyEvent - val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1 - if (!previous && keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_R1) { - false - } else { - if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) { if (previous) onPrevious() else onNext() } - true +internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = this then BumpersElement(onPrevious, onNext) + +private data class BumpersElement(val onPrevious: () -> Unit, val onNext: () -> Unit) : + androidx.compose.ui.node.ModifierNodeElement() { + override fun create() = BumpersNode(onPrevious, onNext) + override fun update(node: BumpersNode) { + node.onPrevious = onPrevious + node.onNext = onNext + } +} + +internal class BumpersNode(var onPrevious: () -> Unit, var onNext: () -> Unit) : + Modifier.Node(), androidx.compose.ui.input.key.KeyInputModifierNode, androidx.compose.ui.node.CompositionLocalConsumerModifierNode { + override fun onAttach() { PageBumpers.attached += this } + override fun onDetach() { PageBumpers.attached -= this } + override fun onPreKeyEvent(event: androidx.compose.ui.input.key.KeyEvent): Boolean = PageBumpers.handle(event.nativeKeyEvent, this) + override fun onKeyEvent(event: androidx.compose.ui.input.key.KeyEvent): Boolean = false + + @OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) + fun step(previous: Boolean) { + releaseFocusedTextField(currentValueOf(androidx.compose.ui.platform.LocalView)) + OpenMenus.leaveAll(withPage = false) + if (previous) onPrevious() else onNext() + // Android keeps touch mode through gamepad buttons, and the pages move the focus only outside it. + val input = currentValueOf(LocalInputModeManager) + if (input.inputMode != InputMode.Keyboard) input.requestInputMode(InputMode.Keyboard) + } +} + +internal object PageBumpers { + val attached = ArrayList() + + fun handle(event: KeyEvent, node: BumpersNode? = attached.lastOrNull()): Boolean { + val previous = event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 + if (node == null || (!previous && event.keyCode != KeyEvent.KEYCODE_BUTTON_R1)) return false + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) node.step(previous) + return true } } @@ -182,7 +212,8 @@ internal fun TabStrip( Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) { if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) } // Centred, the bumpers sit at the edges and the tabs in the middle, as in the bottom bar. - Box(if (centered) Modifier.weight(1f) else Modifier.weight(1f, fill = false), contentAlignment = Alignment.Center) { Row( + Box(if (centered) Modifier.weight(1f) else Modifier.weight(1f, fill = false), contentAlignment = Alignment.Center) { androidx.compose.foundation.layout.BoxWithConstraints { + if (tabsAsMenu(maxWidth, tabs.size)) TabMenu(tabs, selected, onSelect, focus = focusRequesters) else Row( modifier = Modifier.clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape) .horizontalScroll(scroll).selectableGroup().padding(3.dp), ) { @@ -209,7 +240,7 @@ internal fun TabStrip( .padding(horizontal = tabPadding, vertical = if (compact) 6.dp else 12.dp), ) } - } } + } } } if (bumpers) BumperKey("RB", stringResource(R.string.widgets_next_tab)) { onSelect((selected + 1) % tabs.size) } } } @@ -267,6 +298,25 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider { } } +private val StepKeys = setOf(KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2) + +private fun launcherOf(view: android.view.View) = view.context.findActivity() as? com.droiddeck.launcher.FrontEndActivity + +// A popup is a window of its own, so controller input sent to it never reaches the launcher's. +private fun Modifier.passSteps(host: android.view.View): Modifier = onPreviewKeyEvent { event -> + event.nativeKeyEvent.keyCode in StepKeys && launcherOf(host) != null && host.rootView.dispatchKeyEvent(event.nativeKeyEvent) +} + +@Composable +private fun PassTriggerMotion(host: android.view.View) { + val popup = androidx.compose.ui.platform.LocalView.current + androidx.compose.runtime.DisposableEffect(popup, host) { + val launcher = launcherOf(host)?.takeIf { it.window.decorView === host.rootView } + if (launcher != null) popup.setOnGenericMotionListener { _, event -> launcher.onMenuMotion(event); false } + onDispose { popup.setOnGenericMotionListener(null) } + } +} + @OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) @Composable fun AnchoredMenu( @@ -277,6 +327,13 @@ fun AnchoredMenu( val state = remember { MutableTransitionState(false) } state.targetState = open if (!state.currentState && !state.targetState && state.isIdle) return + val dismissNow = rememberUpdatedState(onDismiss) + if (open) androidx.compose.runtime.DisposableEffect(Unit) { + val leave = { _: Boolean -> dismissNow.value() } + OpenMenus.leave += leave + onDispose { OpenMenus.leave -= leave } + } + val hostView = androidx.compose.ui.platform.LocalView.current val firstItemFocus = remember { FocusRequester() } val inputMode = LocalInputModeManager.current.inputMode LaunchedEffect(open, inputMode) { @@ -294,6 +351,7 @@ fun AnchoredMenu( val pal = LocalPalette.current Popup(popupPositionProvider = provider, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) { TrackKeyWindow() + PassTriggerMotion(hostView) val popupInput = LocalInputModeManager.current LaunchedEffect(open, inputMode) { if (!open || inputMode != InputMode.Keyboard) return@LaunchedEffect @@ -307,7 +365,7 @@ fun AnchoredMenu( runCatching { firstItemFocus.requestFocus() } } } - CompositionLocalProvider(LocalDensity provides density, LocalConfiguration provides configuration) { + SolidSurfaces { CompositionLocalProvider(LocalDensity provides density, LocalConfiguration provides configuration) { AnimatedVisibility( visibleState = state, enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f, transformOrigin = TransformOrigin(if (compact) 0f else 1f, 0f)), @@ -323,6 +381,7 @@ fun AnchoredMenu( .clip(RowShape) .background(pal.surfaceVariant.copy(alpha = 0.95f)) .border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape) + .passSteps(hostView) .controllerBack(onDismiss) .padding(6.dp), ) { @@ -363,7 +422,7 @@ fun AnchoredMenu( } } } - } + } } } } @@ -443,7 +502,11 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo } @Composable -fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, content: @Composable ColumnScope.() -> Unit) { +fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, key: String? = null, tag: String? = null, content: @Composable ColumnScope.() -> Unit) { + LocalDrawerSections.current?.let { sections -> + DrawerSection(sections, key ?: title, title, detail, tag, content) + return + } val tight = compact || LocalCompactSettings.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -462,7 +525,7 @@ fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = nul } @Composable -fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, control: @Composable () -> Unit) { +fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, tightControlSpacing: Boolean = false, control: @Composable () -> Unit) { val compact = LocalCompactSettings.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -484,13 +547,13 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint } else if (stacked || LocalNarrowPane.current) Column( modifier = Modifier.fillMaxWidth().background(bg).padding( horizontal = if (compact) 10.dp else 14.dp, - vertical = if (compact) 6.dp else 12.dp), + vertical = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 12.dp), ) { Text(label, fontSize = if (compact) 13.sp else 15.sp, lineHeight = if (compact) 16.sp else androidx.compose.ui.unit.TextUnit.Unspecified, fontWeight = FontWeight.SemiBold, color = colors.onBackground) if (hint != null || hintLines != null) hintText(if (compact) 11.sp else 13.sp) - Box(Modifier.padding(top = if (compact) 6.dp else 8.dp)) { control() } + Box(Modifier.padding(top = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 8.dp)) { control() } } else Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt b/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt index 181a837065..af9136fba4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt @@ -2,7 +2,10 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp import com.droiddeck.launcher.R @@ -12,8 +15,26 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) { SettingsGroup(stringResource(R.string.frame_gen_title)) { SettingsRow(stringResource(R.string.frame_gen_title), stringResource(R.string.frame_gen_hint), highlighted = host.open == "fg") { Box { - ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" } - FrameGenMenu(host, s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless) + val open = host.open == "fg" + ValueChip(s.frameGenLabel, open) { host.open = if (open) null else "fg" } + AnchoredMenu( + open = open, + onDismiss = { if (host.open == "fg") host.open = null }, + title = stringResource(R.string.frame_gen_title), + compact = true, + minWidth = 220.dp, + ) { firstItemFocus -> + FrameGenMenu( + mode = s.frameGen, + lossless = s.lossless, + onPick = { mode -> + a.onFrameGenPick(mode) + host.open = null + }, + focusModifier = Modifier.focusRequester(firstItemFocus), + legacyButtons = true, + ) + } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 6ea5b16cab..95a4ece552 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -82,17 +82,25 @@ import kotlinx.coroutines.withContext private const val WALL_MIN_GAMES = 4 private const val WALL_DISTINCT = 40 -private const val IDLE_FRAME_NS = 30_000_000L +internal val IdleFrames = IdleFrameGate() -internal object IdleFrames { - private var shown = 0L +internal class IdleFrameGate { + private var next = Long.MIN_VALUE + private var shown = Long.MIN_VALUE fun due(nanos: Long): Boolean { if (nanos == shown) return true - if (nanos - shown < IDLE_FRAME_NS) return false + // Allow sub-ms vsync jitter; carry the phase on panels whose refresh isn't a multiple of 60. + if (nanos + VSYNC_TOLERANCE_NS < next) return false + next = if (next == Long.MIN_VALUE || nanos - next >= FRAME_NS) nanos + FRAME_NS else next + FRAME_NS shown = nanos return true } + + private companion object { + const val FRAME_NS = 1_000_000_000L / 60 + const val VSYNC_TOLERANCE_NS = 500_000L + } } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt index b888f08065..20a18aa845 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt @@ -145,11 +145,16 @@ internal class StepOutScope(private val items: List Unit>() + + fun leaveAll(withPage: Boolean) = leave.toList().forEach { it(withPage) } +} + private val OutPull = 6.dp private val OutBoxCorner = 16.dp private val OutFillet = 10.dp -@OptIn(ExperimentalComposeUiApi::class) @Composable internal fun StepOut( open: Boolean, @@ -163,6 +168,22 @@ internal fun StepOut( items: Int = 4, handle: @Composable () -> Unit, content: @Composable StepOutScope.() -> Unit, +) = SolidSurfaces { StepOutPanel(open, pill, preferredSide, accent, onDismiss, onClosed, pillCorner, maxWidth, items, handle, content) } + +@OptIn(ExperimentalComposeUiApi::class) +@Composable +private fun StepOutPanel( + open: Boolean, + pill: Rect, + preferredSide: StepSide, + accent: Color, + onDismiss: () -> Unit, + onClosed: () -> Unit, + pillCorner: Dp?, + maxWidth: Dp, + items: Int, + handle: @Composable () -> Unit, + content: @Composable StepOutScope.() -> Unit, ) { val colors = MaterialTheme.colorScheme val density = LocalDensity.current @@ -179,13 +200,25 @@ internal fun StepOut( val glide = LocalFocusGlide.current val opener = remember { arrayOfNulls(1) } val openNow = androidx.compose.runtime.rememberUpdatedState(open) + val dismissNow = androidx.compose.runtime.rememberUpdatedState(onDismiss) + val leavesWithPage = remember { booleanArrayOf(false) } + val presence = remember { Animatable(1f) } + if (open) androidx.compose.runtime.DisposableEffect(Unit) { + val leave = { withPage: Boolean -> + opener[0] = null + leavesWithPage[0] = withPage + dismissNow.value() + } + OpenMenus.leave += leave + onDispose { OpenMenus.leave -= leave } + } var moving by remember { mutableStateOf(false) } val placed = remember { arrayOfNulls(3) } if (moving) VeilRing() val pull = with(density) { OutPull.toPx() } val corner = pillCorner?.let { with(density) { it.toPx() } } ?: minOf(pill.height, pill.width) / 2f - BoxWithConstraints(Modifier.fillMaxSize()) { + BoxWithConstraints(Modifier.fillMaxSize().graphicsLayer { alpha = presence.value }) { val hostWidth = constraints.maxWidth.toFloat() val hostHeight = constraints.maxHeight.toFloat() val availableHeight = with(density) { @@ -206,9 +239,11 @@ internal fun StepOut( if (grown && flipped) edge.snapTo(if (open) out else rest) val boxBottom = pill.bottom + pull + c.height if (open) { + leavesWithPage[0] = false + presence.snapTo(1f) if (!grown) { opener[0] = glide?.current - edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f) + edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f); dim.snapTo(0f) pieces.forEach { it.snapTo(0f) } grown = true } @@ -226,7 +261,10 @@ internal fun StepOut( } else { opener[0]?.let { o -> if (inputMode.inputMode == InputMode.Keyboard) runCatching { o.requester.requestFocus() } } opener[0] = null - coroutineScope { + if (leavesWithPage[0]) { + moving = true + presence.animateTo(0f, Motion.tw(160)) + } else coroutineScope { pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } } launch { delay(Motion.ms(60).toLong()); dim.animateTo(0f, Motion.tw(300)) } moving = true diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt index 2d6e37753c..2f7c962934 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt @@ -56,6 +56,7 @@ import androidx.compose.ui.draw.alpha 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.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext @@ -358,6 +359,67 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t } } +/** The Achievements page of the session menu: the same list as the full panel, inside the menu's own scroll. */ +@Composable +internal fun DrawerAchievementsPage(game: StoreAchievements.Game, title: String?, track: (String) -> Modifier) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val label = StoreAchievements.forSource(game.source)?.label.orEmpty() + val state = rememberAchievements(game) ?: AchievementsState.READING + val kinds = remember(state.list) { + val list = state.list.orEmpty() + val split = groups(list) + if (split.size < 2) emptyList() else listOf(R.string.stores_tab_all to list) + split + } + var pick by remember { mutableIntStateOf(0) } + if (pick >= kinds.size) pick = 0 + var noteHadFocus by remember { mutableStateOf(false) } + val firstRow = remember { FocusRequester() } + val loaded = !state.list.isNullOrEmpty() + LaunchedEffect(loaded) { + if (loaded && noteHadFocus) { + noteHadFocus = false + withFrameNanos { } + runCatching { firstRow.requestFocus() } + } + } + Column(Modifier.fillMaxWidth().padding(top = 8.dp, start = 4.dp, end = 4.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + Text(title.orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) + state.list?.takeIf { it.isNotEmpty() }?.let { list -> + if (state.all) Trophy(18.dp, Modifier.padding(end = 6.dp)) + Text(stringResource(R.string.achievements_count_short, state.done, list.size), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = pal.signal) + } + } + val list = state.list + if (list.isNullOrEmpty()) { + Text(achievementsNote(state, label).orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant, + modifier = Modifier.padding(top = 12.dp).then(track("achievements")) + .onFocusChanged { if (it.isFocused) noteHadFocus = true }.focusable()) + return@Column + } + LinearProgressIndicator( + progress = { state.done / list.size.toFloat() }, color = pal.signal, trackColor = pal.line, + modifier = Modifier.padding(top = 8.dp).fillMaxWidth().height(4.dp).clip(RoundedCornerShape(2.dp)), + ) + if (kinds.isNotEmpty()) TabStrip( + kinds.map { (name, group) -> if (name == R.string.stores_tab_all) stringResource(name) + " · " + group.size else stringResource(name, group.size) }, + pick, { pick = it }, Modifier.padding(top = 10.dp), bumpers = false, compact = true, + ) + val shown = kinds.getOrNull(pick)?.second ?: list + val sections = if (pick == 0) groups(shown).filter { it.second.isNotEmpty() } else listOf(null to shown) + val first = sections.firstOrNull()?.second?.firstOrNull()?.id + Column(Modifier.padding(top = 6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + for ((group, items) in sections) { + if (group != null) AchievementGroupLabel(stringResource(group, items.size)) + for (a in items) androidx.compose.runtime.key(a.id) { + AchievementRow(a, compact = true, if (a.id == first) track("achievements").focusRequester(firstRow) else Modifier) + } + } + } + } +} + @Composable internal fun DrawerAchievementsRow(progress: Pair?, modifier: Modifier = Modifier, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 963c2f9c99..33963e2d34 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -453,7 +453,7 @@ private fun StoreDot(store: Store, signedIn: Boolean) { @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable -private fun StoreChips( +internal fun StoreChips( selected: String, focused: String?, tabs: List, onStore: (Store) -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit, ) { @@ -470,27 +470,42 @@ private fun StoreChips( val tabScroll = rememberScrollState() Box(Modifier.fillMaxWidth()) { Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - Box(Modifier.weight(1f).edgeFade(tabScroll).horizontalScroll(tabScroll)) { - Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { - for (tab in tabs) { - val store = tab.store - if (tab.shown) { - val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true - key(store) { - val reveal = remember { BringIntoViewRequester() } - LaunchedEffect(selected) { if (selected == store.id) reveal.bringIntoView() } - StoreChip( - label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot, - modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[store.id] = it.boundsInParent() }, - lead = { StoreDot(store, signedIn) }, - description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out), - onFocused = onFocusChip, - ) { onStore(store) } + val shown = tabs.filter { it.shown }.map { it.store } + BoxWithConstraints(Modifier.weight(1f)) { + if (sourceTabsAsMenu(maxWidth, shown.size)) TabMenu( + shown.map { it.shortLabel }, shown.indexOfFirst { it.id == selected }, { onStore(shown[it]) }, + chipModifier = shown.fold(Modifier as Modifier) { m, st -> key(st) { m.paneItem("storechip:${st.id}") } }, + descriptions = shown.map { st -> + val signedIn = StoresState.isSignedIn(st) && StoresState.expired[st] != true + st.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out) + }, + leading = { i, inList -> + val signedIn = StoresState.isSignedIn(shown[i]) && StoresState.expired[shown[i]] != true + if (inList) Box(Modifier.size(12.dp).background(sourceColours(shown[i].id).dot.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape)) + else StoreDot(shown[i], signedIn) + }, + ) else Box(Modifier.edgeFade(tabScroll).horizontalScroll(tabScroll)) { + Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { + for (tab in tabs) { + val store = tab.store + if (tab.shown) { + val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true + key(store) { + val reveal = remember { BringIntoViewRequester() } + LaunchedEffect(selected) { if (selected == store.id) reveal.bringIntoView() } + StoreChip( + label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot, + modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[store.id] = it.boundsInParent() }, + lead = { StoreDot(store, signedIn) }, + description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out), + onFocused = onFocusChip, + ) { onStore(store) } + } } } } + ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } - ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } var cogAt by remember { mutableStateOf(null) } Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt new file mode 100644 index 0000000000..c5c31a203c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt @@ -0,0 +1,109 @@ +package com.droiddeck.launcher.ui + +import android.content.res.Configuration +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.ExpandLess +import androidx.compose.material.icons.outlined.ExpandMore +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +private val TAB_MENU_BELOW = 600.dp +private val TAB_MIN_WIDTH = 96.dp + +/** Whether [count] tabs in [width] become a [TabMenu]: on a narrow page, when they would not fit side by side. */ +internal fun tabsAsMenu(width: Dp, count: Int): Boolean = + count > 2 && width < TAB_MENU_BELOW && width / count < TAB_MIN_WIDTH + +@Composable +internal fun sourceTabsAsMenu(width: Dp, count: Int): Boolean = + count > 1 && (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT || + (width < TAB_MENU_BELOW && width / count < TAB_MIN_WIDTH)) + +/** + * Tabs as one chip naming the shown tab, which opens the list of them, as the second screen's + * picker does. Each of [focus] lands on the chip, so callers that focus a tab still reach it. + */ +@Composable +internal fun TabMenu( + labels: List, selected: Int, onPick: (Int) -> Unit, + modifier: Modifier = Modifier, focus: List? = null, + chipModifier: Modifier = Modifier, descriptions: List? = null, + leading: (@Composable (index: Int, inList: Boolean) -> Unit)? = null, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var open by remember { mutableStateOf(false) } + val source = remember { MutableInteractionSource() } + val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value + val shape = RoundedCornerShape(22.dp) + val label = labels.getOrNull(selected).orEmpty() + val description = descriptions?.getOrNull(selected) ?: label + val toggle = { open = !open } + Box(modifier) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = focus.orEmpty().fold(chipModifier.height(44.dp)) { m, r -> m.focusRequester(r) } + .testTag("tab-menu") + .semantics { contentDescription = description } + .clip(shape).background(if (hot || open) pal.signal.copy(alpha = 0.14f) else colors.surfaceVariant) + .glideBorder(hot || open, shape, pal.signal, pal.line2) + .hoverable(source) + .clickable(role = Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = toggle) + .controllerConfirm(onClick = toggle) + .padding(start = 14.dp, end = 10.dp), + ) { + if (selected in labels.indices) leading?.invoke(selected, false) + Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, contentDescription = null, + tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + } + AnchoredMenu(open, { open = false }, compact = true, minWidth = 200.dp) { first -> + labels.forEachIndexed { i, item -> + MenuItem( + item, checked = i == selected, + leading = leading?.let { { it(i, true) } }, + focusRequester = first.takeIf { i == selected || (i == 0 && selected !in labels.indices) }, + modifier = Modifier.testTag("tab-menu:$i") + .then(descriptions?.getOrNull(i)?.let { d -> Modifier.semantics { contentDescription = d } } ?: Modifier), + ) { open = false; onPick(i) } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt index a639615129..17151e1782 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt @@ -230,35 +230,51 @@ val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.GRAPHITE) } val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03111F) else Color.White +internal val LocalSolidPalette = staticCompositionLocalOf { null } + @Composable -fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, content: @Composable () -> Unit) { +fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, frost: FrostChoice? = null, content: @Composable () -> Unit) { val context = LocalContext.current remember(context) { Themes.loadGradient(context) } val id = theme ?: SessionPrefs.theme(context) if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed) - val p = Themes.byId(id) - val scheme = darkColorScheme( - primary = p.primary, onPrimary = p.onPrimary, secondary = p.onSurfaceVariant, - background = p.background, onBackground = p.onBackground, - surface = p.surface, onSurface = p.onBackground, - surfaceVariant = p.surfaceVariant, onSurfaceVariant = p.onSurfaceVariant, - error = p.error, - ) + val solid = Themes.byId(id) + val look = frost?.let { frostLook(solid, it) } + val p = if (look == null) solid else solid.frosted(look) val baseDensity = LocalDensity.current val baseConfiguration = LocalConfiguration.current val density = remember(baseDensity, appScale) { scaledAppDensity(baseDensity, appScale) } val configuration = remember(baseConfiguration, appScale) { scaledAppConfiguration(baseConfiguration, appScale) } CompositionLocalProvider( LocalPalette provides p, + LocalSolidPalette provides solid.takeIf { look != null }, + LocalFrost provides look?.veil, LocalDensity provides density, LocalConfiguration provides configuration, ) { - MaterialTheme(colorScheme = scheme, typography = ContentDirected) { + MaterialTheme(colorScheme = p.scheme(), typography = ContentDirected) { FocusGlideHost { ProvideTextStyle(TextStyle(textDirection = TextDirection.Content), content) } } } } +private fun Palette.scheme() = darkColorScheme( + primary = primary, onPrimary = onPrimary, secondary = onSurfaceVariant, + background = background, onBackground = onBackground, + surface = surface, onSurface = onBackground, + surfaceVariant = surfaceVariant, onSurfaceVariant = onSurfaceVariant, + error = error, +) + +@Composable +internal fun SolidSurfaces(content: @Composable () -> Unit) { + val solid = LocalSolidPalette.current + if (solid == null) content() + else CompositionLocalProvider(LocalPalette provides solid, LocalSolidPalette provides null, LocalFrost provides null) { + MaterialTheme(colorScheme = solid.scheme(), typography = MaterialTheme.typography, content = content) + } +} + private val ContentDirected = Typography().run { fun TextStyle.byContent() = copy(textDirection = TextDirection.Content) Typography( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt b/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt index 279941154f..88cd13355a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt @@ -69,7 +69,7 @@ internal object ThemeColors { private val DARK_INK = Color(0xFF03111F) - private fun contrast(a: Color, b: Color): Float { + internal fun contrast(a: Color, b: Color): Float { val x = a.luminance() val y = b.luminance() return (max(x, y) + 0.05f) / (min(x, y) + 0.05f) @@ -80,7 +80,7 @@ internal object ThemeColors { return if (worst(DARK_INK) >= worst(Color.White)) DARK_INK else Color.White } - private const val MIN_CONTRAST = 4.5f + internal const val MIN_CONTRAST = 4.5f private fun fitTo(ink: Color, argb: Int): Int { fun short(color: Int) = contrast(ink, Color(color)) < MIN_CONTRAST diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt index 92478a6cd2..c454dfe2db 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -9,7 +9,6 @@ import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.background -import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.hoverable @@ -25,6 +24,9 @@ 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.RowScope +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -44,6 +46,7 @@ import androidx.compose.material.icons.outlined.Science import androidx.compose.material.icons.outlined.SwapHoriz import androidx.compose.material.icons.outlined.Sync import androidx.compose.material.icons.outlined.Verified +import androidx.compose.material.icons.outlined.WarningAmber import androidx.compose.material3.Icon import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.vector.ImageVector @@ -109,50 +112,37 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie val me = remember { AppUpdates.installed() } val colors = MaterialTheme.colorScheme Column(modifier = modifier) { - Row( - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), - modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp), - ) { - Text( - stringResource(R.string.upd_build, me.version, s.buildLabel), fontSize = 12.5.sp, color = colors.onSurfaceVariant, - maxLines = 1, modifier = Modifier.weight(1f) - .basicMarquee(iterations = Int.MAX_VALUE, initialDelayMillis = 700, velocity = 40.dp), - ) - val checked = u.catalog?.checkedAt?.takeIf { it > 0 } - if (!LocalNarrowPane.current) Text( - if (u.checking) stringResource(R.string.common_checking) else if (checked != null) stringResource(R.string.upd_checked, ago(checked).replaceFirstChar { it.lowercase() }) else stringResource(R.string.upd_not_checked), - fontSize = 13.sp, color = colors.onSurfaceVariant, - ) - val clipboard = LocalClipboardManager.current - val context = LocalContext.current - val details = buildDetails(me, s.buildLabel) - ToolIcon(Icons.Outlined.ContentCopy, stringResource(R.string.upd_copy_build)) { - clipboard.setText(AnnotatedString(details)) - android.widget.Toast.makeText(context, context.getString(R.string.upd_copied), android.widget.Toast.LENGTH_SHORT).show() - } - ToolIcon(Icons.Outlined.Refresh, stringResource(R.string.store_check_updates), busy = u.checking, enabled = !u.checking && u.stage == null, onClick = ua.onCheck) - } BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { val stacked = LocalNarrowPane.current || maxWidth < 600.dp Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + SectionLabel(stringResource(R.string.upd_installed_label)) + InstalledCard(s, u, me) + CheckRow(u, ua) + SectionLabel(stringResource(R.string.upd_channel)) if (stacked) { + ChannelPicker(u, ua) + Box(Modifier.height(14.dp)) StatusPanel(s, u, ua, me) - Box(Modifier.height(18.dp)) - ChannelLabel() - ChannelPicker(u, ua, s.sessionRunning) } else { - ChannelLabel() Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) { - Box(Modifier.weight(1f)) { ChannelPicker(u, ua, s.sessionRunning) } + Box(Modifier.weight(1f)) { ChannelPicker(u, ua) } Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) } } } - Box(Modifier.padding(top = 18.dp)) { - ToggleRow( - host, "build-watermark", stringResource(R.string.setup_build_watermark), - stringResource(R.string.setup_build_watermark_hint), s.buildWatermark, - ) { a.onBuildWatermark() } - } + SectionLabel(stringResource(R.string.upd_testers), top = 22.dp) + ToggleRow( + host, "build-watermark", stringResource(R.string.setup_build_watermark), + stringResource(R.string.setup_build_watermark_hint), s.buildWatermark, + ) { a.onBuildWatermark() } + val context = LocalContext.current + val agentReady = com.droiddeck.launcher.agent.AgentHost.installed && + (com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context)) + LabBuilds(s.sessionRunning, onRebuild = if (agentReady) { info -> + com.droiddeck.launcher.agent.AgentHost.send(context, context.getString(R.string.agent_rebuild_lab, info.label)) + context.startActivity(android.content.Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java) + .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent") + .addFlags(android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) + } else null) } } } @@ -169,6 +159,112 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie ) } +private val TEST_TINT = Color(0xFF9B6CFF) + +@Composable +private fun SectionLabel(text: String, top: androidx.compose.ui.unit.Dp = 4.dp) { + Text( + text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = top, bottom = 10.dp), + ) +} + +/** What is installed: which kind of build, its version and versionCode, and its commit, as the first thing on the page. */ +@Composable +private fun InstalledCard(s: FrontEndState, u: UpdatesState, me: AppUpdates.Installed) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val catalog = u.catalog + val lab = com.droiddeck.launcher.lab.LabOverlay.active + val basePr = if (me.pr > 0) me.pr else Regex("""\bpr(\d+)\b""").find(s.buildLabel)?.groupValues?.get(1)?.toIntOrNull() ?: 0 + val kind = when { + lab != null -> stringResource(R.string.upd_kind_lab) + me.pr > 0 -> stringResource(R.string.upd_kind_test) + catalog?.stable?.let { AppUpdates.isRunning(it, me) } == true -> stringResource(R.string.upd_stable) + catalog?.preview?.let { AppUpdates.isRunning(it, me) } == true -> stringResource(R.string.upd_preview) + else -> null + } + val tint = if (lab != null || me.pr > 0) TEST_TINT else pal.signal + val title = when { + lab != null -> lab.label + me.pr > 0 -> stringResource(R.string.upd_pr, me.pr) + else -> stringResource(R.string.upd_droiddeck_version, me.version) + } + val subtitle = when { + lab != null && basePr > 0 -> stringResource(R.string.upd_lab_on_pr, basePr) + lab != null -> stringResource(R.string.upd_lab_on_version, me.version) + me.pr > 0 -> catalog?.tests?.firstOrNull { it.pr == me.pr }?.title?.takeIf { it.isNotBlank() }?.let(::changeTitle) + else -> null + } + val built = lab?.built?.takeIf { it > 0 } ?: me.committedAt + val meta = listOfNotNull( + me.version.takeIf { lab != null || me.pr > 0 }, + stringResource(R.string.upd_version_code, me.versionCode), + me.commit.take(7).takeIf { it.length == 7 }, + built.takeIf { it > 0 }?.let { stringResource(R.string.upd_built_ago, ago(it).replaceFirstChar { c -> c.lowercase() }) }, + ).joinToString(" · ") + val clipboard = LocalClipboardManager.current + val context = LocalContext.current + val details = buildDetails(me, s.buildLabel) + Row( + verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(start = 18.dp, end = 12.dp, top = 14.dp, bottom = 16.dp), + ) { + Column(Modifier.weight(1f).padding(top = 2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + if (kind != null) Text( + kind.uppercase(), fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.6.sp, color = tint, maxLines = 1, + modifier = Modifier.clip(CircleShape).background(tint.copy(alpha = 0.16f)).padding(horizontal = 8.dp, vertical = 3.dp), + ) + Text(title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + if (subtitle != null) Text(subtitle, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = colors.onBackground, maxLines = 2, + overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 6.dp)) + Text(meta, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp)) + } + ToolIcon(Icons.Outlined.ContentCopy, stringResource(R.string.upd_copy_build)) { + clipboard.setText(AnnotatedString(details)) + android.widget.Toast.makeText(context, context.getString(R.string.upd_copied), android.widget.Toast.LENGTH_SHORT).show() + } + } +} + +@Composable +private fun CheckRow(u: UpdatesState, ua: UpdatesActions) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val enabled = !u.checking && u.stage == null + val checked = u.catalog?.checkedAt?.takeIf { it > 0 } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 14.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.offset(x = (-6).dp).paneItem("updates:check").heightIn(min = 40.dp).clip(Shape12) + .background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + .glideBorder(hot, Shape12, pal.signal) + .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.Button, onClick = ua.onCheck) + .controllerConfirm(enabled = enabled, onClick = ua.onCheck) + .padding(horizontal = 6.dp), + ) { + if (u.checking) androidx.compose.material3.CircularProgressIndicator(Modifier.size(16.dp), color = pal.signal, strokeWidth = 2.dp) + else Icon(Icons.Outlined.Refresh, contentDescription = null, tint = pal.signal.copy(alpha = if (enabled) 1f else 0.5f), modifier = Modifier.size(18.dp)) + Text( + if (u.checking) stringResource(R.string.common_checking) else stringResource(R.string.upd_check_now), + fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = pal.signal.copy(alpha = if (enabled || u.checking) 1f else 0.5f), + ) + } + Box(Modifier.weight(1f)) + Text( + if (checked != null) stringResource(R.string.upd_checked, ago(checked).replaceFirstChar { it.lowercase() }) else stringResource(R.string.upd_not_checked), + fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, + ) + } +} + @Composable private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed) { val colors = MaterialTheme.colorScheme @@ -201,12 +297,18 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) { Box(Modifier.size(7.dp).clip(CircleShape).background(look.tint)) Text(look.status, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = look.tint) - if (offered) Text(stringResource(R.string.upd_dot_ago, ago(release!!.publishedAt)), fontSize = 13.sp, color = colors.onSurfaceVariant) } Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp)) if (offered) { - ReleaseNotes(changeTitle(release!!.title.ifBlank { release.tag }), release.summary, release.tag) - ReleaseFacts(release) + val size = release!!.apk?.size?.takeIf { it > 0 }?.let { megabytes(it) } + Text( + listOfNotNull(stringResource(R.string.upd_released_ago, ago(release.publishedAt)), size).joinToString(" · "), + fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp), + ) + val older = (release.committedAt.takeIf { it > 0 } ?: release.publishedAt).let { it > 0 && me.committedAt > 0 && it < me.committedAt } + if (offer == Offer.SWITCH && older) OlderNote(me.committedAt) + val title = changeTitle(release.title.ifBlank { release.tag }) + ReleaseNotes(title.takeUnless { it == look.headline || (release.version != null && it.endsWith(release.version)) }, release.summary, release.tag) } if (release != null && u.follow.channel == Channel.TEST && catalog != null) { androidx.compose.runtime.LaunchedEffect(release.tag, release.commit, release.apk?.sha256) { ua.onSeen(release) } @@ -228,8 +330,10 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(6.dp).clip(CircleShape)) } offered && installBlock != null -> Unit - offer == Offer.UPDATE -> PrimaryButton(stringResource(R.string.upd_update_button, button), enabled = installable, main = true) { ua.onInstall(release!!) } - offer == Offer.SWITCH -> PrimaryButton(stringResource(R.string.upd_install_button, button), enabled = installable, main = true) { ua.onInstall(release!!) } + offer == Offer.UPDATE -> PrimaryButton(stringResource(R.string.upd_update_button, button), enabled = installable, main = true, fill = true, + modifier = Modifier.fillMaxWidth()) { ua.onInstall(release!!) } + offer == Offer.SWITCH -> PrimaryButton(stringResource(R.string.upd_switch_to_button, channelTitle(u.follow), button), enabled = installable, main = true, + fill = true, modifier = Modifier.fillMaxWidth()) { ua.onInstall(release!!) } offer == Offer.AHEAD && u.follow.channel == Channel.STABLE && installBlock == null -> SecondaryButton(stringResource(R.string.upd_install_anyway, release?.version.orEmpty()), enabled = installable) { ua.onInstall(release!!) } offer == Offer.GONE -> PrimaryButton(stringResource(R.string.upd_follow_preview), main = true) { ua.onFollow(Follow(Channel.NIGHTLY)) } @@ -238,25 +342,53 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m if (s.sessionRunning && (offered || offer == Offer.AHEAD)) { Text(stringResource(R.string.upd_stop_session), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp)) } + if (offered) ReleaseFacts(release!!) if (u.follow.channel == Channel.NIGHTLY) { PreviewHistory(catalog, me, s, u, ua) } } } +/** A switch that installs a build made before the installed one; Android keeps the app's data across it. */ @Composable -private fun ReleaseNotes(title: String, notes: String, key: String) { +private fun OlderNote(installedAt: Long) { + val context = LocalContext.current + val date = android.text.format.DateUtils.formatDateTime(context, installedAt, + android.text.format.DateUtils.FORMAT_SHOW_DATE or android.text.format.DateUtils.FORMAT_ABBREV_MONTH) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.padding(top = 12.dp).fillMaxWidth().clip(Shape12).background(AttentionAmber.copy(alpha = 0.12f)) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + Icon(Icons.Outlined.WarningAmber, contentDescription = null, tint = AttentionAmber, modifier = Modifier.size(20.dp)) + Column { + Text(stringResource(R.string.upd_older_than_installed, date), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = AttentionAmber) + Text(stringResource(R.string.upd_data_stays), fontSize = 12.5.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +@Composable +private fun channelTitle(f: Follow) = when (f.channel) { + Channel.STABLE -> stringResource(R.string.upd_stable) + Channel.NIGHTLY -> stringResource(R.string.upd_preview) + Channel.TEST -> stringResource(R.string.upd_pr, f.pr) +} + +@Composable +private fun ReleaseNotes(title: String?, notes: String, key: String) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current var open by rememberSaveable(key) { mutableStateOf(false) } var cut by remember(key) { mutableStateOf(false) } - Text( + if (title != null) Text( title, fontSize = 15.sp, color = colors.onBackground, maxLines = if (open) Int.MAX_VALUE else 2, overflow = TextOverflow.Ellipsis, onTextLayout = { if (it.hasVisualOverflow) cut = true }, modifier = Modifier.padding(top = 10.dp), ) if (notes.isNotBlank()) Text( - notes, fontSize = 13.5.sp, color = colors.onSurfaceVariant, maxLines = if (open) Int.MAX_VALUE else 1, overflow = TextOverflow.Ellipsis, - onTextLayout = { if (it.hasVisualOverflow) cut = true }, modifier = Modifier.padding(top = 4.dp), + notes, fontSize = 13.5.sp, color = colors.onSurfaceVariant, maxLines = if (open) Int.MAX_VALUE else if (title == null) 3 else 1, + overflow = TextOverflow.Ellipsis, onTextLayout = { if (it.hasVisualOverflow) cut = true }, + modifier = Modifier.padding(top = if (title == null) 10.dp else 4.dp), ) if (cut || open) { val src = remember { MutableInteractionSource() } @@ -287,47 +419,76 @@ private fun changeTitle(t: String): String = private fun megabytes(bytes: Long) = stringResource(R.string.upd_mb, ((bytes + 524_288) / 1_048_576).toInt()) @Composable -private fun ChannelLabel() { - Text( - stringResource(R.string.upd_channel), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp), - ) -} - -@Composable -private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions, sessionRunning: Boolean) { +private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) { val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current val catalog = u.catalog val tests = catalog?.tests.orEmpty() val me = remember { AppUpdates.installed() } val ready = tests.count { AppUpdates.installable(it, me) } var showTests by rememberSaveable { mutableStateOf(false) } + val listing = (showTests || u.follow.channel == Channel.TEST) && tests.isNotEmpty() + val shown = if (listing || showTests) Channel.TEST else u.follow.channel Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - ChannelCard( - Icons.Outlined.Verified, stringResource(R.string.upd_stable), stringResource(R.string.upd_stable_hint), - catalog?.stable?.let { stringResource(R.string.upd_version_ago, it.version ?: it.tag, ago(it.publishedAt)) }, u.follow.channel == Channel.STABLE, - ) { ua.onFollow(Follow(Channel.STABLE)) } - ChannelCard( - Icons.Outlined.Bolt, stringResource(R.string.upd_preview), stringResource(R.string.upd_preview_hint), - catalog?.preview?.let { ago(it.publishedAt) }, u.follow.channel == Channel.NIGHTLY, - ) { ua.onFollow(Follow(Channel.NIGHTLY)) } - ChannelCard( - Icons.Outlined.Science, stringResource(R.string.upd_tests), stringResource(R.string.upd_tests_hint), - if (tests.isEmpty()) stringResource(R.string.upd_tests_none) else pluralStringResource(R.plurals.upd_tests_count, ready, ready), - u.follow.channel == Channel.TEST, enabled = tests.isNotEmpty() || u.follow.channel == Channel.TEST, - ) { showTests = !showTests } - AnimatedVisibility((showTests || u.follow.channel == Channel.TEST) && tests.isNotEmpty(), enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) { + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.fillMaxWidth().clip(CircleShape).background(colors.surface).border(1.dp, pal.line, CircleShape) + .padding(4.dp).selectableGroup(), + ) { + ChannelSegment(Icons.Outlined.Verified, stringResource(R.string.upd_stable), null, shown == Channel.STABLE) { + showTests = false; ua.onFollow(Follow(Channel.STABLE)) + } + ChannelSegment(Icons.Outlined.Bolt, stringResource(R.string.upd_preview), null, shown == Channel.NIGHTLY) { + showTests = false; ua.onFollow(Follow(Channel.NIGHTLY)) + } + ChannelSegment( + Icons.Outlined.Science, stringResource(R.string.upd_tests_short), ready.takeIf { it > 0 }?.toString(), + shown == Channel.TEST, enabled = tests.isNotEmpty() || u.follow.channel == Channel.TEST, + ) { showTests = !showTests } + } + val hint = when { + listing || u.follow.channel == Channel.TEST -> stringResource(R.string.upd_tests_hint) + u.follow.channel == Channel.NIGHTLY -> stringResource(R.string.upd_preview_hint) + + (catalog?.preview?.let { " · " + stringResource(R.string.upd_latest_ago, ago(it.publishedAt)) } ?: "") + else -> stringResource(R.string.upd_stable_hint) + + (catalog?.stable?.let { " · " + stringResource(R.string.upd_version_ago, it.version ?: it.tag, ago(it.publishedAt)) } ?: "") + } + Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp)) + if (tests.isEmpty() && catalog != null && showTests) Text(stringResource(R.string.upd_tests_none), fontSize = 12.5.sp, color = colors.onSurfaceVariant) + AnimatedVisibility(listing, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) { TestList(tests, me, u, ua) } - val context = androidx.compose.ui.platform.LocalContext.current - val agentReady = com.droiddeck.launcher.agent.AgentHost.installed && - (com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context)) - LabBuilds(sessionRunning, onRebuild = if (agentReady) { info -> - com.droiddeck.launcher.agent.AgentHost.send(context, context.getString(R.string.agent_rebuild_lab, info.label)) - context.startActivity(android.content.Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java) - .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent") - .addFlags(android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) - } else null) + } +} + +@Composable +private fun RowScope.ChannelSegment( + icon: ImageVector, title: String, badge: String?, selected: Boolean, + enabled: Boolean = true, onClick: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally), + modifier = Modifier.weight(1f).heightIn(min = 44.dp).paneItem("channel:$title") + .clip(CircleShape) + .background(if (selected) pal.signal.copy(alpha = 0.16f) else if (hot) pal.signal.copy(alpha = 0.10f) else Color.Transparent) + .glideBorder(hot, CircleShape, pal.signal, if (selected) pal.signal else Color.Transparent) + .alpha(if (enabled) 1f else 0.5f) + .hoverable(src) + .selectable(selected = selected, interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) + .padding(horizontal = 6.dp), + ) { + Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(18.dp)) + Text(title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (selected) colors.onBackground else colors.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + if (badge != null) Text( + badge, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant, + modifier = Modifier.clip(CircleShape).background(colors.surfaceVariant).padding(horizontal = 6.dp, vertical = 1.dp), + ) } } @@ -542,41 +703,6 @@ private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesS } } -@Composable -private fun ChannelCard( - icon: ImageVector, title: String, hint: String, latest: String?, selected: Boolean, - enabled: Boolean = true, onClick: () -> Unit, -) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - val src = remember { MutableInteractionSource() } - val hot = rememberHot(src) - val fill = if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(14.dp), - modifier = Modifier.fillMaxWidth().paneItem("channel:$title") - .clip(Shape14).background(colors.surface).background(fill).glideBorder(hot, Shape14, pal.signal, pal.line) - .alpha(if (enabled) 1f else 0.55f) - .hoverable(src) - .clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onClick) - .controllerConfirm(enabled = enabled, onClick = onClick) - .padding(horizontal = 14.dp, vertical = 10.dp), - ) { - Box(contentAlignment = Alignment.Center, modifier = Modifier.size(38.dp).clip(Shape12).background(if (selected) pal.signal.copy(alpha = 0.18f) else colors.surfaceVariant)) { - Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) - } - Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) - if (latest != null) Text(latest, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = if (selected) pal.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - RadioDot(selected) - } -} - @Composable private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.dp) { val pal = LocalPalette.current diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt b/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt index d1c64b4b39..4b9d25957a 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt @@ -31,7 +31,7 @@ class BottomDesktopCompositorService : Service() { MSG_RESIZE -> resize(msg.arg1, msg.arg2) MSG_TOUCH -> WaylandCompositor.nativeSendTouch(msg.arg1 and 0xff, msg.arg1 shr 8, msg.arg2 ushr 16, msg.arg2 and 0xffff) - MSG_KEY -> WaylandCompositor.nativeSendKey(msg.arg1, msg.arg2) + MSG_KEY -> WaylandCompositor.nativeSendKeyOrdered(msg.arg1, msg.arg2) MSG_POINTER -> WaylandCompositor.nativeSendPointer(1, msg.arg1, msg.arg2) MSG_SCENE -> WaylandCompositor.nativeSendSceneInput(msg.arg1, msg.arg2, msg.peekData()?.getInt(KEY_B) ?: 0) MSG_CURSOR -> if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(msg.arg1 != 0) 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 afe0df226f..2cc0ecd638 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -9,6 +9,10 @@ public final class WaylandCompositor { private WaylandCompositor() {} + public static native boolean frameWorkerProbeEnabled(); + public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino, long startTicks); + public static native void frameWorkerProbeRevoke(int owner, int pid); + private static volatile Runnable firstFrameListener; public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; } @@ -202,6 +206,27 @@ public final class WaylandCompositor { if (l != null) l.onTextInput(enabled, program, x, y, w, h); } + public interface TextInputFallbackListener { + boolean onTextInputFallback(String text, int token); + } + + private static volatile TextInputFallbackListener textInputFallbackListener; + + public static void setTextInputFallbackListener(TextInputFallbackListener l) { textInputFallbackListener = l; } + + public static boolean isTextInputFallbackListener(TextInputFallbackListener l) { return textInputFallbackListener == l; } + + public static void clearTextInputFallbackListener(TextInputFallbackListener l) { + if (textInputFallbackListener == l) textInputFallbackListener = null; + } + + @SuppressWarnings("unused") + static boolean onTextInputFallback(byte[] utf8, int token) { + TextInputFallbackListener l = textInputFallbackListener; + if (l == null || utf8 == null) return false; + return l.onTextInputFallback(new String(utf8, java.nio.charset.StandardCharsets.UTF_8), token); + } + private static byte[] utf8(String s) { return s == null ? new byte[0] : s.getBytes(java.nio.charset.StandardCharsets.UTF_8); } @@ -210,14 +235,28 @@ public final class WaylandCompositor { public static void textInputCommit(String text) { if (text != null && !text.isEmpty()) nativeTextInputCommit(utf8(text)); } + public static void textInputCommitAndSubmit(String text) { + if (text != null && !text.isEmpty()) nativeTextInputCommitAndSubmit(utf8(text)); + } + public static void textInputPreedit(String text, int cursor) { nativeTextInputPreedit(utf8(text), cursor, cursor); } public static void textInputDelete(int before, int after) { nativeTextInputDelete(before, after); } + public static final int TEXT_NOT_DELIVERED = 0; + public static final int TEXT_DELIVERED = 1; + public static final int TEXT_UNRESOLVED = 2; + + public static void completeTextInputFallback(int token, int result) { + nativeCompleteTextInputFallback(token, result); + } + private static native void nativeSetClipboardText(byte[] utf8); private static native void nativeTextInputCommit(byte[] utf8); + private static native void nativeTextInputCommitAndSubmit(byte[] utf8); private static native void nativeTextInputPreedit(byte[] utf8, int cursorBegin, int cursorEnd); private static native void nativeTextInputDelete(int before, int after); + private static native void nativeCompleteTextInputFallback(int token, int result); public static native void nativeStart(String xdgRuntimeDir); @@ -248,6 +287,10 @@ public final class WaylandCompositor { public static native void nativeSendKey(int evdev, int state); + // Ordered delivery: key events share the host queue with text commits so keys cannot overtake pending text. + public static native void nativeSendKeyOrdered(int evdev, int state); + public static native void nativeSelectGameField(boolean copy); + public static native boolean nativeFocusTakesTouch(); public static native boolean nativeCursorInputPos(int[] out); @@ -417,12 +460,14 @@ public final class WaylandCompositor { public static final int SCENE_BUTTON = 3, SCENE_WHEEL = 4, SCENE_POINTER_DELTA = 6, SCENE_AXIS = 11, SCENE_AXIS_FINGER = 12; public static final int WHEEL_STEP_UNITS = 120, POINTER_DELTA_SCALE = 256; - public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1; + public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1, FG_ENGINE_ZEROFG = 2; public static native void nativeSetFrameGenEngine(int kind); public static native void nativeSetFrameGenArmed(boolean armed, int multiplier, int targetFps); + public static native void nativeSetFrameGenPacer(boolean on); + public static native void nativeSetLsfgCachePath(String path); public static native void nativeSetFrameGenTuning(float flowScale, float refreshHz); diff --git a/app/src/main/res/drawable/ic_frame_generation.xml b/app/src/main/res/drawable/ic_frame_generation.xml new file mode 100644 index 0000000000..bf643a0c8d --- /dev/null +++ b/app/src/main/res/drawable/ic_frame_generation.xml @@ -0,0 +1,14 @@ + + + + diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 6adbf809b9..ea85ca5c12 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG تكيّفي %1$d يتطلب Lossless Scaling على Steam - ثبّت Lossless Scaling في Steam أو استورد Lossless.dll - استيراد Lossless.dll… - يتم استخدام النسخة الموجودة في Steam - يتم استخدام نسخة مستوردة - اختر Lossless.dll - تم استيراد Lossless.dll - ملف Lossless.dll هذا قيد الاستخدام بالفعل - حساب Steam هذا لا يملك Lossless Scaling - هذا الملف ليس Lossless.dll الخاص بـ Lossless Scaling - تعذّر تجهيز LSFG من ملف Lossless.dll هذا - يتطلب LSFG برنامج Lossless Scaling من Steam أو ملف Lossless.dll مستوردًا تعذّر على LSFG تجهيز أدوات التظليل من Lossless.dll %1$s: غير مدعوم %1$s: فشل المحرك @@ -654,6 +643,9 @@ اسم المضيف الاسم الذي يراه Steam لهذا الجهاز. اتركه خاليًا للاستعادة إلى %1$s. أحرف وأرقام وشرطات داخلية فقط، حتى 63 حرفًا. + تشغيل سطح المكتب كمستخدم + يعمل سطح المكتب وتطبيقاته وطرفياته كمستخدم عادي باسم deck بدلًا من root، للتطبيقات التي ترفض root. يظل sudo يعمل. يسري على سطح المكتب التالي. + يتطلب التشغيل دون proot. Android مهيَّأ لإنهاء هذه الجلسة مثبّت متاح للتنزيل @@ -1265,6 +1257,11 @@ تحضير تعذّر الوصول إلى تصحيح الأخطاء اللاسلكي؛ زر الاقتران يشغّله اقتران + لا يحتوي Quest على شاشة اقتران. من حاسوب، شغّل مرة واحدة: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS و adb tcpip 5555. ثم اضغط «السماح» واقبل الطلب في النظارة + السماح + اقبل «السماح بتصحيح الأخطاء؟» في النظارة مع تحديد «السماح دائمًا» + تعذّر الاتصال. اقبل طلب تصحيح الأخطاء في النظارة، وإن لم يظهر، شغّل adb tcpip 5555 من حاسوب ثم حاول مجددًا + تعذّر الوصول إلى تصحيح الأخطاء اللاسلكي. اضغط «السماح» لإعداده من جديد تثبيت تسجيل الدخول PR #%1$d @@ -1342,6 +1339,16 @@ أجهزة Joy-Con كوحدات تحكم VR أثناء تشغيل SteamVR، يصبح كل Joy-Con يدًا. وجّهه إلى الأمام واضغط مطولًا على Home أو Capture لإعادة توسيطه. الرسوم المتحركة + مصنفر + يعرض خلفية الشاشة مموّهة خلف المشغّل. يستهلك طاقة بطارية أكثر. + خلفية مصنفرة + بطاقات مصنفرة + تُظهر البطاقات والمجموعات قليلًا من الخلفية. تبقى القوائم والحوارات معتمة. + يتطلب الخلفية المصنفرة. + شفافية الخلفية + مقدار ما يظهر من الخلفية. + شفافية البطاقات + مقدار ما يظهر من الخلفية عبر البطاقات. التحذير عند انخفاض مساحة التخزين اسأل قبل تشغيل Steam عندما تكون المساحة الحرة أقل من 10 جيجابايت. التخطيط @@ -2231,6 +2238,7 @@ يسار وسط يمين + مقسّم قائمة الوصول السريع في Steam غير متاحة بعد. إحصاءات داخل اللعبة مؤشرات الشاشة السفلية @@ -2545,6 +2553,8 @@ %1$s إذا لم يكن ذلك ممكنًا، وصِّل هذا الجهاز بكمبيوتر يستخدم ADB ونفِّذ الأمر أدناه. عُد إلى هنا وتحقَّق مرة أخرى. يمكن بدء جلسات Steam. لا يستخدم إصدار Android هذا هذا الحدّ. + يتولى DroidDeck حد العمليات الفرعية + يشغّل DroidDeck معظم برامج الجلسة في عمليات لا يحتسبها Android، ما يبقي الجلسة دون الحد بكثير، لذا يمكن إبقاء خيارات المطوّرين متوقفة. ما زال Steam وبعض أدواته المساعدة محتسبة. فعِّل «إيقاف القيود المفروضة على العمليات الثانوية» في خيارات المطوّرين، واترك خيارات المطوّرين مفعَّلة بعد ذلك. لا يحتوي إصدار Android هذا على مفتاح لذلك. استخدِم تصحيح الأخطاء اللاسلكي لتغييره من هذا الجهاز. لا يتوفّر تنزيل لهذا الإصدار الخاص بهذه النسخة من DroidDeck. @@ -3319,9 +3329,11 @@ %1$s س %1$d د موضع الصورة + موضع الصورة (أفقي) + موضع الصورة (عمودي) أعلى أسفل - الوسط (افتراضي) + الوسط يسار يمين التخزين @@ -4310,4 +4322,7 @@ تثبّت هذه اللعبة إصدار Linux الخاص بها. ثبّتها من Steam. تكبير اللعبة اضبط تكبير اللعبة من 100% إلى 300% + اختصار داخل اللعبة + إظهار اختصار النظارات الذكية + إظهار زر النظارات الذكية العائم فوق اللعبة. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index bfc1963cb3..12254b5715 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptativo %1$d Requiere Lossless Scaling en Steam - Instala Lossless Scaling en Steam o importa Lossless.dll - Importar Lossless.dll… - Usando la copia de Steam - Usando una copia importada - Elegir Lossless.dll - Lossless.dll importado - Este Lossless.dll ya está en uso - Lossless Scaling no está en esta cuenta de Steam - Este archivo no es el Lossless.dll de Lossless Scaling - No se pudo preparar LSFG con este Lossless.dll - LSFG necesita Lossless Scaling de Steam o un Lossless.dll importado LSFG no pudo preparar sus shaders desde Lossless.dll %1$s: no compatible %1$s: falló el motor @@ -648,6 +637,9 @@ Nombre del host El nombre que Steam ve para este dispositivo. En blanco restaura %1$s. Solo letras, dígitos y guiones internos, hasta 63 caracteres. + El escritorio se ejecuta como usuario + El escritorio, sus apps y sus terminales se ejecutan como el usuario común deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio. + Requiere Ejecutar sin proot. Android está configurado para cerrar esta sesión Instalado Disponible para descargar @@ -1280,6 +1272,11 @@ Preparar No se puede acceder a la depuración inalámbrica; Vincular la activa Vincular + Quest no tiene pantalla de vinculación. Desde una computadora, ejecuta una vez: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS y adb tcpip 5555. Luego toca Permitir y acepta el aviso en el visor + Permitir + Acepta «¿Permitir depuración?» en el visor, con Permitir siempre marcado + No se pudo conectar. Acepta el aviso de depuración en el visor o, si no apareció, ejecuta adb tcpip 5555 desde una computadora y vuelve a intentarlo + No se puede acceder a la depuración inalámbrica. Toca Permitir para configurarla de nuevo Instalar Iniciar sesión PR #%1$d @@ -1391,6 +1388,16 @@ Compatibilidad experimental con XREAL 1S, One, One Pro, One Pro+ y Aura. Usa el modo Follow y desactiva la estabilización en el menú de las gafas; en Aura, desactiva también Spatial Anchor. El seguimiento de cabeza y el cambio entre 2D/3D se han probado en Aura y One Pro+. Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles. Animaciones + Esmerilado + Muestra tu fondo de pantalla difuminado detrás del launcher. Consume más batería. + Fondo de pantalla esmerilado + Tarjetas esmeriladas + Las tarjetas y los grupos dejan ver un poco del fondo de pantalla. Los menús y diálogos siguen sólidos. + Necesita el fondo de pantalla esmerilado. + Transparencia del fondo de pantalla + Cuánto se ve el fondo de pantalla. + Transparencia de las tarjetas + Cuánto se ve el fondo de pantalla a través de las tarjetas. Avisar cuando queda poco almacenamiento Preguntar antes de iniciar Steam cuando el espacio libre es menor a 10 GB. Disposición @@ -2226,6 +2233,7 @@ Izquierda Centro Derecha + Dividido El menú de acceso rápido de Steam aún no está disponible. Estadísticas del juego HUD de la pantalla inferior @@ -2537,6 +2545,8 @@ %1$s Si no es posible, conecta este dispositivo a una computadora con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo. Ya se pueden iniciar sesiones de Steam. Esta versión de Android no usa este límite. + DroidDeck gestiona el límite de procesos secundarios + DroidDeck ejecuta la mayoría de los programas de la sesión en procesos que Android no cuenta, lo que mantiene la sesión muy por debajo del límite, así que las Opciones de desarrollador pueden quedar desactivadas. Steam y algunos de sus procesos auxiliares todavía cuentan. Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después. Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo. Esta versión no tiene descarga para esta copia de DroidDeck. @@ -3195,9 +3205,11 @@ Seguimiento de manos ¿Rastrear las manos o los mandos Joy-Con con la cámara del teléfono? Posición de la imagen + Posición de la imagen (Horizontal) + Posición de la imagen (Vertical) Arriba Abajo - Centro (predeterminado) + Centro Izquierda Derecha Almacenamiento @@ -4188,4 +4200,7 @@ Cierra Steam primero Pausa primero la descarga de Steam Este juego instala su versión para Linux. Instálalo desde Steam. + Acceso directo en el juego + Mostrar acceso directo de Smart Glasses + Mostrar el botón flotante de Smart Glasses sobre el juego. diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 0eeec70877..bb4ff12581 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Адаптивно %1$d Изисква Lossless Scaling в Steam - Инсталирайте Lossless Scaling в Steam или импортирайте Lossless.dll - Импортиране на Lossless.dll… - Използва се копието от Steam - Използва се импортирано копие - Изберете Lossless.dll - Lossless.dll е импортиран - Този Lossless.dll вече се използва - Lossless Scaling не е закупен за този акаунт в Steam - Този файл не е Lossless.dll на Lossless Scaling - LSFG не можа да се подготви от този Lossless.dll - LSFG изисква Lossless Scaling от Steam или импортиран Lossless.dll LSFG не можа да подготви шейдърите си от Lossless.dll %1$s: не се поддържа %1$s: грешка в двигателя @@ -646,6 +635,9 @@ Име на хоста Името, което Steam вижда за това устройство. Оставено празно възстановява %1$s. Само букви, цифри и тирета по средата, до 63 знака. + Работният плот работи като потребител + Работният плот, приложенията и терминалите му работят като обикновения потребител deck вместо root, за приложения, които отказват root. sudo продължава да работи. Важи за следващия работен плот. + Изисква Работа без proot. Android е настроен да прекратява тази сесия Инсталиран Налично за изтегляне @@ -1249,6 +1241,11 @@ Подготви Безжичното отстраняване на грешки не е достъпно; сдвояването го включва Сдвой + Quest няма екран за сдвояване. От компютър изпълнете веднъж: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS и adb tcpip 5555. След това докоснете „Разреши“ и приемете запитването в шлема + Разреши + Приемете „Разрешаване на отстраняването на грешки?“ в шлема с отметка „Винаги разрешавай“ + Неуспешно свързване. Приемете запитването за отстраняване на грешки в шлема, а ако не се е появило, изпълнете adb tcpip 5555 от компютър и опитайте отново + Безжичното отстраняване на грешки не е достъпно. Докоснете „Разреши“, за да го настроите отново Инсталирай Влез PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Con като VR контролери Докато SteamVR работи, всеки Joy-Con става ръка. Насочете го напред и задръжте Home или Capture, за да го центрирате отново. Анимации + Матово + Показва тапета ви размазан зад лаунчъра. Изразходва повече батерия. + Матов тапет + Матови карти + Картите и групите пропускат малко от тапета. Менютата и диалозите остават плътни. + Изисква матов тапет. + Прозрачност на тапета + Колко от тапета се вижда. + Прозрачност на картите + Колко от тапета се вижда през картите. Предупреждение при малко място Питай преди стартиране на Steam, когато свободното място е под 10 GB. Разположение @@ -2131,6 +2138,7 @@ Вляво В центъра Вдясно + Разделено Менюто за бърз достъп на Steam още не е налично. Статистика в играта HUD на долния екран @@ -2441,6 +2449,8 @@ %1$s Ако това не е възможно, свържи устройството с компютър с ADB и изпълни командата отдолу. Върни се тук и провери отново. Сесиите на Steam могат да стартират. Тази версия на Android не използва това ограничение. + DroidDeck се справя с ограничението за дъщерни процеси + DroidDeck изпълнява повечето програми на сесията в процеси, които Android не отчита, така че сесията остава далеч под лимита и опциите за програмисти могат да останат изключени. Steam и някои от помощните му процеси все още се отчитат. Включи „Деактивиране на ограниченията за дъщерните процеси“ в Опции за програмисти и остави Опции за програмисти включени след това. Тази версия на Android няма превключвател за това. Използвай безжично отстраняване на грешки, за да го промениш от това устройство. Тази версия няма изтегляне за това копие на DroidDeck. @@ -3199,9 +3209,11 @@ %1$s ч %1$d мин Позиция на картината + Позиция на картината (Хоризонтална) + Позиция на картината (Вертикална) Горе Долу - В средата (по подразбиране) + В средата Наляво Надясно Съхранение @@ -4150,4 +4162,7 @@ Тази игра инсталира версията си за Linux. Инсталирайте я от Steam. Мащабиране на играта Регулирайте увеличението на играта от 100% до 300% + Пряк път в играта + Показване на прекия път за Smart Glasses + Показва плаващия бутон за Smart Glasses върху играта. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 833c403b0d..02d5c6d00d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptivní %1$d Vyžaduje Lossless Scaling na Steamu - Nainstalujte Lossless Scaling ve Steamu nebo naimportujte Lossless.dll - Importovat Lossless.dll… - Používá se kopie ze Steamu - Používá se importovaná kopie - Vyberte Lossless.dll - Lossless.dll byl importován - Tento Lossless.dll se už používá - Tento účet Steamu nevlastní Lossless Scaling - Tento soubor není Lossless.dll aplikace Lossless Scaling - Z tohoto souboru Lossless.dll se nepodařilo připravit LSFG - LSFG vyžaduje Lossless Scaling ze Steamu nebo importovaný Lossless.dll LSFG se nepodařilo připravit shadery z Lossless.dll %1$s: nepodporováno %1$s: chyba enginu @@ -650,6 +639,9 @@ Název hostitele Název, který Steam vidí pro toto zařízení. Prázdné obnoví %1$s. Pouze písmena, číslice a vnitřní pomlčky, až 63 znaků. + Plocha běží jako uživatel + Plocha, její aplikace a terminály běží jako běžný uživatel deck místo root, kvůli aplikacím, které root odmítají. sudo dál funguje. Projeví se u příští plochy. + Vyžaduje Spouštět bez proot. Android je nastaven tak, aby tuto relaci ukončil Nainstalováno K dispozici ke stažení @@ -1257,6 +1249,11 @@ Připravit Bezdrátové ladění není dostupné; Spárovat ho zapne Spárovat + Quest nemá obrazovku párování. Z počítače jednou spusťte: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS a adb tcpip 5555. Pak klepněte na Povolit a potvrďte výzvu v headsetu + Povolit + V headsetu potvrďte „Povolit ladění?“ se zaškrtnutým Vždy povolit + Nepodařilo se připojit. Potvrďte výzvu k ladění v headsetu, a pokud se neobjevila, spusťte z počítače adb tcpip 5555 a zkuste to znovu + Bezdrátové ladění není dostupné. Klepnutím na Povolit ho nastavíte znovu Instalovat Přihlásit se PR #%1$d @@ -1328,6 +1325,16 @@ Joy-Cony jako ovladače VR Když běží SteamVR, každý Joy-Con slouží jako ruka. Namiřte ho dopředu a podržením Home nebo Capture ho znovu vycentrujete. Animace + Matné + Zobrazí za spouštěčem rozmazanou tapetu. Spotřebuje více baterie. + Matná tapeta + Matné karty + Karty a skupiny nechají prosvítat trochu tapety. Nabídky a dialogy zůstanou neprůhledné. + Vyžaduje matnou tapetu. + Průhlednost tapety + Kolik tapety prosvítá. + Průhlednost karet + Kolik tapety prosvítá kartami. Upozornit na nedostatek úložiště Zeptat se před spuštěním Steamu, když je volné místo pod 10 GB. Rozložení @@ -2181,6 +2188,7 @@ Vlevo Na střed Vpravo + Rozděleno Nabídka rychlého přístupu Steamu zatím není k dispozici. Statistiky ve hře HUD na spodní obrazovce @@ -2493,6 +2501,8 @@ %1$s Pokud to není možné, připojte toto zařízení k počítači s ADB a spusťte příkaz níže. Vraťte se sem a zkontrolujte to znovu. Relace Steamu se mohou spouštět. Tato verze Androidu tento limit nepoužívá. + Limit podřízených procesů řeší DroidDeck + DroidDeck spouští většinu programů relace v procesech, které Android nezapočítává, takže relace zůstává hluboko pod limitem a možnosti pro vývojáře mohou zůstat vypnuté. Steam a některé jeho pomocné procesy se stále započítávají. Zapněte „Deaktivace omezení podřízených procesů“ v Možnostech pro vývojáře a pak je nechte zapnuté. Tato verze Androidu pro to nemá přepínač. Použijte bezdrátové ladění a změňte to z tohoto zařízení. Toto sestavení nemá stažení pro tuto kopii DroidDecku. @@ -3259,9 +3269,11 @@ %1$s h %1$d min Poloha obrázku + Poloha obrázku (Na šířku) + Poloha obrázku (Na výšku) Nahoře Dole - Uprostřed (výchozí) + Uprostřed Vlevo Vpravo Úložiště @@ -4230,4 +4242,7 @@ Tato hra instaluje svou verzi pro Linux. Nainstalujte ji ze Steamu. Přiblížení hry Nastavte zvětšení hry od 100 % do 300 % + Zkratka ve hře + Zobrazit zkratku Smart Glasses + Zobrazit plovoucí tlačítko Smart Glasses nad hrou. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 6efe122eb6..f3383e6768 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptiv %1$d Kræver Lossless Scaling på Steam - Installer Lossless Scaling via Steam, eller importer Lossless.dll - Importer Lossless.dll… - Bruger kopien fra Steam - Bruger en importeret kopi - Vælg Lossless.dll - Lossless.dll importeret - Denne Lossless.dll er allerede i brug - Lossless Scaling ejes ikke på denne Steam-konto - Denne fil er ikke Lossless Scalings Lossless.dll - Kunne ikke forberede LSFG fra denne Lossless.dll - LSFG kræver Lossless Scaling fra Steam eller en importeret Lossless.dll LSFG kunne ikke forberede sine shadere fra Lossless.dll %1$s: ikke understøttet %1$s: motoren fejlede @@ -646,6 +635,9 @@ Værtsnavn Navnet Steam ser for denne enhed. Tomt gendanner %1$s. Kun bogstaver, tal og bindestreger i midten, op til 63 tegn. + Skrivebordet kører som bruger + Skrivebordet, dets apps og terminaler kører som den almindelige bruger deck i stedet for root, til apps der afviser root. sudo virker stadig. Gælder fra næste skrivebord. + Kræver Kør uden proot. Android er sat til at lukke denne session Installeret Tilgængelig til download @@ -1249,6 +1241,11 @@ Forbered Trådløs fejlfinding kan ikke nås; Par slår den til Par + Quest har ingen parringsskærm. Kør én gang fra en computer: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS og adb tcpip 5555. Tryk derefter på Tillad, og godkend prompten i headsettet + Tillad + Godkend “Tillad fejlretning?” i headsettet med Tillad altid markeret + Kunne ikke oprette forbindelse. Godkend fejlretningsprompten i headsettet, eller kør adb tcpip 5555 fra en computer og prøv igen, hvis den ikke dukkede op + Trådløs fejlretning kan ikke nås. Tryk på Tillad for at konfigurere den igen Installer Log ind PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Cons som VR-controllere Mens SteamVR kører, bliver hver Joy-Con en hånd. Peg den fremad, og hold Home eller Capture nede for at centrere den igen. Animationer + Mat + Viser din baggrund sløret bag launcheren. Bruger mere batteri. + Mat baggrundsbillede + Matte kort + Kort og grupper lader lidt af baggrundsbilledet skinne igennem. Menuer og dialoger forbliver faste. + Kræver mat baggrundsbillede. + Baggrundens gennemsigtighed + Hvor meget af baggrundsbilledet der skinner igennem. + Kortenes gennemsigtighed + Hvor meget af baggrundsbilledet der skinner gennem kortene. Advar, når lagerpladsen er lav Spørg, før Steam startes, når den ledige plads er under 10 GB. Layout @@ -2131,6 +2138,7 @@ Venstre Midte Højre + Delt Steams menu til hurtig adgang er ikke tilgængelig endnu. Statistik i spillet HUD på nederste skærm @@ -2441,6 +2449,8 @@ %1$s Hvis det ikke er muligt, så forbind enheden til en computer med ADB, og køre kommandoen nedenfor. Kom tilbage hertil, og tjek igen. Steam-sessioner kan starte. Denne Android-version bruger ikke denne grænse. + DroidDeck håndterer grænsen for underprocesser + DroidDeck kører de fleste af sessionens programmer i processer, som Android ikke tæller med, så sessionen holder sig et godt stykke under grænsen, og Indstillinger for udviklere kan forblive slået fra. Steam og nogle af dets hjælpeprocesser tæller stadig med. Tænd „Deaktiver begrænsningerne for underprocesser“ i Udvikleremuligheder, og lad Udvikleremuligheder være tændt bagefter. Denne Android-version har ingen kontakt til det. Brug Trådløs fejlretning til at ændre det fra denne enhed. Denne version har ingen download til denne kopi af DroidDeck. @@ -3199,9 +3209,11 @@ %1$s t %1$d min Billedets placering + Billedets placering (Liggende) + Billedets placering (Stående) Øverst Nederst - Midten (standard) + Midten Venstre Højre Lager @@ -4150,4 +4162,7 @@ Dette spil installerer sin Linux-version. Installer det fra Steam. Spilzoom Juster spillets forstørrelse fra 100 % til 300 % + Genvej i spillet + Vis Smart Glasses-genvej + Vis den flydende Smart Glasses-knap oven på spillet. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 31d8914d6c..ce45ef01d4 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptiv %1$d Benötigt Lossless Scaling auf Steam - Installiere Lossless Scaling in Steam oder importiere Lossless.dll - Lossless.dll importieren… - Kopie aus Steam wird verwendet - Importierte Kopie wird verwendet - Lossless.dll auswählen - Lossless.dll importiert - Diese Lossless.dll wird bereits verwendet - Dieses Steam-Konto besitzt Lossless Scaling nicht - Diese Datei ist nicht die Lossless.dll von Lossless Scaling - LSFG konnte aus dieser Lossless.dll nicht vorbereitet werden - LSFG benötigt Lossless Scaling aus Steam oder eine importierte Lossless.dll LSFG konnte seine Shader nicht aus Lossless.dll vorbereiten %1$s: nicht unterstützt %1$s: Engine-Fehler @@ -646,6 +635,9 @@ Hostname Der Name, den Steam für dieses Gerät sieht. Leer lassen stellt %1$s wieder her. Nur Buchstaben, Ziffern und innere Bindestriche, bis zu 63 Zeichen. + Desktop läuft als Benutzer + Der Desktop, seine Apps und Terminals laufen als normaler Benutzer deck statt als root, für Apps, die root ablehnen. sudo funktioniert weiterhin. Gilt ab dem nächsten Desktop. + Erfordert Ohne proot ausführen. Android ist so eingestellt, dass es diese Sitzung beendet Installiert Zum Download verfügbar @@ -1241,6 +1233,11 @@ Vorbereiten Wireless-Debugging ist nicht erreichbar; Koppeln schaltet es ein Koppeln + Quest hat keinen Kopplungsbildschirm. Führe einmal an einem Computer aus: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS und adb tcpip 5555. Tippe dann auf Zulassen und bestätige die Abfrage im Headset + Zulassen + Bestätige „Debugging zulassen?“ im Headset mit aktiviertem „Immer zulassen“ + Verbindung fehlgeschlagen. Bestätige die Debugging-Abfrage im Headset. Falls keine erschienen ist, führe adb tcpip 5555 an einem Computer aus und versuche es erneut + Kabelloses Debugging ist nicht erreichbar. Tippe auf Zulassen, um es neu einzurichten Installieren Anmelden PR #%1$d @@ -1306,6 +1303,16 @@ Joy-Cons als VR-Controller Während SteamVR läuft, wird jeder Joy-Con zu einer Hand. Richte ihn nach vorn und halte HOME oder Capture gedrückt, um ihn neu auszurichten. Animationen + Milchglas + Zeigt dein Hintergrundbild unscharf hinter dem Launcher. Verbraucht mehr Akku. + Milchglas-Hintergrundbild + Milchglas-Karten + Karten und Gruppen lassen etwas vom Hintergrundbild durch. Menüs und Dialoge bleiben deckend. + Erfordert das Milchglas-Hintergrundbild. + Transparenz des Hintergrundbilds + Wie viel vom Hintergrundbild durchscheint. + Transparenz der Karten + Wie viel vom Hintergrundbild durch die Karten scheint. Bei knappem Speicher warnen Vor dem Start von Steam nachfragen, wenn weniger als 10 GB frei sind. Layout @@ -2123,6 +2130,7 @@ Links Mitte Rechts + Geteilt Das Schnellzugriffsmenü von Steam ist noch nicht verfügbar. Spielstatistiken HUD für den unteren Bildschirm @@ -2433,6 +2441,8 @@ %1$s Falls das nicht möglich ist, verbinde dieses Gerät per ADB mit einem Computer und führe den Befehl unten aus. Kehre dann hierher zurück und prüfe erneut. Steam-Sitzungen können starten. Diese Android-Version nutzt dieses Limit nicht. + Limit für untergeordnete Prozesse übernimmt DroidDeck + DroidDeck führt die meisten Programme der Sitzung in Prozessen aus, die Android nicht mitzählt. So bleibt die Sitzung deutlich unter dem Limit, und die Entwickleroptionen können ausgeschaltet bleiben. Steam und einige seiner Hilfsprozesse zählen weiterhin mit. Aktiviere „Beschränkungen für Unterprozesse deaktivieren“ in den Entwickleroptionen und lass die Entwickleroptionen danach aktiviert. Diese Android-Version hat dafür keinen Schalter. Nutze Debugging über WLAN, um es auf diesem Gerät zu ändern. Dieser Build hat keinen Download für diese DroidDeck-Installation. @@ -3199,9 +3209,11 @@ Zu wenig Speicher (%1$s frei, %2$s benötigt) Freier Speicher unbekannt Bildposition + Bildposition (Querformat) + Bildposition (Hochformat) Oben Unten - Mitte (Standard) + Mitte Links Rechts Speicher @@ -4150,4 +4162,7 @@ Dieses Spiel installiert seine Linux-Version. Installiere es über Steam. Spielzoom Spielvergrößerung von 100 % bis 300 % anpassen + Ingame-Verknüpfung + Smart-Glasses-Verknüpfung anzeigen + Die schwebende Smart-Glasses-Schaltfläche über dem Spiel anzeigen. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5cad897424..7205dd9940 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG προσαρμοστικό %1$d Απαιτεί το Lossless Scaling στο Steam - Εγκαταστήστε το Lossless Scaling στο Steam ή εισαγάγετε το Lossless.dll - Εισαγωγή Lossless.dll… - Χρήση του αντιγράφου από το Steam - Χρήση ενός εισαγμένου αντιγράφου - Επιλογή Lossless.dll - Το Lossless.dll εισήχθη - Αυτό το Lossless.dll χρησιμοποιείται ήδη - Αυτός ο λογαριασμός Steam δεν κατέχει το Lossless Scaling - Αυτό το αρχείο δεν είναι το Lossless.dll του Lossless Scaling - Δεν ήταν δυνατή η προετοιμασία του LSFG από αυτό το Lossless.dll - Το LSFG απαιτεί το Lossless Scaling από το Steam ή ένα εισαγμένο Lossless.dll Το LSFG δεν μπόρεσε να προετοιμάσει τα shaders του από το Lossless.dll %1$s: μη υποστηριζόμενο %1$s: αποτυχία μηχανής @@ -646,6 +635,9 @@ Όνομα κεντρικού υπολογιστή Το όνομα που βλέπει το Steam για αυτή τη συσκευή. Αν το αφήσετε κενό, επανέρχεται σε %1$s. Μόνο γράμματα, ψηφία και εσωτερικές παύλες, έως 63 χαρακτήρες. + Η επιφάνεια εργασίας εκτελείται ως χρήστης + Η επιφάνεια εργασίας, οι εφαρμογές και τα τερματικά της εκτελούνται ως ο απλός χρήστης deck αντί για root, για εφαρμογές που αρνούνται το root. Το sudo εξακολουθεί να λειτουργεί. Ισχύει από την επόμενη επιφάνεια εργασίας. + Απαιτεί Εκτέλεση χωρίς proot. Το Android είναι ρυθμισμένο να διακόπτει αυτή τη συνεδρία Εγκατεστημένο Διαθέσιμο για λήψη @@ -1249,6 +1241,11 @@ Προετοιμασία Η ασύρματη αποσφαλμάτωση δεν είναι προσβάσιμη · η Σύζευξη την ενεργοποιεί Σύζευξη + Το Quest δεν έχει οθόνη σύζευξης. Από έναν υπολογιστή, εκτελέστε μία φορά: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS και adb tcpip 5555. Μετά πατήστε «Να επιτραπεί» και αποδεχτείτε το μήνυμα στο headset + Να επιτραπεί + Αποδεχτείτε το «Να επιτραπεί ο εντοπισμός σφαλμάτων;» στο headset, με επιλεγμένο το «Να επιτρέπεται πάντα» + Δεν ήταν δυνατή η σύνδεση. Αποδεχτείτε το μήνυμα εντοπισμού σφαλμάτων στο headset ή, αν δεν εμφανίστηκε, εκτελέστε adb tcpip 5555 από υπολογιστή και δοκιμάστε ξανά + Ο ασύρματος εντοπισμός σφαλμάτων δεν είναι προσβάσιμος. Πατήστε «Να επιτραπεί» για να τον ρυθμίσετε ξανά Εγκατάσταση Σύνδεση PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Con ως χειριστήρια VR Όσο εκτελείται το SteamVR, κάθε Joy-Con γίνεται χέρι. Στρέψτε το μπροστά και κρατήστε πατημένο το Home ή το Capture για να το επανακεντράρετε. Κινήσεις + Θαμπό + Εμφανίζει την ταπετσαρία σας θολή πίσω από τον εκκινητή. Καταναλώνει περισσότερη μπαταρία. + Θαμπή ταπετσαρία + Θαμπές κάρτες + Οι κάρτες και οι ομάδες αφήνουν να φαίνεται λίγη από την ταπετσαρία. Τα μενού και οι διάλογοι μένουν συμπαγείς. + Χρειάζεται θαμπή ταπετσαρία. + Διαφάνεια ταπετσαρίας + Πόση από την ταπετσαρία φαίνεται. + Διαφάνεια καρτών + Πόση από την ταπετσαρία φαίνεται μέσα από τις κάρτες. Προειδοποίηση για χαμηλό χώρο αποθήκευσης Ερώτηση πριν από την εκκίνηση του Steam όταν ο ελεύθερος χώρος είναι κάτω από 10 GB. Διάταξη @@ -2131,6 +2138,7 @@ Αριστερά Κέντρο Δεξιά + Διαιρεμένο Το μενού γρήγορης πρόσβασης του Steam δεν είναι ακόμη διαθέσιμο. Στατιστικά παιχνιδιού HUD κάτω οθόνης @@ -2441,6 +2449,8 @@ %1$s Αν αυτό δεν είναι δυνατό, συνδέστε αυτή τη συσκευή σε έναν υπολογιστή με ADB και εκτελέστε την παρακάτω εντολή. Επιστρέψτε εδώ και ελέγξτε ξανά. Οι συνεδρίες Steam μπορούν να ξεκινήσουν. Αυτή η έκδοση Android δεν χρησιμοποιεί αυτό το όριο. + Το DroidDeck χειρίζεται το όριο θυγατρικών διεργασιών + Το DroidDeck εκτελεί τα περισσότερα προγράμματα της συνεδρίας σε διεργασίες που το Android δεν μετράει, ώστε η συνεδρία να μένει πολύ κάτω από το όριο και οι Επιλογές για προγραμματιστές να μπορούν να μείνουν απενεργοποιημένες. Το Steam και ορισμένες βοηθητικές διεργασίες του εξακολουθούν να μετράνε. Ενεργοποιήστε την «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες» στις Επιλογές προγραμματιστή και αφήστε τις Επιλογές προγραμματιστή ενεργές μετά. Αυτή η έκδοση Android δεν έχει διακόπτη για αυτό. Χρησιμοποιήστε τον ασύρματο εντοπισμό σφαλμάτων για να το αλλάξετε από αυτή τη συσκευή. Αυτή η έκδοση δεν έχει λήψη για αυτό το αντίγραφο του DroidDeck. @@ -3199,9 +3209,11 @@ %1$s ώ. %1$d λεπ. Θέση εικόνας + Θέση εικόνας (Οριζόντιος προσανατολισμός) + Θέση εικόνας (Κατακόρυφος) Πάνω Κάτω - Κέντρο (προεπιλογή) + Κέντρο Αριστερά Δεξιά Αποθήκευση @@ -4150,4 +4162,7 @@ Αυτό το παιχνίδι εγκαθιστά την έκδοσή του για Linux. Εγκαταστήστε το από το Steam. Ζουμ παιχνιδιού Ρυθμίστε τη μεγέθυνση του παιχνιδιού από 100% έως 300% + Συντόμευση μέσα στο παιχνίδι + Εμφάνιση συντόμευσης Smart Glasses + Εμφάνιση του αιωρούμενου κουμπιού Smart Glasses πάνω από το παιχνίδι. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index c055194828..71e10bdab3 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptativo %1$d Requiere Lossless Scaling en Steam - Instala Lossless Scaling en Steam o importa Lossless.dll - Importar Lossless.dll… - Usando la copia de Steam - Usando una copia importada - Elegir Lossless.dll - Lossless.dll importado - Este Lossless.dll ya está en uso - Lossless Scaling no está en esta cuenta de Steam - Este archivo no es el Lossless.dll de Lossless Scaling - No se pudo preparar LSFG con este Lossless.dll - LSFG necesita Lossless Scaling de Steam o un Lossless.dll importado LSFG no pudo preparar sus shaders desde Lossless.dll %1$s: no compatible %1$s: falló el motor @@ -648,6 +637,9 @@ Nombre del host El nombre que Steam ve para este dispositivo. En blanco restaura %1$s. Solo letras, dígitos y guiones internos, hasta 63 caracteres. + El escritorio se ejecuta como usuario + El escritorio, sus apps y sus terminales se ejecutan como el usuario normal deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio. + Requiere Ejecutar sin proot. Android está configurado para cerrar esta sesión Instalado Disponible para descargar @@ -1253,6 +1245,11 @@ Preparar No se puede acceder a la depuración inalámbrica; Emparejar la activa Emparejar + Quest no tiene pantalla de vinculación. Desde un ordenador, ejecuta una vez: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS y adb tcpip 5555. Después toca Permitir y acepta el aviso en el visor + Permitir + Acepta «¿Permitir depuración?» en el visor, con Permitir siempre marcado + No se pudo conectar. Acepta el aviso de depuración en el visor o, si no apareció, ejecuta adb tcpip 5555 desde un ordenador y vuelve a intentarlo + No se puede acceder a la depuración inalámbrica. Toca Permitir para configurarla de nuevo Instalar Iniciar sesión PR #%1$d @@ -1321,6 +1318,16 @@ Joy-Con como mandos de RV Mientras SteamVR está activo, cada Joy-Con es una mano. Apúntalo al frente y mantén Home o Captura para recentrarlo. Animaciones + Esmerilado + Muestra tu fondo de pantalla difuminado detrás del launcher. Consume más batería. + Fondo de pantalla esmerilado + Tarjetas esmeriladas + Las tarjetas y los grupos dejan ver un poco del fondo de pantalla. Los menús y diálogos siguen opacos. + Necesita el fondo de pantalla esmerilado. + Transparencia del fondo de pantalla + Cuánto se ve el fondo de pantalla. + Transparencia de las tarjetas + Cuánto se ve el fondo de pantalla a través de las tarjetas. Avisar cuando queda poco almacenamiento Preguntar antes de iniciar Steam cuando el espacio libre es inferior a 10 GB. Disposición @@ -2156,6 +2163,7 @@ Izquierda Centro Derecha + Dividido El menú de acceso rápido de Steam aún no está disponible. Estadísticas del juego HUD de la pantalla inferior @@ -2467,6 +2475,8 @@ %1$s Si no es posible, conecta este dispositivo a un ordenador con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo. Ya se pueden iniciar sesiones de Steam. Esta versión de Android no usa este límite. + DroidDeck gestiona el límite de procesos secundarios + DroidDeck ejecuta la mayoría de los programas de la sesión en procesos que Android no cuenta, lo que mantiene la sesión muy por debajo del límite, así que las Opciones para desarrolladores pueden seguir desactivadas. Steam y algunos de sus procesos auxiliares siguen contando. Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después. Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo. Esta versión no tiene descarga para esta copia de DroidDeck. @@ -3229,9 +3239,11 @@ Espacio insuficiente (%1$s libres, se necesitan %2$s) Espacio libre desconocido Posición de la imagen + Posición de la imagen (Horizontal) + Posición de la imagen (Vertical) Arriba Abajo - Centro (predeterminado) + Centro Izquierda Derecha Almacenamiento @@ -4190,4 +4202,7 @@ Este juego instala su versión para Linux. Instálalo desde Steam. Zoom del juego Ajusta la ampliación del juego del 100 % al 300 % + Acceso directo en el juego + Mostrar acceso directo de Smart Glasses + Mostrar el botón flotante de Smart Glasses sobre el juego. diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 4fac8b737d..464e2576be 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Mukautuva %1$d Vaatii Lossless Scalingin Steamista - Asenna Lossless Scaling Steamista tai tuo Lossless.dll - Tuo Lossless.dll… - Käytössä on Steamin kopio - Käytössä on tuotu kopio - Valitse Lossless.dll - Lossless.dll tuotu - Tämä Lossless.dll on jo käytössä - Lossless Scaling ei ole tämän Steam-tilin omistuksessa - Tämä tiedosto ei ole Lossless Scalingin Lossless.dll - LSFG:n valmistelu tästä Lossless.dll-tiedostosta epäonnistui - LSFG tarvitsee Lossless Scalingin Steamista tai tuodun Lossless.dll-tiedoston LSFG ei pystynyt valmistelemaan sävyttimiään Lossless.dll-tiedostosta %1$s: ei tuettu %1$s: moottori epäonnistui @@ -646,6 +635,9 @@ Isäntänimi Nimi, jonka Steam näkee tälle laitteelle. Tyhjä palauttaa arvon %1$s. Vain kirjaimia, numeroita ja sisäisiä yhdysmerkkejä, enintään 63 merkkiä. + Työpöytä toimii käyttäjänä + Työpöytä, sen sovellukset ja päätteet toimivat tavallisena käyttäjänä deck rootin sijaan, rootin torjuvia sovelluksia varten. sudo toimii edelleen. Koskee seuraavaa työpöytää. + Vaatii Suorita ilman prootia. Android on asetettu lopettamaan tämä istunto Asennettu Ladattavissa @@ -1249,6 +1241,11 @@ Valmistele Langaton virheenkorjaus ei ole tavoitettavissa; Parita ottaa sen käyttöön Parita + Questissa ei ole laiteparinäkymää. Suorita kerran tietokoneelta: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS ja adb tcpip 5555. Napauta sitten Salli ja hyväksy kehote laseissa + Salli + Hyväksy ”Sallitaanko virheenkorjaus?” laseissa, kun Salli aina on valittuna + Yhteyttä ei saatu. Hyväksy virheenkorjauskehote laseissa, tai jos sitä ei näkynyt, suorita adb tcpip 5555 tietokoneelta ja yritä uudelleen + Langatonta virheenkorjausta ei tavoiteta. Määritä se uudelleen napauttamalla Salli Asenna Kirjaudu sisään PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Conit VR-ohjaimina Kun SteamVR on käynnissä, jokainen Joy-Con toimii kätenä. Osoita sillä eteenpäin ja pidä Home- tai Capture-painiketta pohjassa keskittääksesi sen uudelleen. Animaatiot + Huurrettu + Näyttää taustakuvasi sumennettuna käynnistimen takana. Kuluttaa enemmän akkua. + Huurrettu taustakuva + Huurretut kortit + Kortit ja ryhmät päästävät hieman taustakuvaa läpi. Valikot ja valintaikkunat pysyvät peittävinä. + Vaatii huurretun taustakuvan. + Taustakuvan läpinäkyvyys + Kuinka paljon taustakuvaa näkyy läpi. + Korttien läpinäkyvyys + Kuinka paljon taustakuvaa näkyy korttien läpi. Varoita, kun tallennustila on vähissä Kysy ennen Steamin käynnistämistä, kun vapaata tilaa on alle 10 Gt. Asettelu @@ -2131,6 +2138,7 @@ Vasen Keskellä Oikea + Jaettu Steamin pikavalikko ei ole vielä käytettävissä. Pelinsisäiset tilastot Alanäytön HUD @@ -2441,6 +2449,8 @@ %1$s Jos se ei ole mahdollista, yhdistä tämä laite tietokoneeseen ADB:llä ja suorita alla oleva komento. Palaa tähän ja tarkista uudelleen. Steam-istunnot voivat käynnistyä. Tämä Android-versio ei käytä tätä rajaa. + DroidDeck hoitaa aliprosessirajoituksen + DroidDeck ajaa useimmat istunnon ohjelmat prosesseissa, joita Android ei laske, joten istunto pysyy reilusti rajan alapuolella ja kehittäjäasetukset voivat pysyä pois päältä. Steam ja osa sen apuprosesseista lasketaan edelleen. Ota käyttöön ”Poista käytöstä alatason prosessirajoitukset” Kehittäjäasetuksissa, ja pidä Kehittäjäasetukset päällä sen jälkeen. Tässä Android-versiossa ei ole kytkintä sille. Käytä langatonta virheenkorjausta muuttaaksesi sitä tältä laitteelta. Tälle versiolle ei ole latausta tähän DroidDeck-kopioon. @@ -3199,9 +3209,11 @@ %1$s t %1$d min Kuvan sijainti + Kuvan sijainti (Vaakasuunta) + Kuvan sijainti (Pystysuunta) Ylhäällä Alhaalla - Keskellä (oletus) + Keskellä Vasen Oikea Tallennustila @@ -4150,4 +4162,7 @@ Tämä peli asentaa Linux-versionsa. Asenna se Steamista. Pelin zoomaus Säädä pelin suurennusta välillä 100–300 % + Pelin aikainen pikakuvake + Näytä Smart Glasses -pikakuvake + Näytä pelin päällä kelluva Smart Glasses -painike. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 05ed77da3c..7c1c1ef44d 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptatif %1$d Nécessite Lossless Scaling sur Steam - Installez Lossless Scaling sur Steam ou importez Lossless.dll - Importer Lossless.dll… - Utilise la version sur Steam - Utilise la version importée - Sélectionner le fichier Lossless.dll - Lossless.dll importé - Ce Lossless.dll est déjà utilisé - Ce compte Steam ne possède pas Lossless Scaling - Ce fichier n\'est pas le Lossless.dll de Lossless Scaling - Impossible de préparer LSFG à partir de ce Lossless.dll - LSFG nécessite Lossless Scaling depuis Steam, ou un fichier Lossless.dll importé LSFG ne peut pas préparer ses shaders à partir de ce Lossless.dll %1$s : non pris en charge %1$s : échec du moteur @@ -648,6 +637,9 @@ Nom d\'hôte Le nom sous lequel Steam voit cet appareil. Laisser vide pour restaurer %1$s. Ne peut contenir que des lettres, des chiffres et des tirets au milieu, jusqu\'à 63 caractères. + Le bureau s’exécute en tant qu’utilisateur + Le bureau, ses applications et ses terminaux s’exécutent en tant qu’utilisateur ordinaire deck au lieu de root, pour les applications qui refusent root. sudo fonctionne toujours. S’applique au prochain bureau. + Nécessite Exécuter sans proot. Android est configuré pour terminer cette session Installé Téléchargeable @@ -1252,6 +1244,11 @@ Préparer Le débogage sans fil n\'est pas accessible ; « Associer » l\'active Associer + Le Quest n\'a pas d\'écran d\'association. Depuis un ordinateur, exécutez une fois : adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS et adb tcpip 5555. Touchez ensuite Autoriser et acceptez la demande dans le casque + Autoriser + Acceptez « Autoriser le débogage ? » dans le casque, avec Toujours autoriser coché + Connexion impossible. Acceptez la demande de débogage dans le casque ou, si elle n\'est pas apparue, exécutez adb tcpip 5555 depuis un ordinateur et réessayez + Le débogage sans fil est injoignable. Touchez Autoriser pour le configurer à nouveau Installer Se connecter PR #%1$d @@ -1320,6 +1317,16 @@ Joy-Con comme manettes VR Pendant que SteamVR tourne, chaque Joy-Con devient une main. Pointez-le devant vous et maintenez Home ou Capture pour le recentrer. Animations + Givré + Affiche votre fond d’écran flouté derrière le lanceur. Consomme plus de batterie. + Fond d’écran givré + Cartes givrées + Les cartes et les groupes laissent transparaître un peu du fond d’écran. Les menus et les boîtes de dialogue restent opaques. + Nécessite le fond d’écran givré. + Transparence du fond d’écran + La part du fond d’écran visible à travers. + Transparence des cartes + La part du fond d’écran visible à travers les cartes. Avertir quand l\'espace de stockage est faible Demander avant de lancer Steam lorsque l\'espace libre est inférieur à 10 Go. Disposition @@ -2155,6 +2162,7 @@ Gauche Centre Droite + Partagé Le menu d’accès rapide de Steam n’est pas encore disponible. Statistiques en jeu HUD de l\'écran du bas @@ -2466,6 +2474,8 @@ %1$s Si ce n\'est pas possible, connectez cet appareil à un ordinateur avec ADB et exécutez la commande ci-dessous. Revenez ensuite ici et vérifiez à nouveau. Les sessions Steam peuvent démarrer. Cette version d\'Android n\'utilise pas cette limite. + Limite de processus enfants gérée par DroidDeck + DroidDeck exécute la plupart des programmes de la session dans des processus qu’Android ne compte pas, ce qui maintient la session bien en dessous de la limite : les options pour les développeurs peuvent rester désactivées. Steam et certains de ses processus auxiliaires sont toujours comptés. Activez « Désactiver les limites pour les processus enfant » dans les options pour les développeurs, puis laissez les options pour les développeurs activées. Cette version d\'Android ne dispose pas de cet interrupteur. Utilisez le débogage sans fil pour le modifier depuis cet appareil. Cette version ne propose aucun téléchargement pour cette copie de DroidDeck. @@ -3228,9 +3238,11 @@ Espace insuffisant (%1$s libres, %2$s nécessaires) Espace libre inconnu Position de l\'image + Position de l\'image (Paysage) + Position de l\'image (Portrait) Haut Bas - Centre (par défaut) + Centre Gauche Droite Stockage @@ -4189,4 +4201,7 @@ Ce jeu installe sa version Linux. Installez-le depuis Steam. Zoom du jeu Réglez le grossissement du jeu de 100 % à 300 % + Raccourci en jeu + Afficher le raccourci Smart Glasses + Afficher le bouton flottant Smart Glasses par-dessus le jeu. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 174f70bfa1..281c5914d5 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG एडैप्टिव %1$d Steam पर Lossless Scaling की ज़रूरत है - Steam में Lossless Scaling इंस्टॉल करें या Lossless.dll इंपोर्ट करें - Lossless.dll इंपोर्ट करें… - Steam वाली कॉपी का उपयोग हो रहा है - इंपोर्ट की गई कॉपी का उपयोग हो रहा है - Lossless.dll चुनें - Lossless.dll इंपोर्ट हो गई - यह Lossless.dll पहले से उपयोग में है - इस Steam खाते में Lossless Scaling नहीं है - यह फ़ाइल Lossless Scaling की Lossless.dll नहीं है - इस Lossless.dll से LSFG तैयार नहीं हो सका - LSFG को Steam से Lossless Scaling या इंपोर्ट की गई Lossless.dll चाहिए LSFG अपने शेडर Lossless.dll से तैयार नहीं कर सका %1$s: असमर्थित %1$s: इंजन विफल @@ -646,6 +635,9 @@ होस्ट नाम वह नाम जो Steam इस डिवाइस के लिए देखता है। खाली छोड़ने पर %1$s वापस आ जाता है। सिर्फ़ अक्षर, अंक और बीच के हाइफ़न, 63 वर्णों तक। + डेस्कटॉप उपयोगकर्ता के रूप में चलता है + डेस्कटॉप, उसके ऐप और टर्मिनल root के बजाय सामान्य उपयोगकर्ता deck के रूप में चलते हैं, उन ऐप के लिए जो root को अस्वीकार करते हैं। sudo फिर भी काम करता है। अगले डेस्कटॉप पर लागू होता है। + proot के बिना चलाएँ आवश्यक है। Android इस सेशन को बंद करने के लिए सेट है इंस्टॉल है डाउनलोड के लिए उपलब्ध @@ -1249,6 +1241,11 @@ तैयार करें वायरलेस डिबगिंग से कनेक्ट नहीं हो पा रहा; पेयर करने से यह चालू हो जाता है पेयर करें + Quest में पेयरिंग स्क्रीन नहीं है। किसी कंप्यूटर से एक बार चलाएँ: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS और adb tcpip 5555। फिर अनुमति दें पर टैप करें और हेडसेट में संकेत स्वीकार करें + अनुमति दें + हेडसेट में “डीबगिंग की अनुमति दें?” स्वीकार करें, हमेशा अनुमति दें चुना हुआ रखें + कनेक्ट नहीं हो सका। हेडसेट में डीबगिंग संकेत स्वीकार करें, या अगर वह नहीं दिखा, तो कंप्यूटर से adb tcpip 5555 चलाएँ और दोबारा कोशिश करें + वायरलेस डीबगिंग तक नहीं पहुँचा जा सकता। इसे फिर से सेट करने के लिए अनुमति दें पर टैप करें इंस्टॉल करें साइन इन करें PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Con को VR कंट्रोलर की तरह SteamVR चलते समय हर Joy-Con एक हाथ बन जाता है। उसे सामने की ओर करें और फिर से केंद्रित करने के लिए Home या Capture दबाए रखें। एनिमेशन + फ़्रॉस्टेड + लॉन्चर के पीछे आपका वॉलपेपर धुंधला दिखाता है। ज़्यादा बैटरी खर्च होती है। + फ़्रॉस्टेड वॉलपेपर + फ़्रॉस्टेड कार्ड + कार्ड और समूह वॉलपेपर का थोड़ा हिस्सा दिखाते हैं। मेन्यू और डायलॉग ठोस रहते हैं। + फ़्रॉस्टेड वॉलपेपर ज़रूरी है। + वॉलपेपर की पारदर्शिता + वॉलपेपर कितना दिखता है। + कार्ड की पारदर्शिता + कार्ड के पार वॉलपेपर कितना दिखता है। स्टोरेज कम होने पर चेतावनी दें खाली जगह 10 GB से कम होने पर Steam शुरू करने से पहले पूछें। लेआउट @@ -2131,6 +2138,7 @@ बाएँ बीच में दाएँ + विभाजित Steam का क्विक एक्सेस मेनू अभी उपलब्ध नहीं है। इन-गेम आंकड़े निचली स्क्रीन HUD @@ -2441,6 +2449,8 @@ %1$s अगर यह संभव नहीं है, तो इस डिवाइस को ADB वाले कंप्यूटर से कनेक्ट करें और नीचे दिया कमांड चलाएं। यहां वापस आएं और फिर से जांचें। Steam सेशन शुरू हो सकते हैं। यह Android वर्शन इस सीमा का उपयोग नहीं करता। + चाइल्ड-प्रोसेस सीमा DroidDeck संभालता है + DroidDeck सत्र के ज़्यादातर प्रोग्राम उन प्रोसेस में चलाता है जिन्हें Android नहीं गिनता, जिससे सत्र सीमा से काफ़ी नीचे रहता है, इसलिए डेवलपर विकल्प बंद रह सकते हैं। Steam और उसके कुछ सहायक प्रोसेस अब भी गिने जाते हैं। डेवलपर विकल्प में “चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” चालू करें, और बाद में डेवलपर विकल्प चालू रहने दें। इस Android वर्शन में इसके लिए कोई स्विच नहीं है। इसे इस डिवाइस से बदलने के लिए वायरलेस डीबगिंग इस्तेमाल करें। इस बिल्ड में DroidDeck की इस कॉपी के लिए कोई डाउनलोड नहीं है। @@ -3199,9 +3209,11 @@ %1$s घं %1$d मि चित्र की स्थिति + चित्र की स्थिति (लैंडस्केप) + चित्र की स्थिति (पोर्ट्रेट) ऊपर नीचे - बीच में (डिफ़ॉल्ट) + बीच में बाएँ दाएँ स्टोरेज @@ -4150,4 +4162,7 @@ यह गेम अपना Linux संस्करण इंस्टॉल करता है। इसे Steam से इंस्टॉल करें। गेम ज़ूम गेम का ज़ूम 100% से 300% तक समायोजित करें + गेम में शॉर्टकट + Smart Glasses शॉर्टकट दिखाएँ + गेम के ऊपर तैरता हुआ Smart Glasses बटन दिखाएँ। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 5fdb4a5a66..a74cef1df8 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptív %1$d A Lossless Scaling szükséges a Steamen - Telepítse a Lossless Scalinget a Steamen, vagy importálja a Lossless.dll fájlt - Lossless.dll importálása… - A Steamről származó másolat használatban - Egy importált másolat használatban - Válassza ki a Lossless.dll fájlt - A Lossless.dll importálva - Ez a Lossless.dll már használatban van - A Lossless Scaling nincs a tulajdonában ezen a Steam-fiókon - Ez a fájl nem a Lossless Scaling Lossless.dll fájlja - Nem sikerült előkészíteni az LSFG-t ebből a Lossless.dll fájlból - Az LSFG-hez szükséges a Lossless Scaling a Steamről vagy egy importált Lossless.dll Az LSFG nem tudta előkészíteni a shadereket a Lossless.dll fájlból %1$s: nem támogatott %1$s: a motor hibát jelzett @@ -646,6 +635,9 @@ Hosztnév A név, amelyet a Steam ehhez az eszközhöz lát. Üresen hagyva visszaállítja: %1$s. Csak betűk, számok és belső kötőjelek, legfeljebb 63 karakter. + Az asztal felhasználóként fut + Az asztal, az alkalmazásai és a termináljai root helyett a deck nevű átlagos felhasználóként futnak, a root-ot elutasító alkalmazások miatt. A sudo továbbra is működik. A következő asztaltól érvényes. + A Futtatás proot nélkül szükséges hozzá. Az Android be van állítva, hogy kilője ezt a munkamenetet Telepítve Letölthető @@ -1249,6 +1241,11 @@ Előkészítés A vezeték nélküli hibakeresés nem érhető el; a Párosítás bekapcsolja Párosítás + A Quest nem rendelkezik párosítási képernyővel. Egy számítógépről futtasd egyszer: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS és adb tcpip 5555. Ezután koppints az Engedélyezés gombra, és fogadd el a kérdést a headsetben + Engedélyezés + Fogadd el az „Engedélyezed a hibakeresést?” kérdést a headsetben, a Mindig engedélyez bejelölésével + Nem sikerült csatlakozni. Fogadd el a hibakeresési kérdést a headsetben, vagy ha nem jelent meg, futtasd az adb tcpip 5555 parancsot egy számítógépről, és próbáld újra + A vezeték nélküli hibakeresés nem érhető el. Koppints az Engedélyezés gombra az újbóli beállításhoz Telepítés Bejelentkezés PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Conok VR-kontrollerként Amíg a SteamVR fut, minden Joy-Con egy kéz lesz. Irányítsa előre, és tartsa lenyomva a Home vagy a Capture gombot az újraközpontosításhoz. Animációk + Matt + A háttérképet elmosva jeleníti meg az indítóalkalmazás mögött. Több akkumulátort használ. + Matt háttérkép + Matt kártyák + A kártyák és csoportok átengednek egy kicsit a háttérképből. A menük és párbeszédablakok átlátszatlanok maradnak. + Matt háttérkép szükséges hozzá. + Háttérkép átlátszósága + Mennyi látszik át a háttérképből. + Kártyák átlátszósága + Mennyi látszik a háttérképből a kártyákon át. Figyelmeztetés kevés tárhely esetén Rákérdezés a Steam indítása előtt, ha 10 GB-nál kevesebb a szabad hely. Elrendezés @@ -2131,6 +2138,7 @@ Balra Középen Jobbra + Osztott A Steam gyorselérési menüje még nem érhető el. Játékon belüli statisztikák HUD az alsó képernyőn @@ -2441,6 +2449,8 @@ %1$s Ha ez nem lehetséges, csatlakoztassa ezt az eszközt egy ADB-vel rendelkező számítógéphez, és futtassa az alábbi parancsot. Térjen vissza ide, és ellenőrizze újra. A Steam-munkamenetek elindulhatnak. Ez az Android-verzió nem használja ezt a korlátot. + A gyermekfolyamat-korlátot a DroidDeck kezeli + A DroidDeck a munkamenet legtöbb programját olyan folyamatokban futtatja, amelyeket az Android nem számol bele, így a munkamenet jóval a korlát alatt marad, és a fejlesztői beállítások kikapcsolva maradhatnak. A Steam és néhány segédfolyamata továbbra is beleszámít. Kapcsolja be az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget a Fejlesztői beállításokban, és utána hagyja bekapcsolva a Fejlesztői beállításokat. Ehhez az Android-verzióhoz nincs kapcsoló. Használja a vezeték nélküli hibakeresést a módosításához erről az eszközről. Ehhez a buildhez nincs letöltés a DroidDeck ezen másolatához. @@ -3199,9 +3209,11 @@ %1$s óra %1$d perc A kép pozíciója + A kép pozíciója (Fekvő) + A kép pozíciója (Álló) Fent Lent - Középen (alapértelmezett) + Középen Bal Jobb Tárhely @@ -4150,4 +4162,7 @@ Ez a játék a Linux-verzióját telepíti. Telepítsd a Steamből. Játék nagyítása A játék nagyításának beállítása 100% és 300% között + Játékon belüli parancsikon + Smart Glasses parancsikon megjelenítése + A játék fölött lebegő Smart Glasses gomb megjelenítése. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 09891934b8..8bd5840655 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptif %1$d Memerlukan Lossless Scaling di Steam - Instal Lossless Scaling di Steam atau impor Lossless.dll - Impor Lossless.dll… - Menggunakan salinan dari Steam - Menggunakan salinan yang diimpor - Pilih Lossless.dll - Lossless.dll diimpor - Lossless.dll ini sudah digunakan - Lossless Scaling tidak dimiliki di akun Steam ini - File ini bukan Lossless.dll milik Lossless Scaling - Tidak dapat menyiapkan LSFG dari Lossless.dll ini - LSFG memerlukan Lossless Scaling dari Steam atau Lossless.dll yang diimpor LSFG tidak dapat menyiapkan shader-nya dari Lossless.dll %1$s: tidak didukung %1$s: mesin gagal @@ -644,6 +633,9 @@ Nama host Nama yang dilihat Steam untuk perangkat ini. Kosongkan untuk memulihkan %1$s. Hanya huruf, angka, dan tanda hubung di tengah, hingga 63 karakter. + Desktop berjalan sebagai pengguna + Desktop, aplikasi, dan terminalnya berjalan sebagai pengguna biasa deck, bukan root, untuk aplikasi yang menolak root. sudo tetap berfungsi. Berlaku untuk desktop berikutnya. + Memerlukan Jalankan tanpa proot. Android diatur untuk menghentikan sesi ini Terinstal Tersedia untuk diunduh @@ -1246,6 +1238,11 @@ Siapkan Debug nirkabel tidak dapat dijangkau; Pasangkan menyalakannya Pasangkan + Quest tidak memiliki layar penyambungan. Dari komputer, jalankan sekali: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS dan adb tcpip 5555. Lalu ketuk Izinkan dan terima permintaan di headset + Izinkan + Terima “Izinkan debugging?” di headset, dengan Selalu izinkan dicentang + Tidak dapat terhubung. Terima permintaan debugging di headset, atau jika tidak muncul, jalankan adb tcpip 5555 dari komputer lalu coba lagi + Debugging nirkabel tidak dapat dijangkau. Ketuk Izinkan untuk menyiapkannya lagi Pasang Masuk PR #%1$d @@ -1308,6 +1305,16 @@ Joy-Con sebagai pengontrol VR Saat SteamVR berjalan, setiap Joy-Con menjadi tangan. Arahkan ke depan lalu tahan Home atau Capture untuk memusatkannya kembali. Animasi + Buram + Menampilkan wallpaper Anda yang diburamkan di belakang peluncur. Memakai lebih banyak baterai. + Wallpaper buram + Kartu buram + Kartu dan grup menampilkan sedikit wallpaper. Menu dan dialog tetap solid. + Memerlukan wallpaper buram. + Transparansi wallpaper + Seberapa banyak wallpaper yang terlihat. + Transparansi kartu + Seberapa banyak wallpaper yang terlihat melalui kartu. Peringatkan saat penyimpanan hampir penuh Tanya sebelum memulai Steam saat ruang kosong di bawah 10 GB. Tata letak @@ -2107,6 +2114,7 @@ Kiri Tengah Kanan + Terbagi Menu Akses Cepat Steam belum tersedia. Statistik dalam gim HUD layar bawah @@ -2416,6 +2424,8 @@ %1$s Jika itu tidak memungkinkan, sambungkan perangkat ini ke komputer dengan ADB dan jalankan perintah di bawah. Kembali ke sini dan periksa lagi. Sesi Steam dapat dimulai. Versi Android ini tidak menggunakan batas ini. + Batas proses anak ditangani DroidDeck + DroidDeck menjalankan sebagian besar program sesi dalam proses yang tidak dihitung Android, sehingga sesi tetap jauh di bawah batas dan Opsi developer bisa tetap nonaktif. Steam dan beberapa proses pembantunya masih dihitung. Aktifkan “Nonaktifkan batasan proses turunan” di Opsi developer, dan biarkan Opsi developer tetap aktif setelahnya. Versi Android ini tidak memiliki sakelar untuk itu. Gunakan Debugging nirkabel untuk mengubahnya dari perangkat ini. Build ini tidak memiliki unduhan untuk salinan DroidDeck ini. @@ -3170,9 +3180,11 @@ %1$s j %1$d mnt Posisi gambar + Posisi gambar (Lanskap) + Posisi gambar (Potret) Atas Bawah - Tengah (bawaan) + Tengah Kiri Kanan Penyimpanan @@ -4120,4 +4132,7 @@ Game ini memasang versi Linux-nya. Pasang dari Steam. Zoom game Sesuaikan pembesaran game dari 100% hingga 300% + Pintasan dalam game + Tampilkan pintasan Smart Glasses + Tampilkan tombol Smart Glasses mengambang di atas game. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 4aaee8b446..0d79a90921 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adattivo %1$d Richiede Lossless Scaling su Steam - Installa Lossless Scaling in Steam o importa Lossless.dll - Importa Lossless.dll… - In uso la copia di Steam - In uso una copia importata - Scegli Lossless.dll - Lossless.dll importato - Questo Lossless.dll è già in uso - Questo account Steam non possiede Lossless Scaling - Questo file non è il Lossless.dll di Lossless Scaling - Impossibile preparare LSFG da questo Lossless.dll - LSFG richiede Lossless Scaling da Steam o un Lossless.dll importato LSFG non è riuscito a preparare gli shader da Lossless.dll %1$s: non supportato %1$s: errore del motore @@ -648,6 +637,9 @@ Nome host Il nome con cui Steam vede questo dispositivo. Se vuoto, torna a %1$s. Solo lettere, cifre e trattini interni, fino a 63 caratteri. + Il desktop viene eseguito come utente + Il desktop, le sue app e i suoi terminali vengono eseguiti come utente normale deck invece che come root, per le app che rifiutano root. sudo funziona comunque. Si applica al prossimo desktop. + Richiede Esegui senza proot. Android è impostato per terminare questa sessione Installati Disponibili per il download @@ -1244,6 +1236,11 @@ Prepara Il debug wireless non è raggiungibile; Associa lo attiva Associa + Quest non ha una schermata di accoppiamento. Da un computer, esegui una volta: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS e adb tcpip 5555. Poi tocca Consenti e accetta la richiesta nel visore + Consenti + Accetta «Consentire il debug?» nel visore, con Consenti sempre selezionato + Impossibile connettersi. Accetta la richiesta di debug nel visore oppure, se non è comparsa, esegui adb tcpip 5555 da un computer e riprova + Il debug wireless non è raggiungibile. Tocca Consenti per configurarlo di nuovo Installa Accedi PR #%1$d @@ -1312,6 +1309,16 @@ Joy-Con come controller VR Mentre SteamVR è in esecuzione, ogni Joy-Con diventa una mano. Puntalo in avanti e tieni premuto Home o Capture per ricentrarlo. Animazioni + Satinato + Mostra il tuo sfondo sfocato dietro il launcher. Consuma più batteria. + Sfondo satinato + Schede satinate + Schede e gruppi lasciano trasparire un po’ dello sfondo. Menu e finestre di dialogo restano opachi. + Richiede lo sfondo satinato. + Trasparenza dello sfondo + Quanto dello sfondo si vede attraverso. + Trasparenza delle schede + Quanto dello sfondo si vede attraverso le schede. Avvisa quando lo spazio è scarso Chiedi conferma prima di avviare Steam quando lo spazio libero è inferiore a 10 GB. Layout @@ -2147,6 +2154,7 @@ Sinistra Centro Destra + Diviso Il menu di accesso rapido di Steam non è ancora disponibile. Statistiche di gioco HUD dello schermo inferiore @@ -2458,6 +2466,8 @@ %1$s Se non è possibile, collega questo dispositivo a un computer con ADB ed esegui il comando qui sotto. Poi torna qui e ricontrolla. Le sessioni Steam possono avviarsi. Questa versione di Android non usa questo limite. + Limite dei processi figli gestito da DroidDeck + DroidDeck esegue la maggior parte dei programmi della sessione in processi che Android non conteggia, così la sessione resta ben al di sotto del limite e le Opzioni sviluppatore possono restare disattivate. Steam e alcuni dei suoi processi di supporto vengono ancora conteggiati. Attiva “Disattiva limitazioni per i processi secondari” in Opzioni sviluppatore e poi lascia attive le Opzioni sviluppatore. Questa versione di Android non ha un interruttore per farlo. Usa il debug wireless per cambiarlo da questo dispositivo. Questa build non ha un download per questa copia di DroidDeck. @@ -3228,9 +3238,11 @@ Spazio insufficiente (%1$s liberi, ne servono %2$s) Spazio libero sconosciuto Posizione immagine + Posizione immagine (Orizzontale) + Posizione immagine (Verticale) In alto In basso - Centro (predefinito) + Centro Sinistra Destra Archiviazione @@ -4189,4 +4201,7 @@ Questo gioco installa la sua versione Linux. Installalo da Steam. Zoom del gioco Regola l\'ingrandimento del gioco dal 100% al 300% + Scorciatoia nel gioco + Mostra scorciatoia Smart Glasses + Mostra il pulsante mobile Smart Glasses sopra il gioco. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 157a2b6627..f66a14fc6e 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG アダプティブ %1$d Steam版のLossless Scalingが必要です - SteamでLossless Scalingをインストールするか、Lossless.dllをインポートしてください - Lossless.dllをインポート… - Steam版を使用中 - インポート版を使用中 - Lossless.dllファイルを選択 - Lossless.dllをインポートしました - このLossless.dllはすでに使用されています - このSteamアカウントはLossless Scalingを所有していません - このファイルはLossless ScalingのLossless.dllではありません - このLossless.dllからLSFGを準備できませんでした - LSFGにはSteam版のLossless Scaling、またはインポートされたLossless.dllファイルが必要です LSFGはこのLossless.dllからシェーダーを準備できませんでした %1$s:サポート外 %1$s:エンジンエラー @@ -644,6 +633,9 @@ ホスト名 Steamがこのデバイスを認識する名前。空にすると%1$sに戻ります。 英数字と中間のハイフンのみ使用でき、最大63文字です。 + デスクトップをユーザーとして実行 + デスクトップとそのアプリやターミナルを root ではなく一般ユーザー deck として実行します。root を拒否するアプリ向けです。sudo は引き続き使えます。次回のデスクトップから適用されます。 + proot なしで実行が必要です。 Androidがこのセッションを終了するように設定されています インストール済み ダウンロード可能 @@ -1246,6 +1238,11 @@ 準備 ワイヤレスデバッグに接続できません。ペアリングで有効になります ペアリング + Quest にはペア設定画面がありません。パソコンから一度だけ adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS と adb tcpip 5555 を実行し、[許可] をタップしてヘッドセットの確認を承認してください + 許可 + ヘッドセットで「デバッグを許可しますか?」を、[常に許可] にチェックを入れて承認してください + 接続できませんでした。ヘッドセットでデバッグの確認を承認してください。表示されなかった場合は、パソコンから adb tcpip 5555 を実行してもう一度お試しください + ワイヤレス デバッグに接続できません。[許可] をタップして設定し直してください インストール サインイン PR #%1$d @@ -1308,6 +1305,16 @@ Joy-ConをVRコントローラーとして使う SteamVRの実行中は各Joy-Conが手になります。前に向けてHOMEボタンかキャプチャーボタンを長押しすると、向きを合わせ直します。 アニメーション + すりガラス + ランチャーの背後に壁紙をぼかして表示します。バッテリーの消費が増えます。 + すりガラスの壁紙 + すりガラスのカード + カードやグループから壁紙が少し透けて見えます。メニューとダイアログは不透明のままです。 + すりガラスの壁紙が必要です。 + 壁紙の透明度 + 壁紙がどれだけ透けて見えるか。 + カードの透明度 + カード越しに壁紙がどれだけ透けて見えるか。 ストレージ残量が少ないときに警告する 空き容量が 10 GB 未満のとき、Steam を起動する前に確認します。 レイアウト @@ -2107,6 +2114,7 @@ 左 中央 右 + 分割 Steam のクイックアクセスメニューはまだ使えません。 ゲーム内統計 下部画面の HUD @@ -2416,6 +2424,8 @@ %1$s それができない場合は、このデバイスをADBが使えるPCに接続し、以下のコマンドを実行してください。その後ここに戻って再確認してください。 Steamセッションを開始できます。 このAndroidバージョンではこの制限は使用されません。 + 子プロセスの制限は DroidDeck が対処します + DroidDeck はセッションのほとんどのプログラムを Android が数えないプロセスで実行するため、セッションは上限を大きく下回り、開発者向けオプションはオフのままでかまいません。Steam とその補助プロセスの一部は引き続き数えられます。 開発者向けオプションで「子プロセスの制限を無効化」をオンにし、その後も開発者向けオプションをオンのままにしてください。 このAndroidバージョンにはこのスイッチがありません。ワイヤレスデバッグを使って、このデバイスから変更してください。 このビルドには、このDroidDeckコピー用のダウンロードがありません。 @@ -3170,9 +3180,11 @@ ダウンロードは「コンポーネント」ページと共有されます。上でダウンロード済みのバージョンを選ぶと、次回のゲーム起動時に使用されます。 ダウンロードするバージョンを選択 画面の位置 + 画面の位置(横向き) + 画面の位置(縦向き) 上 下 - 中央(既定) + 中央 左 右 ストレージ @@ -4120,4 +4132,7 @@ このゲームは Linux 版をインストールします。Steam からインストールしてください。 ゲームズーム ゲームの拡大率を100%から300%の間で調整します + ゲーム内ショートカット + Smart Glasses のショートカットを表示 + ゲーム画面上に Smart Glasses のフローティングボタンを表示します。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index cd41e8aa47..dbcf405e3f 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG 적응형 %1$d Steam에서 Lossless Scaling이 필요합니다 - Steam에서 Lossless Scaling을 설치하거나 Lossless.dll을 가져오세요 - Lossless.dll 가져오기… - Steam 버전 사용 중 - 가져온 버전 사용 중 - Lossless.dll 파일 선택 - Lossless.dll을 가져왔습니다 - 이 Lossless.dll은 이미 사용 중입니다 - 이 Steam 계정에는 Lossless Scaling이 없습니다 - 이 파일은 Lossless Scaling의 Lossless.dll이 아닙니다 - 이 Lossless.dll에서 LSFG를 준비할 수 없습니다 - LSFG에는 Steam의 Lossless Scaling 또는 가져온 Lossless.dll 파일이 필요합니다 LSFG가 이 Lossless.dll에서 셰이더를 준비할 수 없습니다 %1$s: 지원되지 않음 %1$s: 엔진 실패 @@ -644,6 +633,9 @@ 호스트 이름 Steam이 이 기기를 인식하는 이름입니다. 비워 두면 %1$s(으)로 복원됩니다. 영문, 숫자 및 중간 하이픈만 사용할 수 있으며 최대 63자입니다. + 데스크톱을 사용자로 실행 + 데스크톱과 앱, 터미널이 root 대신 일반 사용자 deck으로 실행됩니다. root를 거부하는 앱을 위한 설정입니다. sudo는 계속 사용할 수 있습니다. 다음 데스크톱부터 적용됩니다. + proot 없이 실행이 필요합니다. Android가 이 세션을 종료하도록 설정했습니다 설치됨 다운로드 가능 @@ -1246,6 +1238,11 @@ 준비 무선 디버깅에 연결할 수 없습니다. 페어링하면 켜집니다 페어링 + Quest에는 페어링 화면이 없습니다. 컴퓨터에서 한 번 실행하세요: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 및 adb tcpip 5555. 그런 다음 허용을 탭하고 헤드셋에서 요청을 수락하세요 + 허용 + 헤드셋에서 \'디버깅을 허용하시겠습니까?\'를 항상 허용을 선택한 채로 수락하세요 + 연결하지 못했습니다. 헤드셋에서 디버깅 요청을 수락하거나, 요청이 나타나지 않았다면 컴퓨터에서 adb tcpip 5555를 실행한 뒤 다시 시도하세요 + 무선 디버깅에 연결할 수 없습니다. 허용을 탭해 다시 설정하세요 설치 로그인 PR #%1$d @@ -1308,6 +1305,16 @@ Joy-Con을 VR 컨트롤러로 사용 SteamVR이 실행되는 동안 각 Joy-Con이 손이 됩니다. 앞을 향하게 한 채 HOME 또는 캡처 버튼을 길게 누르면 다시 가운데로 맞춥니다. 애니메이션 + 반투명 + 런처 뒤에 배경화면을 흐리게 표시합니다. 배터리를 더 많이 사용합니다. + 반투명 배경화면 + 반투명 카드 + 카드와 그룹에 배경화면이 살짝 비쳐 보입니다. 메뉴와 대화상자는 불투명하게 유지됩니다. + 반투명 배경화면이 필요합니다. + 배경화면 투명도 + 배경화면이 얼마나 비쳐 보이는지 정합니다. + 카드 투명도 + 카드 너머로 배경화면이 얼마나 비쳐 보이는지 정합니다. 저장 공간이 부족할 때 경고 여유 공간이 10GB 미만이면 Steam을 시작하기 전에 확인합니다. 레이아웃 @@ -2107,6 +2114,7 @@ 왼쪽 가운데 오른쪽 + 분할 Steam 빠른 메뉴를 아직 사용할 수 없습니다. 게임 내 통계 하단 화면 HUD @@ -2416,6 +2424,8 @@ %1$s 이 방법을 사용할 수 없으면 이 기기를 ADB가 설치된 PC에 연결하고 아래 명령을 실행하세요. 그런 다음 여기로 돌아와 다시 확인하세요. Steam 세션을 시작할 수 있습니다. 이 Android 버전에서는 이 제한을 사용하지 않습니다. + 하위 프로세스 제한은 DroidDeck이 처리합니다 + DroidDeck은 세션 프로그램 대부분을 Android가 세지 않는 프로세스에서 실행하므로 세션이 한도보다 훨씬 낮게 유지되어 개발자 옵션을 꺼 둔 채로 두어도 됩니다. Steam과 일부 보조 프로세스는 여전히 집계됩니다. 개발자 옵션에서 “하위 프로세스 제한 사용 중지”를 켜고, 이후에도 개발자 옵션을 켜 둔 상태로 유지하세요. 이 Android 버전에는 해당 스위치가 없습니다. 무선 디버깅을 사용하여 이 기기에서 변경하세요. 이 빌드에는 이 DroidDeck 복사본용 다운로드가 없습니다. @@ -3170,9 +3180,11 @@ 다운로드는 구성 요소 페이지와 공유됩니다. 위에서 다운로드한 버전을 선택하면 다음 게임 실행 시 사용됩니다. 다운로드할 버전 선택 화면 위치 + 화면 위치 (가로 모드) + 화면 위치 (세로) 위 아래 - 가운데(기본) + 가운데 왼쪽 오른쪽 저장 공간 @@ -4120,4 +4132,7 @@ 이 게임은 Linux 버전을 설치합니다. Steam에서 설치하세요. 게임 확대 게임 확대율을 100%에서 300%까지 조정합니다 + 게임 내 바로가기 + Smart Glasses 바로가기 표시 + 게임 위에 떠 있는 Smart Glasses 버튼을 표시합니다. diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 92d613f184..2dc5bcea1b 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptif %1$d Memerlukan Lossless Scaling pada Steam - Pasang Lossless Scaling dalam Steam atau import Lossless.dll - Import Lossless.dll… - Menggunakan salinan daripada Steam - Menggunakan salinan yang diimport - Pilih Lossless.dll - Lossless.dll diimport - Lossless.dll ini sudah digunakan - Lossless Scaling tidak dimiliki pada akaun Steam ini - Fail ini bukan Lossless.dll milik Lossless Scaling - Tidak dapat menyediakan LSFG daripada Lossless.dll ini - LSFG memerlukan Lossless Scaling daripada Steam atau Lossless.dll yang diimport LSFG tidak dapat menyediakan shadernya daripada Lossless.dll %1$s: tidak disokong %1$s: enjin gagal @@ -644,6 +633,9 @@ Nama hos Nama yang dilihat Steam untuk peranti ini. Kosongkan untuk memulihkan %1$s. Huruf, digit dan tanda sempang dalaman sahaja, sehingga 63 aksara. + Desktop berjalan sebagai pengguna + Desktop, aplnya dan terminalnya berjalan sebagai pengguna biasa deck dan bukan root, untuk apl yang menolak root. sudo masih berfungsi. Berkuat kuasa pada desktop seterusnya. + Memerlukan Jalankan tanpa proot. Android ditetapkan untuk menamatkan sesi ini Dipasang Tersedia untuk dimuat turun @@ -1246,6 +1238,11 @@ Sediakan Penyahpepijatan wayarles tidak dapat dicapai; Pasangkan menghidupkannya Pasangkan + Quest tiada skrin pasangan. Dari komputer, jalankan sekali: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS dan adb tcpip 5555. Kemudian ketik Benarkan dan terima gesaan dalam set kepala + Benarkan + Terima “Benarkan penyahpepijatan?” dalam set kepala, dengan Sentiasa benarkan ditanda + Tidak dapat bersambung. Terima gesaan penyahpepijatan dalam set kepala, atau jika tiada, jalankan adb tcpip 5555 dari komputer dan cuba lagi + Penyahpepijatan wayarles tidak dapat dicapai. Ketik Benarkan untuk menyediakannya semula Pasang Log masuk PR #%1$d @@ -1308,6 +1305,16 @@ Joy-Con sebagai pengawal VR Semasa SteamVR berjalan, setiap Joy-Con menjadi tangan. Halakan ke hadapan dan tahan Home atau Capture untuk memusatkannya semula. Animasi + Kabur + Memaparkan kertas dinding anda yang dikaburkan di belakang pelancar. Menggunakan lebih banyak bateri. + Kertas dinding kabur + Kad kabur + Kad dan kumpulan menampakkan sedikit kertas dinding. Menu dan dialog kekal padu. + Memerlukan kertas dinding kabur. + Ketelusan kertas dinding + Berapa banyak kertas dinding yang kelihatan. + Ketelusan kad + Berapa banyak kertas dinding yang kelihatan melalui kad. Beri amaran apabila storan rendah Tanya sebelum memulakan Steam apabila ruang kosong kurang daripada 10 GB. Susun atur @@ -2107,6 +2114,7 @@ Kiri Tengah Kanan + Terbahagi Menu Akses Pantas Steam belum tersedia. Statistik dalam permainan HUD skrin bawah @@ -2416,6 +2424,8 @@ %1$s Jika itu tidak boleh, sambungkan peranti ini ke komputer dengan ADB dan jalankan arahan di bawah. Kembali ke sini dan semak semula. Sesi Steam boleh dimulakan. Versi Android ini tidak menggunakan had ini. + Had proses anak dikendalikan oleh DroidDeck + DroidDeck menjalankan kebanyakan program sesi dalam proses yang tidak dikira oleh Android, jadi sesi kekal jauh di bawah had dan Pilihan pembangun boleh kekal dimatikan. Steam dan sesetengah proses pembantunya masih dikira. Hidupkan “Lumpuhkan sekatan proses anak” dalam Pilihan pembangun, dan biarkan Pilihan pembangun hidup selepas itu. Versi Android ini tidak mempunyai suis untuknya. Gunakan Debugging Wayarles untuk menukarnya daripada peranti ini. Binaan ini tidak mempunyai muat turun untuk salinan DroidDeck ini. @@ -3170,9 +3180,11 @@ %1$s j %1$d min Kedudukan gambar + Kedudukan gambar (Lanskap) + Kedudukan gambar (Potret) Atas Bawah - Tengah (lalai) + Tengah Kiri Kanan Storan @@ -4120,4 +4132,7 @@ Permainan ini memasang versi Linuxnya. Pasang daripada Steam. Zum permainan Laraskan pembesaran permainan daripada 100% hingga 300% + Pintasan dalam permainan + Tunjukkan pintasan Smart Glasses + Tunjukkan butang Smart Glasses terapung di atas permainan. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index edc7b5fa51..70da47fde8 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptiv %1$d Krever Lossless Scaling på Steam - Installer Lossless Scaling via Steam, eller importer Lossless.dll - Importer Lossless.dll… - Bruker kopien fra Steam - Bruker en importert kopi - Velg Lossless.dll - Lossless.dll importert - Denne Lossless.dll-filen er allerede i bruk - Lossless Scaling eies ikke av denne Steam-kontoen - Denne filen er ikke Lossless Scalings Lossless.dll - Kunne ikke forberede LSFG fra denne Lossless.dll-filen - LSFG krever Lossless Scaling fra Steam eller en importert Lossless.dll LSFG kunne ikke forberede shaderne sine fra Lossless.dll %1$s: ikke støttet %1$s: motoren feilet @@ -646,6 +635,9 @@ Vertsnavn Navnet Steam ser for denne enheten. Tomt gjenoppretter %1$s. Bare bokstaver, tall og bindestreker inni navnet, opptil 63 tegn. + Skrivebordet kjører som bruker + Skrivebordet, appene og terminalene kjører som den vanlige brukeren deck i stedet for root, for apper som avviser root. sudo virker fortsatt. Gjelder fra neste skrivebord. + Krever Kjør uten proot. Android er satt til å avslutte denne sesjonen Installert Tilgjengelig for nedlasting @@ -1249,6 +1241,11 @@ Forbered Trådløs feilsøking er ikke tilgjengelig; Par slår den på Par + Quest har ingen sammenkoblingsskjerm. Kjør én gang fra en datamaskin: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS og adb tcpip 5555. Trykk deretter på Tillat og godta spørsmålet i hodesettet + Tillat + Godta «Vil du tillate feilsøking?» i hodesettet med Tillat alltid avkrysset + Kunne ikke koble til. Godta feilsøkingsspørsmålet i hodesettet, eller kjør adb tcpip 5555 fra en datamaskin og prøv igjen hvis det ikke dukket opp + Trådløs feilsøking kan ikke nås. Trykk på Tillat for å sette den opp på nytt Installer Logg inn PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Con som VR-kontrollere Mens SteamVR kjører, blir hver Joy-Con en hånd. Pek den fremover og hold inne Home eller Capture for å sentrere den på nytt. Animasjoner + Matt + Viser bakgrunnsbildet ditt uskarpt bak launcheren. Bruker mer batteri. + Matt bakgrunnsbilde + Matte kort + Kort og grupper slipper litt av bakgrunnsbildet gjennom. Menyer og dialoger forblir heldekkende. + Krever matt bakgrunnsbilde. + Bakgrunnens gjennomsiktighet + Hvor mye av bakgrunnsbildet som synes gjennom. + Kortenes gjennomsiktighet + Hvor mye av bakgrunnsbildet som synes gjennom kortene. Advar når lagringsplassen er lav Spør før Steam startes når ledig plass er under 10 GB. Oppsett @@ -2131,6 +2138,7 @@ Venstre Midten Høyre + Delt Steams hurtigtilgangsmeny er ikke tilgjengelig ennå. Statistikk i spillet HUD på bunnskjermen @@ -2441,6 +2449,8 @@ %1$s Hvis det ikke er mulig, koble denne enheten til en datamaskin med ADB og kjør kommandoen under. Kom tilbake hit og kontroller igjen. Steam-sesjoner kan starte. Denne Android-versjonen bruker ikke denne grensen. + DroidDeck håndterer grensen for underprosesser + DroidDeck kjører de fleste programmene i økten i prosesser som Android ikke teller med, så økten holder seg godt under grensen og utvikleralternativer kan forbli av. Steam og noen av hjelpeprosessene dens telles fortsatt. Slå på «Slå av begrensninger for underordnede prosesser» i Utvikleralternativer, og la Utvikleralternativer stå på etterpå. Denne Android-versjonen har ingen bryter for det. Bruk trådløs feilsøking for å endre det fra denne enheten. Denne builden har ingen nedlasting for denne kopien av DroidDeck. @@ -3199,9 +3209,11 @@ %1$s t %1$d min Bildets posisjon + Bildets posisjon (Liggende) + Bildets posisjon (Stående) Øverst Nederst - Midten (standard) + Midten Venstre Høyre Lagring @@ -4150,4 +4162,7 @@ Dette spillet installerer Linux-versjonen sin. Installer det fra Steam. Spillzoom Juster spillforstørrelsen fra 100 % til 300 % + Snarvei i spillet + Vis Smart Glasses-snarvei + Vis den flytende Smart Glasses-knappen over spillet. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 77808b5f3c..aa95f349be 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptief %1$d Vereist Lossless Scaling op Steam - Installeer Lossless Scaling in Steam of importeer Lossless.dll - Lossless.dll importeren… - De kopie uit Steam wordt gebruikt - Een geïmporteerde kopie wordt gebruikt - Kies Lossless.dll - Lossless.dll geïmporteerd - Deze Lossless.dll wordt al gebruikt - Lossless Scaling staat niet op dit Steam-account - Dit bestand is niet de Lossless.dll van Lossless Scaling - Kan LSFG niet voorbereiden met deze Lossless.dll - LSFG vereist Lossless Scaling uit Steam of een geïmporteerde Lossless.dll LSFG kan zijn shaders niet voorbereiden uit Lossless.dll %1$s: niet ondersteund %1$s: engine mislukt @@ -646,6 +635,9 @@ Hostnaam De naam die Steam voor dit apparaat ziet. Leeg herstelt %1$s. Alleen letters, cijfers en koppeltekens binnen de naam, tot 63 tekens. + Bureaublad draait als gebruiker + Het bureaublad, de apps en terminals draaien als de gewone gebruiker deck in plaats van root, voor apps die root weigeren. sudo werkt nog steeds. Geldt vanaf het volgende bureaublad. + Vereist Uitvoeren zonder proot. Android is ingesteld om deze sessie te sluiten Geïnstalleerd Beschikbaar om te downloaden @@ -1249,6 +1241,11 @@ Voorbereiden Draadloze foutopsporing is niet bereikbaar; Koppelen schakelt dit in Koppelen + Quest heeft geen koppelscherm. Voer vanaf een computer één keer uit: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS en adb tcpip 5555. Tik daarna op Toestaan en accepteer de melding in de headset + Toestaan + Accepteer ‘Foutopsporing toestaan?’ in de headset, met Altijd toestaan aangevinkt + Verbinden mislukt. Accepteer de foutopsporingsmelding in de headset, of voer adb tcpip 5555 uit vanaf een computer en probeer het opnieuw als er geen verscheen + Draadloze foutopsporing is niet bereikbaar. Tik op Toestaan om het opnieuw in te stellen Installeren Inloggen PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Cons als VR-controllers Zolang SteamVR draait, wordt elke Joy-Con een hand. Richt hem naar voren en houd Home of Capture ingedrukt om hem opnieuw te centreren. Animaties + Matglas + Toont je achtergrond wazig achter de launcher. Verbruikt meer batterij. + Matglazen achtergrond + Matglazen kaarten + Kaarten en groepen laten iets van de achtergrond door. Menu’s en dialogen blijven dekkend. + Vereist de matglazen achtergrond. + Transparantie van de achtergrond + Hoeveel van de achtergrond doorschijnt. + Transparantie van de kaarten + Hoeveel van de achtergrond door de kaarten schijnt. Waarschuwen bij weinig opslagruimte Vragen voordat Steam start als er minder dan 10 GB vrij is. Indeling @@ -2131,6 +2138,7 @@ Links Midden Rechts + Gesplitst Het menu Snelle toegang van Steam is nog niet beschikbaar. In-game statistieken HUD op het onderste scherm @@ -2441,6 +2449,8 @@ %1$s Als dat niet mogelijk is, sluit dit apparaat aan op een computer met ADB en voer de onderstaande opdracht uit. Kom hierna terug en controleer opnieuw. Steam-sessies kunnen starten. Deze Android-versie gebruikt deze limiet niet. + Limiet voor onderliggende processen geregeld door DroidDeck + DroidDeck voert de meeste programma\'s van de sessie uit in processen die Android niet meetelt, zodat de sessie ruim onder de limiet blijft en Ontwikkelaarsopties uit kunnen blijven. Steam en enkele van zijn hulpprocessen tellen nog wel mee. Schakel “Beperkingen voor onderliggende processen uitzetten” in bij Ontwikkelaarsopties en laat Ontwikkelaarsopties daarna aan staan. Deze Android-versie heeft hier geen schakelaar voor. Gebruik draadloze foutopsporing om dit vanaf dit apparaat te wijzigen. Deze build heeft geen download voor dit exemplaar van DroidDeck. @@ -3199,9 +3209,11 @@ %1$s u %1$d min Positie van de afbeelding + Positie van de afbeelding (Liggend) + Positie van de afbeelding (Staand) Boven Onder - Midden (standaard) + Midden Links Rechts Opslag @@ -4150,4 +4162,7 @@ Deze game installeert zijn Linux-versie. Installeer hem via Steam. Gamezoom Pas de spelvergroting aan van 100% tot 300% + Snelkoppeling in game + Smart Glasses-snelkoppeling tonen + Toon de zwevende Smart Glasses-knop boven het spel. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 687742d283..350871461b 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptacyjne %1$d Wymaga Lossless Scaling ze Steam - Zainstaluj Lossless Scaling w Steam lub zaimportuj Lossless.dll - Importuj Lossless.dll… - Używana jest kopia ze Steam - Używana jest zaimportowana kopia - Wybierz Lossless.dll - Zaimportowano Lossless.dll - Ten plik Lossless.dll jest już używany - To konto Steam nie ma Lossless Scaling - Ten plik to nie Lossless.dll z Lossless Scaling - Nie udało się przygotować LSFG z tego pliku Lossless.dll - LSFG wymaga Lossless Scaling ze Steam lub zaimportowanego pliku Lossless.dll Nie udało się przygotować shaderów LSFG z pliku Lossless.dll %1$s: nieobsługiwane %1$s: błąd silnika @@ -650,6 +639,9 @@ Nazwa hosta Nazwa tego urządzenia widoczna dla Steam. Puste pole przywraca %1$s. Tylko litery, cyfry i łączniki w środku, do 63 znaków. + Pulpit działa jako użytkownik + Pulpit, jego aplikacje i terminale działają jako zwykły użytkownik deck zamiast root, dla aplikacji, które odrzucają root. sudo nadal działa. Obowiązuje od następnego pulpitu. + Wymaga Uruchamiaj bez proot. Android jest ustawiony tak, że zamknie tę sesję Zainstalowane Do pobrania @@ -1257,6 +1249,11 @@ Przygotuj Debugowanie bezprzewodowe jest niedostępne; Paruj, aby je włączyć Paruj + Quest nie ma ekranu parowania. Na komputerze uruchom raz: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS oraz adb tcpip 5555. Następnie dotknij Zezwól i zaakceptuj monit w goglach + Zezwól + Zaakceptuj „Zezwolić na debugowanie?” w goglach z zaznaczonym Zawsze zezwalaj + Nie udało się połączyć. Zaakceptuj monit debugowania w goglach, a jeśli się nie pojawił, uruchom adb tcpip 5555 na komputerze i spróbuj ponownie + Debugowanie bezprzewodowe jest nieosiągalne. Dotknij Zezwól, aby skonfigurować je ponownie Zainstaluj Zaloguj się PR #%1$d @@ -1328,6 +1325,16 @@ Joy-Cony jako kontrolery VR Gdy działa SteamVR, każdy Joy-Con staje się dłonią. Skieruj go przed siebie i przytrzymaj Home lub Capture, aby go wyśrodkować. Animacje + Matowe + Pokazuje rozmytą tapetę za aplikacją. Zużywa więcej baterii. + Matowa tapeta + Matowe karty + Karty i grupy przepuszczają trochę tapety. Menu i okna dialogowe pozostają nieprzezroczyste. + Wymaga matowej tapety. + Przezroczystość tapety + Ile tapety prześwituje. + Przezroczystość kart + Ile tapety prześwituje przez karty. Ostrzegaj o małej ilości miejsca Pytaj przed uruchomieniem Steam, gdy wolne miejsce wynosi mniej niż 10 GB. Układ @@ -2181,6 +2188,7 @@ Do lewej Na środku Do prawej + Podzielony Menu szybkiego dostępu Steam nie jest jeszcze dostępne. Statystyki w grze HUD dolnego ekranu @@ -2493,6 +2501,8 @@ %1$s Jeśli to niemożliwe, podłącz to urządzenie do komputera z ADB i uruchom poniższe polecenie. Wróć tutaj i sprawdź ponownie. Sesje Steam mogą się uruchamiać. Ta wersja systemu Android nie używa tego limitu. + Limitem procesów podrzędnych zajmuje się DroidDeck + DroidDeck uruchamia większość programów sesji w procesach, których Android nie liczy, dzięki czemu sesja pozostaje znacznie poniżej limitu, a Opcje programisty mogą pozostać wyłączone. Steam i niektóre jego procesy pomocnicze nadal są liczone. Włącz „Wyłącz ograniczenia procesów podrzędnych aplikacji” w Opcjach programisty i nie wyłączaj potem Opcji programisty. Ta wersja systemu Android nie ma dla niego przełącznika. Użyj debugowania bezprzewodowego, aby zmienić go z tego urządzenia. Ta wersja nie ma pliku do pobrania dla tej kopii DroidDeck. @@ -3259,9 +3269,11 @@ %1$s godz. %1$d min Pozycja obrazu + Pozycja obrazu (Pozioma) + Pozycja obrazu (Pionowa) Góra Dół - Środek (domyślnie) + Środek Lewo Prawo Pamięć @@ -4230,4 +4242,7 @@ Ta gra instaluje swoją wersję dla Linuksa. Zainstaluj ją ze Steama. Powiększenie gry Dostosuj powiększenie gry w zakresie od 100% do 300% + Skrót w grze + Pokaż skrót Smart Glasses + Pokaż pływający przycisk Smart Glasses nad grą. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index c5970fe00b..58c25267da 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptativo %1$d Requer o Lossless Scaling no Steam - Instale o Lossless Scaling no Steam ou importe o Lossless.dll - Importar Lossless.dll… - A utilizar a cópia do Steam - A utilizar uma cópia importada - Escolher Lossless.dll - Lossless.dll importado - Este Lossless.dll já está a ser utilizado - Esta conta Steam não possui o Lossless Scaling - Este ficheiro não é o Lossless.dll do Lossless Scaling - Não foi possível preparar o LSFG a partir deste Lossless.dll - O LSFG requer o Lossless Scaling do Steam ou um Lossless.dll importado O LSFG não conseguiu preparar os shaders a partir do Lossless.dll %1$s: não suportado %1$s: falha do motor @@ -648,6 +637,9 @@ Nome do anfitrião O nome com que o Steam vê este dispositivo. Em branco, repõe %1$s. Apenas letras, algarismos e hífenes interiores, até 63 carateres. + O ambiente de trabalho corre como utilizador + O ambiente de trabalho, as suas apps e terminais correm como o utilizador comum deck em vez de root, para apps que recusam root. O sudo continua a funcionar. Aplica-se ao próximo ambiente de trabalho. + Requer Executar sem proot. O Android está configurado para terminar esta sessão Instalado Disponível para transferir @@ -1244,6 +1236,11 @@ Preparar A depuração sem fios não está acessível; Emparelhar ativa-a Emparelhar + O Quest não tem ecrã de emparelhamento. Num computador, execute uma vez: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS e adb tcpip 5555. Depois toque em Permitir e aceite o pedido no headset + Permitir + Aceite “Permitir depuração?” no headset, com Permitir sempre assinalado + Não foi possível ligar. Aceite o pedido de depuração no headset ou, se não apareceu, execute adb tcpip 5555 num computador e tente novamente + A depuração sem fios não está acessível. Toque em Permitir para a configurar de novo Instalar Iniciar sessão PR #%1$d @@ -1312,6 +1309,16 @@ Joy-Con como comandos de RV Enquanto o SteamVR está a correr, cada Joy-Con torna-se uma mão. Aponte-o para a frente e mantenha Home ou Capture premido para o recentrar. Animações + Fosco + Mostra a imagem de fundo desfocada atrás do iniciador. Gasta mais bateria. + Fundo fosco + Cartões foscos + Os cartões e grupos deixam ver um pouco do fundo. Os menus e caixas de diálogo continuam opacos. + Requer o fundo fosco. + Transparência do fundo + Quanto do fundo se vê através. + Transparência dos cartões + Quanto do fundo se vê através dos cartões. Avisar quando o armazenamento estiver baixo Perguntar antes de iniciar o Steam quando o espaço livre for inferior a 10 GB. Esquema @@ -2162,6 +2169,7 @@ Esquerda Centro Direita + Dividido O menu de acesso rápido do Steam ainda não está disponível. Estatísticas no jogo HUD do ecrã inferior @@ -2473,6 +2481,8 @@ %1$s Se não for possível, ligue este dispositivo a um computador com ADB e execute o comando abaixo. Volte aqui e verifique novamente. As sessões Steam podem ser iniciadas. Esta versão do Android não usa este limite. + Limite de processos filhos gerido pelo DroidDeck + O DroidDeck executa a maioria dos programas da sessão em processos que o Android não conta, o que mantém a sessão bem abaixo do limite, por isso as Opções de programador podem continuar desativadas. O Steam e alguns dos seus processos auxiliares continuam a contar. Ative «Desativar restrições de processos secundários» nas Opções de programador e mantenha as Opções de programador ativadas depois. Esta versão do Android não tem um interruptor para isto. Use a depuração sem fios para o alterar a partir deste dispositivo. Esta versão não tem transferência para esta cópia do DroidDeck. @@ -3243,11 +3253,13 @@ Espaço livre insuficiente: são necessários %1$s, só há %2$s livres Espaço livre desconhecido Posição da imagem + Posição da imagem (Horizontal) + Posição da imagem (Vertical) Topo Esquerda Direita Fundo - Centro (predefinido) + Centro Armazenamento A medir o armazenamento… Na primeira vez demora alguns segundos. @@ -4189,4 +4201,7 @@ Este jogo instala a sua versão para Linux. Instale-o a partir do Steam. Zoom do jogo Ajuste a ampliação do jogo de 100% a 300% + Atalho no jogo + Mostrar atalho do Smart Glasses + Mostrar o botão flutuante do Smart Glasses sobre o jogo. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index df77690a5a..08eb2c38de 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptativo %1$d Requer o Lossless Scaling na Steam - Instale o Lossless Scaling na Steam ou importe o Lossless.dll - Importar Lossless.dll… - Usando a cópia da Steam - Usando uma cópia importada - Escolha o Lossless.dll - Lossless.dll importado - Este Lossless.dll já está em uso - Esta conta Steam não tem o Lossless Scaling - Este arquivo não é o Lossless.dll do Lossless Scaling - Não foi possível preparar o LSFG com este Lossless.dll - O LSFG requer o Lossless Scaling da Steam ou um Lossless.dll importado O LSFG não conseguiu preparar os shaders a partir do Lossless.dll %1$s: sem suporte %1$s: falha no mecanismo @@ -648,6 +637,9 @@ Nome do host O nome que a Steam vê para este dispositivo. Em branco, volta a ser %1$s. Só letras, dígitos e hifens internos, até 63 caracteres. + A área de trabalho roda como usuário + A área de trabalho, seus apps e terminais rodam como o usuário comum deck em vez de root, para apps que recusam root. O sudo continua funcionando. Vale a partir da próxima área de trabalho. + Requer Executar sem proot. O Android está configurado para encerrar esta sessão Instalados Disponíveis para download @@ -1252,6 +1244,11 @@ Preparar A depuração sem fio não está acessível; Parear a ativa Parear + O Quest não tem tela de pareamento. Em um computador, execute uma vez: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS e adb tcpip 5555. Depois toque em Permitir e aceite o aviso no headset + Permitir + Aceite “Permitir depuração?” no headset, com Sempre permitir marcado + Não foi possível conectar. Aceite o aviso de depuração no headset ou, se ele não apareceu, execute adb tcpip 5555 em um computador e tente novamente + A depuração sem fio não está acessível. Toque em Permitir para configurá-la de novo Instalar Entrar PR #%1$d @@ -1320,6 +1317,16 @@ Joy-Cons como controles de RV Enquanto o SteamVR está rodando, cada Joy-Con vira uma mão. Aponte-o para a frente e segure Home ou Capture para recentralizá-lo. Animações + Fosco + Mostra seu papel de parede desfocado atrás do inicializador. Usa mais bateria. + Papel de parede fosco + Cartões foscos + Cartões e grupos deixam ver um pouco do papel de parede. Menus e caixas de diálogo continuam opacos. + Requer o papel de parede fosco. + Transparência do papel de parede + Quanto do papel de parede aparece. + Transparência dos cartões + Quanto do papel de parede aparece através dos cartões. Avisar quando o armazenamento estiver baixo Perguntar antes de iniciar o Steam quando o espaço livre for inferior a 10 GB. Layout @@ -2170,6 +2177,7 @@ Esquerda Centro Direita + Dividido O menu de acesso rápido do Steam ainda não está disponível. Estatísticas no jogo HUD da tela inferior @@ -2481,6 +2489,8 @@ %1$s Se não for possível, conecte este dispositivo a um computador com ADB e execute o comando abaixo. Depois volte aqui e verifique de novo. As sessões do Steam podem ser iniciadas. Esta versão do Android não usa esse limite. + Limite de processos filhos gerenciado pelo DroidDeck + O DroidDeck executa a maioria dos programas da sessão em processos que o Android não conta, o que mantém a sessão bem abaixo do limite, então as Opções do desenvolvedor podem continuar desativadas. O Steam e alguns dos seus processos auxiliares ainda contam. Ative “Desativar restrições de processos filhos” nas Opções do desenvolvedor e mantenha as Opções do desenvolvedor ativadas depois. Esta versão do Android não tem uma chave para isso. Use a depuração por Wi-Fi para alterar pelo próprio dispositivo. Esta versão não tem download para esta cópia do DroidDeck. @@ -3253,11 +3263,13 @@ Espaço insuficiente (%1$s livres, são necessários %2$s) Espaço livre desconhecido Posição da imagem + Posição da imagem (Paisagem) + Posição da imagem (Retrato) Topo Esquerda Direita Base - Centro (padrão) + Centro Armazenamento Medindo o armazenamento… Na primeira vez leva alguns segundos. @@ -4197,4 +4209,7 @@ Feche o Steam primeiro Pause o download do Steam primeiro Este jogo instala sua versão para Linux. Instale-o pelo Steam. + Atalho durante o jogo + Mostrar atalho do Smart Glasses + Mostrar o botão flutuante do Smart Glasses sobre o jogo. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 8d6da38074..bd89893d52 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptiv %1$d Necesită Lossless Scaling pe Steam - Instalează Lossless Scaling în Steam sau importă Lossless.dll - Importă Lossless.dll… - Se folosește copia din Steam - Se folosește o copie importată - Alege Lossless.dll - Lossless.dll importat - Acest Lossless.dll este deja în uz - Lossless Scaling nu este deținut pe acest cont Steam - Acest fișier nu este Lossless.dll al Lossless Scaling - Nu s-a putut pregăti LSFG din acest Lossless.dll - LSFG are nevoie de Lossless Scaling din Steam sau de un Lossless.dll importat LSFG nu a putut pregăti shaderele din Lossless.dll %1$s: neacceptat %1$s: motor eșuat @@ -648,6 +637,9 @@ Nume de host Numele pe care Steam îl vede pentru acest dispozitiv. Gol restaurează %1$s. Doar litere, cifre și liniuțe interioare, până la 63 de caractere. + Desktopul rulează ca utilizator + Desktopul, aplicațiile și terminalele sale rulează ca utilizatorul obișnuit deck în loc de root, pentru aplicațiile care refuză root. sudo funcționează în continuare. Se aplică la următorul desktop. + Necesită Rulează fără proot. Android este setat să închidă această sesiune Instalat Disponibil pentru descărcare @@ -1253,6 +1245,11 @@ Pregătește Depanarea fără fir nu este accesibilă; „Asociază” o activează Asociază + Quest nu are ecran de asociere. De pe un computer, rulează o dată: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS și adb tcpip 5555. Apoi atinge Permite și acceptă solicitarea în cască + Permite + Acceptă „Permiți remedierea erorilor?” în cască, cu Permite întotdeauna bifat + Conectarea a eșuat. Acceptă solicitarea de remediere a erorilor în cască sau, dacă nu a apărut, rulează adb tcpip 5555 de pe un computer și încearcă din nou + Remedierea wireless a erorilor nu este accesibilă. Atinge Permite pentru a o configura din nou Instalează Conectați-vă PR #%1$d @@ -1321,6 +1318,16 @@ Joy-Con ca controllere VR Cât timp rulează SteamVR, fiecare Joy-Con devine o mână. Îndreaptă-l înainte și ține apăsat Home sau Capture pentru a-l recentra. Animații + Mat + Afișează imaginea de fundal estompată în spatele launcherului. Consumă mai multă baterie. + Imagine de fundal mată + Carduri mate + Cardurile și grupurile lasă să se vadă puțin din imaginea de fundal. Meniurile și dialogurile rămân opace. + Necesită imaginea de fundal mată. + Transparența imaginii de fundal + Cât din imaginea de fundal se vede. + Transparența cardurilor + Cât din imaginea de fundal se vede prin carduri. Avertizează când spațiul de stocare este redus Întreabă înainte de pornirea Steam când spațiul liber este sub 10 GB. Aranjament @@ -2156,6 +2163,7 @@ Stânga Centru Dreapta + Împărțit Meniul de acces rapid Steam nu este încă disponibil. Statistici în joc HUD pe ecranul de jos @@ -2467,6 +2475,8 @@ %1$s Dacă nu este posibil, conectează acest dispozitiv la un computer cu ADB și rulează comanda de mai jos. Revino aici și verifică din nou. Sesiunile Steam pot porni. Această versiune de Android nu folosește această limită. + Limita proceselor copil este gestionată de DroidDeck + DroidDeck rulează majoritatea programelor sesiunii în procese pe care Android nu le numără, astfel încât sesiunea rămâne mult sub limită, iar Opțiunile pentru dezvoltatori pot rămâne dezactivate. Steam și unele dintre procesele sale auxiliare sunt încă numărate. Activează „Dezactivează restricțiile pentru procese secundare” în Opțiunile pentru dezvoltatori, și lasă Opțiunile pentru dezvoltatori activate după aceea. Această versiune de Android nu are un comutator pentru asta. Folosește Depanarea wireless pentru a o schimba de pe acest dispozitiv. Această versiune nu are o descărcare pentru această copie de DroidDeck. @@ -3229,9 +3239,11 @@ %1$s h %1$d min Poziția imaginii + Poziția imaginii (Peisaj) + Poziția imaginii (Portret) Sus Jos - Centru (implicit) + Centru Stânga Dreapta Stocare @@ -4190,4 +4202,7 @@ Acest joc își instalează versiunea pentru Linux. Instalează-l din Steam. Zoom joc Reglați mărirea jocului între 100% și 300% + Comandă rapidă în joc + Afișează comanda rapidă Smart Glasses + Afișează butonul plutitor Smart Glasses peste joc. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index a37ec1a0aa..c75b0aa343 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Адаптивный %1$d Требуется Lossless Scaling из Steam - Установите Lossless Scaling в Steam или импортируйте Lossless.dll - Импорт Lossless.dll… - Используется копия из Steam - Используется импортированная копия - Выберите файл Lossless.dll - Lossless.dll импортирован - Этот Lossless.dll уже используется - В этой учетной записи Steam нет Lossless Scaling - Этот файл не является Lossless.dll от Lossless Scaling - Не удалось подготовить LSFG из этого Lossless.dll - Для LSFG требуется Lossless Scaling из Steam или импортированный файл Lossless.dll LSFG не удалось подготовить шейдеры из Lossless.dll %1$s: не поддерживается %1$s: сбой движка @@ -650,6 +639,9 @@ Имя хоста Имя, под которым Steam видит это устройство. Оставьте пустым, чтобы вернуть %1$s. Только буквы, цифры и дефисы посередине, до 63 символов. + Рабочий стол от имени пользователя + Рабочий стол, его приложения и терминалы работают от имени обычного пользователя deck вместо root — для приложений, которые отказываются работать от root. sudo по-прежнему работает. Применяется к следующему запуску рабочего стола. + Требуется «Запуск без proot». Android настроен на завершение этой сессии Установлен Доступен для скачивания @@ -1257,6 +1249,11 @@ Подготовить Беспроводная отладка недоступна; «Сопряжение» включит её Сопряжение + В Quest нет экрана сопряжения. Один раз выполните на компьютере: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS и adb tcpip 5555. Затем нажмите «Разрешить» и подтвердите запрос в шлеме + Разрешить + Подтвердите «Разрешить отладку?» в шлеме, отметив «Всегда разрешать» + Не удалось подключиться. Подтвердите запрос на отладку в шлеме, а если он не появился, выполните adb tcpip 5555 на компьютере и повторите попытку + Беспроводная отладка недоступна. Нажмите «Разрешить», чтобы настроить её заново Установить Войти PR #%1$d @@ -1328,6 +1325,16 @@ Joy-Con как VR-контроллеры Пока работает SteamVR, каждый Joy-Con становится рукой. Направьте его вперёд и удерживайте Home или Capture, чтобы снова его отцентрировать. Анимации + Матовое стекло + Показывает размытые обои за лаунчером. Расходует больше заряда. + Матовые обои + Матовые карточки + Сквозь карточки и группы немного просвечивают обои. Меню и диалоги остаются непрозрачными. + Нужны матовые обои. + Прозрачность обоев + Насколько просвечивают обои. + Прозрачность карточек + Насколько обои просвечивают сквозь карточки. Предупреждать о нехватке места Спрашивать перед запуском Steam, если свободно меньше 10 ГБ. Раскладка @@ -2182,6 +2189,7 @@ Слева По центру Справа + Разделённый Меню быстрого доступа Steam пока недоступно. Игровая статистика HUD нижнего экрана @@ -2494,6 +2502,8 @@ %1$s Если это невозможно, подключите устройство к компьютеру с ADB и выполните команду ниже. Затем вернитесь сюда и проверьте снова. Сессии Steam могут запускаться. Эта версия Android не использует это ограничение. + Ограничение дочерних процессов обходит DroidDeck + DroidDeck запускает большинство программ сеанса в процессах, которые Android не учитывает, поэтому сеанс остаётся намного ниже лимита и параметры разработчика можно не включать. Steam и некоторые его вспомогательные процессы по-прежнему учитываются. Включите «Отключить ограничения для дочерних процессов» в разделе «Для разработчиков» и оставьте этот раздел включенным. В этой версии Android нет такого переключателя. Измените настройку с этого устройства через отладку по Wi-Fi. В этой сборке нет загрузки для этой копии DroidDeck. @@ -3260,9 +3270,11 @@ Недостаточно места (свободно %1$s, нужно %2$s) Свободное место неизвестно Положение изображения + Положение изображения (Альбомная) + Положение изображения (Портретная) Сверху Снизу - По центру (по умолчанию) + По центру Слева Справа Хранилище @@ -4231,4 +4243,7 @@ Эта игра устанавливает свою версию для Linux. Установите её из Steam. Масштаб игры Настройте увеличение игры от 100% до 300% + Ярлык в игре + Показывать ярлык Smart Glasses + Показывать плавающую кнопку Smart Glasses поверх игры. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 506e6226ab..f3819c7385 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptiv %1$d Kräver Lossless Scaling på Steam - Installera Lossless Scaling i Steam eller importera Lossless.dll - Importera Lossless.dll… - Använder kopian från Steam - Använder en importerad kopia - Välj Lossless.dll - Lossless.dll har importerats - Den här Lossless.dll används redan - Lossless Scaling ägs inte på det här Steam-kontot - Filen är inte Lossless.dll från Lossless Scaling - Kunde inte förbereda LSFG från den här Lossless.dll - LSFG kräver Lossless Scaling från Steam eller en importerad Lossless.dll LSFG kunde inte förbereda sina shaders från Lossless.dll %1$s: stöds inte %1$s: motorn misslyckades @@ -646,6 +635,9 @@ Värdnamn Namnet Steam ser för den här enheten. Lämna tomt för att återställa till %1$s. Endast bokstäver, siffror och bindestreck inuti, upp till 63 tecken. + Skrivbordet körs som användare + Skrivbordet, dess appar och terminaler körs som den vanliga användaren deck i stället för root, för appar som vägrar root. sudo fungerar fortfarande. Gäller från nästa skrivbord. + Kräver Kör utan proot. Android är inställt på att avsluta den här sessionen Installerad Tillgänglig att ladda ned @@ -1249,6 +1241,11 @@ Förbered Trådlös felsökning kan inte nås; Para slår på den Para + Quest har ingen parkopplingsskärm. Kör en gång från en dator: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS och adb tcpip 5555. Tryck sedan på Tillåt och godkänn frågan i headsetet + Tillåt + Godkänn ”Tillåt felsökning?” i headsetet med Tillåt alltid markerat + Det gick inte att ansluta. Godkänn felsökningsfrågan i headsetet, eller kör adb tcpip 5555 från en dator och försök igen om ingen visades + Trådlös felsökning går inte att nå. Tryck på Tillåt för att konfigurera den igen Installera Logga in PR #%1$d @@ -1314,6 +1311,16 @@ Joy-Con som VR-handkontroller Medan SteamVR körs blir varje Joy-Con en hand. Rikta den framåt och håll in Home eller Capture för att centrera den igen. Animationer + Frostat + Visar din bakgrundsbild suddig bakom startprogrammet. Drar mer batteri. + Frostad bakgrundsbild + Frostade kort + Kort och grupper släpper igenom lite av bakgrundsbilden. Menyer och dialogrutor förblir täckande. + Kräver frostad bakgrundsbild. + Bakgrundsbildens genomskinlighet + Hur mycket av bakgrundsbilden som syns igenom. + Kortens genomskinlighet + Hur mycket av bakgrundsbilden som syns genom korten. Varna när lagringsutrymmet är lågt Fråga innan Steam startas när det lediga utrymmet är under 10 GB. Layout @@ -2131,6 +2138,7 @@ Vänster Mitten Höger + Delad Steams snabbåtkomstmeny är inte tillgänglig än. Statistik i spelet HUD på nedre skärmen @@ -2441,6 +2449,8 @@ %1$s Om det inte är möjligt ansluter du den här enheten till en dator med ADB och kör kommandot nedan. Kom tillbaka hit och kontrollera igen. Steam-sessioner kan starta. Den här Android-versionen använder inte den här gränsen. + DroidDeck hanterar gränsen för underprocesser + DroidDeck kör de flesta av sessionens program i processer som Android inte räknar, så sessionen håller sig långt under gränsen och Utvecklaralternativ kan vara avstängda. Steam och några av dess hjälpprocesser räknas fortfarande. Slå på ”Inaktivera begränsningar på underordnade processer” i Utvecklaralternativ, och låt Utvecklaralternativ vara kvar på efteråt. Den här Android-versionen har ingen växel för det. Använd trådlös felsökning för att ändra det från den här enheten. Den här versionen har ingen nedladdning för den här kopian av DroidDeck. @@ -3199,9 +3209,11 @@ %1$s h %1$d min Bildens position + Bildens position (Liggande) + Bildens position (Stående) Överst Nederst - Mitten (standard) + Mitten Vänster Höger Lagring @@ -4150,4 +4162,7 @@ Det här spelet installerar sin Linux-version. Installera det från Steam. Spelzoom Justera spelförstoringen från 100 % till 300 % + Genväg i spelet + Visa Smart Glasses-genväg + Visa den flytande Smart Glasses-knappen ovanpå spelet. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index adca121cf7..21c96ecd2a 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG แบบปรับอัตโนมัติ %1$d ต้องมี Lossless Scaling บน Steam - ติดตั้ง Lossless Scaling ใน Steam หรือนำเข้า Lossless.dll - นำเข้า Lossless.dll… - ใช้ชุดที่มาจาก Steam - ใช้ชุดที่นำเข้ามา - เลือก Lossless.dll - นำเข้า Lossless.dll แล้ว - Lossless.dll นี้ถูกใช้งานอยู่แล้ว - บัญชี Steam นี้ไม่ได้เป็นเจ้าของ Lossless Scaling - ไฟล์นี้ไม่ใช่ Lossless.dll ของ Lossless Scaling - ไม่สามารถเตรียม LSFG จาก Lossless.dll นี้ได้ - LSFG ต้องใช้ Lossless Scaling จาก Steam หรือ Lossless.dll ที่นำเข้ามา LSFG ไม่สามารถเตรียมเชดเดอร์จาก Lossless.dll ได้ %1$s: ไม่รองรับ %1$s: เอนจินล้มเหลว @@ -644,6 +633,9 @@ ชื่อโฮสต์ ชื่อที่ Steam มองเห็นสำหรับอุปกรณ์นี้ เว้นว่างไว้เพื่อคืนค่าเป็น %1$s ใช้ได้เฉพาะตัวอักษร ตัวเลข และยัติภังค์ตรงกลาง ไม่เกิน 63 ตัวอักษร + เดสก์ท็อปทำงานในฐานะผู้ใช้ + เดสก์ท็อป แอป และเทอร์มินัลจะทำงานในฐานะผู้ใช้ทั่วไป deck แทน root สำหรับแอปที่ไม่ยอมทำงานด้วย root sudo ยังใช้งานได้ มีผลกับเดสก์ท็อปครั้งถัดไป + ต้องเปิด เรียกใช้โดยไม่มี proot Android ถูกตั้งให้ปิดเซสชันนี้ ติดตั้งแล้ว พร้อมดาวน์โหลด @@ -1246,6 +1238,11 @@ เตรียม เชื่อมต่อการดีบักแบบไร้สายไม่ได้; จับคู่จะเปิดใช้งาน จับคู่ + Quest ไม่มีหน้าจอจับคู่ จากคอมพิวเตอร์ ให้รันหนึ่งครั้ง: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS และ adb tcpip 5555 จากนั้นแตะอนุญาตและยอมรับข้อความในเฮดเซ็ต + อนุญาต + ยอมรับ “อนุญาตการแก้ไขข้อบกพร่องไหม” ในเฮดเซ็ต โดยเลือกอนุญาตเสมอ + เชื่อมต่อไม่ได้ ยอมรับข้อความแก้ไขข้อบกพร่องในเฮดเซ็ต หรือหากไม่มีข้อความขึ้น ให้รัน adb tcpip 5555 จากคอมพิวเตอร์แล้วลองอีกครั้ง + เข้าถึงการแก้ไขข้อบกพร่องแบบไร้สายไม่ได้ แตะอนุญาตเพื่อตั้งค่าใหม่ ติดตั้ง ลงชื่อเข้าใช้ PR #%1$d @@ -1308,6 +1305,16 @@ ใช้ Joy-Con เป็นคอนโทรลเลอร์ VR ขณะที่ SteamVR ทำงาน Joy-Con แต่ละตัวจะกลายเป็นมือ ชี้ไปข้างหน้าแล้วกด Home หรือ Capture ค้างไว้เพื่อจัดให้อยู่ตรงกลางอีกครั้ง ภาพเคลื่อนไหว + แบบฝ้า + แสดงวอลเปเปอร์แบบเบลอไว้ด้านหลังตัวเปิดแอป ใช้แบตเตอรี่มากขึ้น + วอลเปเปอร์แบบฝ้า + การ์ดแบบฝ้า + การ์ดและกลุ่มจะเห็นวอลเปเปอร์เล็กน้อย เมนูและกล่องโต้ตอบยังคงทึบ + ต้องเปิดวอลเปเปอร์แบบฝ้า + ความโปร่งใสของวอลเปเปอร์ + ปริมาณวอลเปเปอร์ที่มองทะลุได้ + ความโปร่งใสของการ์ด + ปริมาณวอลเปเปอร์ที่มองทะลุการ์ดได้ เตือนเมื่อพื้นที่เก็บข้อมูลเหลือน้อย ถามก่อนเริ่ม Steam เมื่อพื้นที่ว่างน้อยกว่า 10 GB การจัดวาง @@ -2107,6 +2114,7 @@ ซ้าย กึ่งกลาง ขวา + แบ่งหน้าจอ เมนูเข้าถึงด่วนของ Steam ยังไม่พร้อมใช้งาน สถิติในเกม HUD หน้าจอล่าง @@ -2416,6 +2424,8 @@ %1$s หากทำไม่ได้ ให้เชื่อมต่ออุปกรณ์นี้กับคอมพิวเตอร์ที่มี ADB แล้วรันคำสั่งด้านล่าง กลับมาที่นี่แล้วตรวจสอบอีกครั้ง เซสชัน Steam สามารถเริ่มได้ Android รุ่นนี้ไม่ใช้ขีดจำกัดนี้ + DroidDeck จัดการขีดจำกัดโปรเซสลูกให้ + DroidDeck เรียกใช้โปรแกรมส่วนใหญ่ของเซสชันในโปรเซสที่ Android ไม่นับ เซสชันจึงต่ำกว่าขีดจำกัดมาก และปิดตัวเลือกสำหรับนักพัฒนาซอฟต์แวร์ไว้ได้ Steam และโปรเซสตัวช่วยบางตัวของ Steam ยังคงถูกนับ เปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย” ในตัวเลือกสำหรับนักพัฒนา และเปิดตัวเลือกสำหรับนักพัฒนาไว้ต่อไปหลังจากนั้น Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ใช้ Wireless debugging เพื่อเปลี่ยนค่าจากอุปกรณ์นี้ บิลด์นี้ไม่มีให้ดาวน์โหลดสำหรับสำเนานี้ของ DroidDeck @@ -3170,9 +3180,11 @@ %1$s ชม. %1$d นาที ตำแหน่งภาพ + ตำแหน่งภาพ (แนวนอน) + ตำแหน่งภาพ (แนวตั้ง) บน ล่าง - กลาง (ค่าเริ่มต้น) + กลาง ซ้าย ขวา พื้นที่จัดเก็บ @@ -4120,4 +4132,7 @@ เกมนี้ติดตั้งเวอร์ชัน Linux ของตัวเอง ให้ติดตั้งจาก Steam ซูมเกม ปรับการขยายเกมตั้งแต่ 100% ถึง 300% + ทางลัดในเกม + แสดงทางลัด Smart Glasses + แสดงปุ่ม Smart Glasses แบบลอยทับบนเกม diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 3960ffac55..acc9089167 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Uyarlanabilir %1$d Steam\'de Lossless Scaling gerekli - Lossless Scaling\'i Steam\'den yükleyin veya Lossless.dll dosyasını içe aktarın - Lossless.dll içe aktar… - Steam\'deki kopya kullanılıyor - İçe aktarılan kopya kullanılıyor - Lossless.dll seçin - Lossless.dll içe aktarıldı - Bu Lossless.dll zaten kullanılıyor - Bu Steam hesabı Lossless Scaling\'e sahip değil - Bu dosya Lossless Scaling\'in Lossless.dll dosyası değil - Bu Lossless.dll ile LSFG hazırlanamadı - LSFG için Steam\'den Lossless Scaling veya içe aktarılmış bir Lossless.dll gerekir LSFG, gölgelendiricilerini Lossless.dll dosyasından hazırlayamadı %1$s: desteklenmiyor %1$s: motor hatası @@ -646,6 +635,9 @@ Ana bilgisayar adı Steam\'in bu cihaz için gördüğü ad. Boş bırakılırsa %1$s geri yüklenir. Yalnızca harf, rakam ve arada kısa çizgi; en fazla 63 karakter. + Masaüstü kullanıcı olarak çalışır + Masaüstü, uygulamaları ve terminalleri root yerine sıradan kullanıcı deck olarak çalışır; root’u reddeden uygulamalar içindir. sudo çalışmaya devam eder. Bir sonraki masaüstünde geçerli olur. + proot olmadan çalıştır gerekir. Android bu oturumu sonlandıracak şekilde ayarlı Yüklü İndirilebilir @@ -1241,6 +1233,11 @@ Hazırla Kablosuz hata ayıklamaya ulaşılamıyor; Eşleştir ile açılır Eşleştir + Quest\'te eşleme ekranı yok. Bir bilgisayardan bir kez çalıştırın: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS ve adb tcpip 5555. Ardından İzin ver\'e dokunun ve kulaklıktaki istemi kabul edin + İzin ver + Kulaklıkta “Hata ayıklamaya izin verilsin mi?” istemini Her zaman izin ver işaretliyken kabul edin + Bağlanılamadı. Kulaklıktaki hata ayıklama istemini kabul edin veya istem görünmediyse bir bilgisayardan adb tcpip 5555 çalıştırıp tekrar deneyin + Kablosuz hata ayıklamaya ulaşılamıyor. Yeniden ayarlamak için İzin ver\'e dokunun Yükle Giriş yap PR #%1$d @@ -1306,6 +1303,16 @@ VR kumandası olarak Joy-Con\'lar SteamVR çalışırken her Joy-Con bir el olur. Öne doğrultun ve yeniden ortalamak için Home veya Capture düğmesini basılı tutun. Animasyonlar + Buzlu + Duvar kâğıdınızı başlatıcının arkasında bulanık gösterir. Daha fazla pil kullanır. + Buzlu duvar kâğıdı + Buzlu kartlar + Kartlar ve gruplar duvar kâğıdının bir kısmını gösterir. Menüler ve iletişim kutuları opak kalır. + Buzlu duvar kâğıdı gerekir. + Duvar kâğıdı saydamlığı + Duvar kâğıdının ne kadar göründüğü. + Kart saydamlığı + Duvar kâğıdının kartların ardından ne kadar göründüğü. Depolama azaldığında uyar Boş alan 10 GB\'ın altındayken Steam\'i başlatmadan önce sor. Düzen @@ -2123,6 +2130,7 @@ Sol Orta Sağ + Bölünmüş Steam Hızlı Erişim menüsü henüz kullanılamıyor. Oyun içi istatistikler Alt ekrandaki HUD @@ -2433,6 +2441,8 @@ %1$s Bu mümkün değilse bu cihazı ADB\'li bir bilgisayara bağlayıp aşağıdaki komutu çalıştırın. Buraya dönüp yeniden kontrol edin. Steam oturumları başlayabilir. Bu Android sürümü bu sınırı kullanmaz. + Alt işlem sınırını DroidDeck yönetiyor + DroidDeck oturumun programlarının çoğunu Android\'in saymadığı işlemlerde çalıştırır; böylece oturum sınırın çok altında kalır ve Geliştirici seçenekleri kapalı kalabilir. Steam ve bazı yardımcı işlemleri hâlâ sayılır. Geliştirici seçenekleri\'nde “Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini açın ve sonrasında Geliştirici seçeneklerini açık tutun. Bu Android sürümünde bunun için bir anahtar yok. Bu cihazdan değiştirmek için Kablosuz hata ayıklamayı kullanın. Bu derlemede bu DroidDeck kopyası için bir indirme yok. @@ -3199,9 +3209,11 @@ Yetersiz alan (%1$s boş, %2$s gerekli) Boş alan bilinmiyor Görüntü konumu + Görüntü konumu (Yatay) + Görüntü konumu (Dikey) Üst Alt - Orta (varsayılan) + Orta Sol Sağ Depolama @@ -4150,4 +4162,7 @@ Bu oyun Linux sürümünü yükler. Steam\'den yükleyin. Oyun yakınlaştırma Oyun yakınlaştırmasını %100 ile %300 arasında ayarlayın + Oyun içi kısayol + Smart Glasses kısayolunu göster + Oyun üzerinde yüzen Smart Glasses düğmesini göster. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 727d6660f4..6ca06df91c 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG адаптивний %1$d Потрібен Lossless Scaling зі Steam - Установіть Lossless Scaling у Steam або імпортуйте Lossless.dll - Імпортувати Lossless.dll… - Використовується копія зі Steam - Використовується імпортована копія - Виберіть Lossless.dll - Lossless.dll імпортовано - Цей Lossless.dll уже використовується - У цьому обліковому записі Steam немає Lossless Scaling - Цей файл не є Lossless.dll від Lossless Scaling - Не вдалося підготувати LSFG із цього Lossless.dll - Для LSFG потрібен Lossless Scaling зі Steam або імпортований Lossless.dll LSFG не вдалося підготувати шейдери з Lossless.dll %1$s: не підтримується %1$s: збій рушія @@ -650,6 +639,9 @@ Ім’я хоста Ім’я, яке Steam бачить для цього пристрою. Порожнє значення відновлює %1$s. Лише літери, цифри та дефіси всередині, до 63 символів. + Робочий стіл від імені користувача + Робочий стіл, його застосунки й термінали працюють від імені звичайного користувача deck замість root — для застосунків, які відмовляються працювати від root. sudo і далі працює. Застосовується до наступного запуску робочого столу. + Потрібен «Запуск без proot». Android налаштовано завершувати цей сеанс Встановлено Доступно для завантаження @@ -1257,6 +1249,11 @@ Підготувати Бездротове налагодження недоступне; «Сполучити» увімкне його Сполучити + У Quest немає екрана підключення. Один раз виконайте на комп’ютері: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS і adb tcpip 5555. Потім торкніться «Дозволити» й підтвердьте запит у шоломі + Дозволити + Підтвердьте «Дозволити налагодження?» у шоломі, позначивши «Завжди дозволяти» + Не вдалося підключитися. Підтвердьте запит на налагодження в шоломі, а якщо його не було, виконайте adb tcpip 5555 на комп’ютері й спробуйте ще раз + Бездротове налагодження недоступне. Торкніться «Дозволити», щоб налаштувати його знову Установити Увійти PR #%1$d @@ -1328,6 +1325,16 @@ Joy-Con як VR-контролери Поки працює SteamVR, кожен Joy-Con стає рукою. Спрямуйте його вперед і утримуйте Home або Capture, щоб знову його відцентрувати. Анімації + Матове скло + Показує розмиті шпалери за лаунчером. Витрачає більше заряду. + Матові шпалери + Матові картки + Крізь картки та групи трохи просвічують шпалери. Меню й діалоги лишаються непрозорими. + Потрібні матові шпалери. + Прозорість шпалер + Наскільки просвічують шпалери. + Прозорість карток + Наскільки шпалери просвічують крізь картки. Попереджати про брак місця Питати перед запуском Steam, якщо вільно менше 10 ГБ. Розкладка @@ -2181,6 +2188,7 @@ Ліворуч По центру Праворуч + Розділений Меню швидкого доступу Steam ще недоступне. Ігрова статистика HUD на нижньому екрані @@ -2493,6 +2501,8 @@ %1$s Якщо це неможливо, підключіть цей пристрій до комп’ютера з ADB і виконайте команду нижче. Потім поверніться сюди і перевірте ще раз. Сеанси Steam можуть запускатися. Ця версія Android не використовує це обмеження. + Обмеження дочірніх процесів обходить DroidDeck + DroidDeck запускає більшість програм сеансу в процесах, які Android не враховує, тож сеанс залишається значно нижче ліміту і параметри розробника можна не вмикати. Steam і деякі його допоміжні процеси все ще враховуються. Увімкніть «Вимкнути обмеження для дочірніх процесів» у розділі «Параметри розробника» і залишіть «Параметри розробника» увімкненими після цього. У цій версії Android немає перемикача для цього. Змініть це з цього пристрою за допомогою бездротового налагодження. У цій збірці немає завантаження для цієї копії DroidDeck. @@ -3259,9 +3269,11 @@ %1$s год %1$d хв Позиція зображення + Позиція зображення (Альбомна) + Позиція зображення (Книжкова) Угорі Унизу - По центру (типово) + По центру Ліворуч Праворуч Сховище @@ -4230,4 +4242,7 @@ Ця гра встановлює свою версію для Linux. Установіть її зі Steam. Масштаб гри Налаштуйте збільшення гри від 100% до 300% + Ярлик у грі + Показувати ярлик Smart Glasses + Показувати плаваючу кнопку Smart Glasses поверх гри. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 6803dd16a0..420c0c1bf5 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG thích ứng %1$d Cần Lossless Scaling trên Steam - Cài Lossless Scaling trong Steam hoặc nhập Lossless.dll - Nhập Lossless.dll… - Đang dùng bản sao từ Steam - Đang dùng bản đã nhập - Chọn Lossless.dll - Đã nhập Lossless.dll - Lossless.dll này đã đang được dùng - Tài khoản Steam này không sở hữu Lossless Scaling - Tệp này không phải là Lossless.dll của Lossless Scaling - Không thể chuẩn bị LSFG từ Lossless.dll này - LSFG cần Lossless Scaling từ Steam hoặc một Lossless.dll đã nhập LSFG không thể chuẩn bị shader từ Lossless.dll %1$s: không hỗ trợ %1$s: engine lỗi @@ -644,6 +633,9 @@ Tên máy chủ Tên mà Steam thấy cho thiết bị này. Để trống để khôi phục %1$s. Chỉ chữ, số và gạch ngang ở giữa, tối đa 63 ký tự. + Màn hình nền chạy dưới dạng người dùng + Màn hình nền, các ứng dụng và terminal của nó chạy dưới người dùng thường deck thay vì root, cho các ứng dụng từ chối root. sudo vẫn hoạt động. Áp dụng cho lần mở màn hình nền tiếp theo. + Cần bật Chạy không cần proot. Android được đặt để tắt phiên này Đã cài Có thể tải @@ -1246,6 +1238,11 @@ Chuẩn bị Không truy cập được gỡ lỗi không dây; Ghép đôi sẽ bật tính năng này Ghép đôi + Quest không có màn hình ghép nối. Từ máy tính, chạy một lần: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS và adb tcpip 5555. Sau đó nhấn Cho phép và chấp nhận lời nhắc trong kính + Cho phép + Chấp nhận “Cho phép gỡ lỗi?” trong kính, với Luôn cho phép được chọn + Không thể kết nối. Chấp nhận lời nhắc gỡ lỗi trong kính, hoặc nếu không thấy lời nhắc, hãy chạy adb tcpip 5555 từ máy tính rồi thử lại + Không thể kết nối gỡ lỗi không dây. Nhấn Cho phép để thiết lập lại Cài đặt Đăng nhập PR #%1$d @@ -1308,6 +1305,16 @@ Dùng Joy-Con làm tay cầm VR Khi SteamVR đang chạy, mỗi Joy-Con trở thành một bàn tay. Hướng nó về phía trước rồi giữ Home hoặc Capture để căn giữa lại. Hiệu ứng chuyển động + Mờ + Hiển thị hình nền được làm mờ phía sau launcher. Tốn pin hơn. + Hình nền mờ + Thẻ mờ + Thẻ và nhóm để lộ một chút hình nền. Menu và hộp thoại vẫn đặc. + Cần bật Hình nền mờ. + Độ trong suốt của hình nền + Mức hình nền hiện qua. + Độ trong suốt của thẻ + Mức hình nền hiện qua các thẻ. Cảnh báo khi dung lượng lưu trữ thấp Hỏi trước khi khởi động Steam khi dung lượng trống dưới 10 GB. Bố cục @@ -2107,6 +2114,7 @@ Trái Giữa Phải + Chia màn hình Menu Truy cập nhanh của Steam chưa sẵn sàng. Thông số trong game HUD màn hình dưới @@ -2416,6 +2424,8 @@ %1$s Nếu không thể, hãy kết nối thiết bị này với một máy tính có ADB và chạy lệnh dưới đây. Quay lại đây và kiểm tra lại. Phiên Steam có thể khởi động. Phiên bản Android này không dùng giới hạn này. + DroidDeck xử lý giới hạn tiến trình con + DroidDeck chạy hầu hết các chương trình của phiên trong những tiến trình mà Android không tính, nên phiên luôn ở dưới giới hạn khá xa và có thể để tắt Tùy chọn cho nhà phát triển. Steam và một số tiến trình phụ trợ của nó vẫn được tính. Bật “Tắt các mục hạn chế đối với tiến trình con” trong Developer options, và giữ Developer options luôn mở sau đó. Phiên bản Android này không có công tắc cho việc đó. Dùng Gỡ lỗi qua mạng không dây để đổi nó từ thiết bị này. Bản build này không có tệp tải cho bản DroidDeck này. @@ -3170,9 +3180,11 @@ %1$s giờ %1$d phút Vị trí ảnh + Vị trí ảnh (Ngang) + Vị trí ảnh (Dọc) Trên Dưới - Giữa (mặc định) + Giữa Trái Phải Lưu trữ @@ -4120,4 +4132,7 @@ Trò chơi này cài bản dành cho Linux. Hãy cài từ Steam. Thu phóng trò chơi Điều chỉnh độ phóng đại trò chơi từ 100% đến 300% + Lối tắt trong trò chơi + Hiển thị lối tắt Smart Glasses + Hiển thị nút Smart Glasses nổi phía trên trò chơi. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index e9623375c4..eb5407a271 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG 自适应 %1$d 需要 Steam 上的 Lossless Scaling - 请在 Steam 中安装 Lossless Scaling,或导入 Lossless.dll - 导入 Lossless.dll… - 正在使用 Steam 中的副本 - 正在使用已导入的副本 - 选择 Lossless.dll - Lossless.dll 已导入 - 该 Lossless.dll 已在使用中 - 此 Steam 账户未拥有 Lossless Scaling - 该文件不是 Lossless Scaling 的 Lossless.dll - 无法由此 Lossless.dll 准备 LSFG - LSFG 需要 Steam 上的 Lossless Scaling 或已导入的 Lossless.dll LSFG 无法从 Lossless.dll 准备其着色器 %1$s:不支持 %1$s:引擎失败 @@ -644,6 +633,9 @@ 主机名 Steam 看到的本设备名称。留空恢复为 %1$s。 仅限字母、数字,连字符只能位于中间,最多 63 个字符。 + 桌面以普通用户运行 + 桌面及其应用和终端以普通用户 deck 而非 root 运行,适用于拒绝以 root 运行的应用。sudo 仍可使用。下次启动桌面时生效。 + 需要开启“不使用 proot 运行”。 Android 将会终止此会话 已安装 可下载 @@ -1329,6 +1321,11 @@ 准备 无线调试无法连接;配对即可开启 配对 + Quest 没有配对界面。请在电脑上运行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 和 adb tcpip 5555。然后点按“允许”,并在头显中接受提示 + 允许 + 在头显中接受“允许调试吗?”,并勾选“始终允许” + 无法连接。请在头显中接受调试提示;如果没有出现提示,请在电脑上运行 adb tcpip 5555 后重试 + 无法连接无线调试。点按“允许”重新设置 安装 登录 PR #%1$d @@ -1391,6 +1388,16 @@ 将 Joy-Con 用作 VR 手柄 SteamVR 运行时,每个 Joy-Con 都会成为一只手。将其指向前方并按住 HOME 键或截图键即可重新居中。 动画 + 毛玻璃 + 在启动器后方显示模糊的壁纸。耗电更多。 + 毛玻璃壁纸 + 毛玻璃卡片 + 卡片和分组会透出少许壁纸。菜单和对话框保持不透明。 + 需要开启毛玻璃壁纸。 + 壁纸透明度 + 壁纸透出的程度。 + 卡片透明度 + 卡片透出壁纸的程度。 存储空间不足时提醒 可用空间不足 10 GB 时,启动 Steam 前先询问。 布局 @@ -2184,6 +2191,7 @@ 左侧 居中 右侧 + 分屏 Steam 快速访问菜单暂不可用。 游戏内数据 下屏 HUD @@ -2493,6 +2501,8 @@ %1$s 如果无法做到,请将此设备连接到装有 ADB 的电脑并运行下方命令,然后返回此处重新检查。 可以启动 Steam 会话了。 此 Android 版本不使用该限制。 + 子进程限制由 DroidDeck 处理 + DroidDeck 在 Android 不计数的进程中运行大部分会话程序,使会话远低于上限,因此开发者选项可以保持关闭。Steam 及其部分辅助进程仍会被计数。 在开发者选项中打开“停止限制子进程”,之后请保持开发者选项开启。 此 Android 版本没有该开关。请使用无线调试在此设备上更改。 此构建没有适用于此 DroidDeck 副本的下载。 @@ -3170,9 +3180,11 @@ 下载内容与“组件”页面共享。在上方选择已下载的版本,即可在下次启动游戏时使用。 选择要下载的版本 画面位置 + 画面位置(横屏) + 画面位置(竖屏) 置顶 置底 - 居中(默认) + 居中 左侧 右侧 存储 @@ -4118,4 +4130,7 @@ 请先关闭 Steam 请先暂停 Steam 下载 此游戏会安装其 Linux 版本。请通过 Steam 安装。 + 游戏内快捷方式 + 显示 Smart Glasses 快捷方式 + 在游戏画面上显示悬浮的 Smart Glasses 按钮。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index ab70512c13..7f4bbd0233 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG 自適應 %1$d 需要 Steam 上的 Lossless Scaling - 請在 Steam 安裝 Lossless Scaling,或匯入 Lossless.dll - 匯入 Lossless.dll… - 正在使用 Steam 上的版本 - 正在使用匯入的版本 - 選擇 Lossless.dll - 已匯入 Lossless.dll - 此 Lossless.dll 已在使用中 - 此 Steam 帳戶未擁有 Lossless Scaling - 此檔案不是 Lossless Scaling 的 Lossless.dll - 無法從此 Lossless.dll 準備 LSFG - LSFG 需要 Steam 上的 Lossless Scaling 或已匯入的 Lossless.dll LSFG 無法從 Lossless.dll 準備著色器 %1$s:不支援 %1$s:引擎故障 @@ -644,6 +633,9 @@ 主機名稱 Steam 看到的此裝置名稱。留空則還原為 %1$s。 只可使用字母、數字和中間的連字號,最多 63 個字元。 + 桌面以普通用戶執行 + 桌面及其應用程式和終端機會以普通用戶 deck 而非 root 執行,適用於拒絕以 root 執行的應用程式。sudo 仍可使用。下次開啟桌面時生效。 + 需要開啟「不使用 proot 執行」。 Android 已設定為終止此會話 已安裝 可供下載 @@ -1245,6 +1237,11 @@ 準備 無線偵錯無法連線;按「配對」即可開啟 配對 + Quest 沒有配對畫面。請在電腦上執行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 及 adb tcpip 5555。然後輕按「允許」,並在頭戴裝置中接受提示 + 允許 + 在頭戴裝置中接受「要允許偵錯嗎?」,並剔選「一律允許」 + 無法連接。請在頭戴裝置中接受偵錯提示;如果沒有出現提示,請在電腦上執行 adb tcpip 5555 後再試一次 + 無法連接無線偵錯。輕按「允許」重新設定 安裝 登入 PR #%1$d @@ -1307,6 +1304,16 @@ 將 Joy-Con 用作 VR 控制器 SteamVR 執行時,每個 Joy-Con 都會變成一隻手。將它指向前方並按住 HOME 鍵或擷取鍵,即可重新置中。 動畫 + 毛玻璃 + 在啟動器後方顯示模糊的桌布。耗電較多。 + 毛玻璃桌布 + 毛玻璃卡片 + 卡片和群組會透出少許桌布。選單和對話框保持不透明。 + 需要開啟毛玻璃桌布。 + 桌布透明度 + 桌布透出的程度。 + 卡片透明度 + 卡片透出桌布的程度。 儲存空間不足時提醒 可用空間少於 10 GB 時,啟動 Steam 前先詢問。 佈局 @@ -2106,6 +2113,7 @@ 左側 置中 右側 + 分割 Steam 快速存取選單暫時無法使用。 遊戲內數據 下方螢幕 HUD @@ -2413,6 +2421,8 @@ %1$s 如無法這樣做,請將此裝置連接到已安裝 ADB 的電腦,並執行以下指令,然後返回這裡再檢查一次。 可以啟動 Steam 會話。 此 Android 版本不使用此限制。 + 子程序限制由 DroidDeck 處理 + DroidDeck 在 Android 不計算的程序中執行工作階段的大部分程式,讓工作階段遠低於上限,因此開發人員選項可以保持關閉。Steam 及其部分輔助程序仍會被計算。 在開發人員選項中開啟「停用對子處理過程的限制」,之後請保持開發人員選項開啟。 此 Android 版本沒有此開關。請使用無線偵錯,直接在此裝置上更改。 此版本沒有適用於此 DroidDeck 版本的下載。 @@ -3167,9 +3177,11 @@ 下載內容與「元件」頁面共用。在上方選擇已下載的版本,即可在下次啟動遊戲時使用。 選擇要下載的版本 畫面位置 + 畫面位置(橫向) + 畫面位置(直向) 置頂 置底 - 置中(預設) + 置中 左側 右側 儲存空間 @@ -4118,4 +4130,7 @@ 請先關閉 Steam 請先暫停 Steam 下載 此遊戲會安裝其 Linux 版本。請透過 Steam 安裝。 + 遊戲內捷徑 + 顯示 Smart Glasses 捷徑 + 在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index b2e20baea0..e52193ca17 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG 自適應 %1$d 需要 Steam 上的 Lossless Scaling - 在 Steam 中安裝 Lossless Scaling,或匯入 Lossless.dll - 匯入 Lossless.dll… - 正在使用 Steam 上的版本 - 正在使用匯入的版本 - 選擇 Lossless.dll 檔案 - 已匯入 Lossless.dll - 這個 Lossless.dll 已經在使用中了 - 此 Steam 帳號沒有 Lossless Scaling - 此檔案不是 Lossless Scaling 的 Lossless.dll - 無法從此 Lossless.dll 準備 LSFG - LSFG 需要來自 Steam 的 Lossless Scaling,或是匯入的 Lossless.dll 檔案 LSFG 無法從此 Lossless.dll 準備其著色器 %1$s:不支援 %1$s:引擎失敗 @@ -644,6 +633,9 @@ 主機名稱 Steam 看到的此裝置名稱。留空可還原為 %1$s。 只能包含字母、數字和中間的連字號,最多 63 個字元。 + 桌面以一般使用者執行 + 桌面及其應用程式和終端機會以一般使用者 deck 而非 root 執行,適用於拒絕以 root 執行的應用程式。sudo 仍可使用。下次開啟桌面時生效。 + 需要開啟「不使用 proot 執行」。 Android 已設定為結束此工作階段 已安裝 可下載 @@ -1245,6 +1237,11 @@ 準備 無線偵錯無法連線;配對即可開啟 配對 + Quest 沒有配對畫面。請在電腦上執行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 和 adb tcpip 5555。接著輕觸「允許」,並在頭戴式裝置中接受提示 + 允許 + 在頭戴式裝置中接受「要允許偵錯嗎?」,並勾選「一律允許」 + 無法連線。請在頭戴式裝置中接受偵錯提示;如果沒有出現提示,請在電腦上執行 adb tcpip 5555 後再試一次 + 無法連上無線偵錯。輕觸「允許」重新設定 安裝 登入 PR #%1$d @@ -1307,6 +1304,16 @@ 將 Joy-Con 當作 VR 控制器 SteamVR 執行時,每個 Joy-Con 都會變成一隻手。將它指向前方並按住 HOME 鍵或擷取鍵,即可重新置中。 動畫 + 毛玻璃 + 在啟動器後方顯示模糊的桌布。較為耗電。 + 毛玻璃桌布 + 毛玻璃卡片 + 卡片和群組會透出少許桌布。選單和對話方塊保持不透明。 + 需要開啟毛玻璃桌布。 + 桌布透明度 + 桌布透出的程度。 + 卡片透明度 + 卡片透出桌布的程度。 儲存空間不足時提醒 可用空間少於 10 GB 時,啟動 Steam 前先詢問。 版面配置 @@ -2106,6 +2113,7 @@ 左側 置中 右側 + 分割 Steam 快速存取選單暫時無法使用。 遊戲內數據 下螢幕 HUD @@ -2413,6 +2421,8 @@ %1$s 如果無法這麼做,請將此裝置連接到裝有 ADB 的電腦並執行下方指令,然後返回這裡重新檢查。 可以啟動 Steam 工作階段。 此 Android 版本不使用這項限制。 + 子程序限制由 DroidDeck 處理 + DroidDeck 在 Android 不計算的程序中執行工作階段的大部分程式,讓工作階段遠低於上限,因此開發人員選項可以保持關閉。Steam 及其部分輔助程序仍會被計算。 在開發人員選項中開啟「停止限制子程序」,之後請保持開發人員選項開啟。 此 Android 版本沒有這個開關。請使用無線偵錯,直接在此裝置上變更。 此組建版本沒有適用於此 DroidDeck 複本的下載檔案。 @@ -3167,9 +3177,11 @@ 下載內容與「元件」頁面共用。在上方選擇已下載的版本,即可在下次啟動遊戲時使用。 選擇要下載的版本 畫面位置 + 畫面位置(橫向) + 畫面位置(直向) 置頂 置底 - 置中(預設) + 置中 左側 右側 儲存空間 @@ -4118,4 +4130,7 @@ 請先關閉 Steam 請先暫停 Steam 下載 此遊戲會安裝其 Linux 版本。請透過 Steam 安裝。 + 遊戲內捷徑 + 顯示 Smart Glasses 捷徑 + 在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 913dcab14c..1289af2a4b 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -83,17 +83,6 @@ LSFG %1$d× LSFG Adaptive %1$d Needs Lossless Scaling on Steam - Install Lossless Scaling in Steam or import Lossless.dll - Import Lossless.dll… - Using the copy from Steam - Using an imported copy - Choose Lossless.dll - Lossless.dll imported - This Lossless.dll is already in use - Lossless Scaling is not owned on this Steam account - This file is not Lossless Scaling\'s Lossless.dll - Could not prepare LSFG from this Lossless.dll - LSFG needs Lossless Scaling from Steam or an imported Lossless.dll LSFG could not prepare its shaders from Lossless.dll %1$s: unsupported %1$s: engine failed @@ -699,6 +688,9 @@ Host name The name Steam sees for this device. Blank restores %1$s. Letters, digits and inner hyphens only, up to 63 characters. + Desktop runs as a user + The desktop, its apps and its terminals run as the ordinary user deck instead of root, for apps that refuse root. sudo still works. Applies to the next desktop. + Needs Run without proot. Android is set to kill this session Installed Available to download @@ -728,7 +720,22 @@ Next page Arrange pages More - Back to %1$s + Performance + Game + VR & glasses + Frame pacing + Mouse + Keyboard layout + Input profile + Compatibility + Fine tuning + controller connected + no controller + running + custom look + attached + downloading + Pause game Back to %1$s Nothing is kept here. Arrange pages and move one below the More row. Reset Done @@ -1185,6 +1192,21 @@ PR #%1$d test build %1$d MB UPDATE CHANNEL + INSTALLED + FOR TESTERS + Test build + Lab build + On the PR #%1$d test build + On DroidDeck %1$s + DroidDeck %1$s + built %1$s + Check now + Tests + latest %1$s + Released %1$s + Switch to %1$s%2$s + Older than your installed build (%1$s) + Your games and settings stay. Stable Tested releases, for most people %1$s · %2$s @@ -1414,6 +1436,11 @@ Prepare Wireless debugging isn\'t reachable; Pair turns it on Pair + Quest has no pairing screen. From a computer, run once: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS and adb tcpip 5555. Then tap Allow and accept the prompt in the headset + Allow + Accept “Allow debugging?” in the headset, with Always allow ticked + Couldn\'t connect. Accept the debugging prompt in the headset, or if none appeared, run adb tcpip 5555 from a computer and try again + Wireless debugging isn\'t reachable. Tap Allow to set it up again Install Sign in Free models @@ -1492,6 +1519,16 @@ Joy-Cons as VR controllers While SteamVR runs, each Joy-Con becomes a hand. Point it ahead and hold Home or Capture to recenter it. Animations + Frosted + Shows your wallpaper, blurred, behind the launcher. Uses more battery. + Frosted wallpaper + Frosted cards + Cards and groups let a little of the wallpaper through. Menus and dialogs stay solid. + Needs Frosted wallpaper. + Wallpaper transparency + How much of the wallpaper shows through. + Card transparency + How much of the wallpaper shows through cards. Warn when storage is low Ask before starting Steam when free space is under 10 GB. Layout @@ -2436,6 +2473,7 @@ Left Center Right + Split Steam\'s Quick Access menu is not available yet. In-game stats Bottom screen HUD @@ -2766,6 +2804,8 @@ %1$s If that is not possible, connect this device to a computer with ADB and run the command below. Return here and check again. Steam sessions can start. This Android version does not use this limit. + Child-process limit handled by DroidDeck + DroidDeck runs most of the session\'s programs in processes Android does not count, which keeps the session well under the limit, so Developer options can stay off. Steam and some of its helpers still count. Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards. This Android version has no switch for it. Use Wireless debugging to change it from this device. This build has no download for this copy of DroidDeck. @@ -2820,6 +2860,9 @@ Image scaling Adjust game magnification from 100% to 300% Game zoom + %1$d%% + Engine + Use global setting Integer scaling Uses the largest whole-number scale that fits. May crop screen edges. If the source is larger than the output, fractional scaling fits the full image. Resolution is configured separately. Fit @@ -3405,6 +3448,9 @@ %1$d×%2$d · %3$d Hz · %4$s 2D 3D + In-game shortcut + Show Smart Glasses shortcut + Show the floating Smart Glasses button over the game. Game on glasses Show the game only on the glasses. Off: the phone shows it and Android mirrors the phone. Display @@ -3556,11 +3602,13 @@ Experimental XREAL 1S, One, One Pro, One Pro+ and Aura support. Use Follow mode and turn off stabilization in the glasses menu; on the Aura, also turn off Spatial Anchor. Head tracking and 2D/3D switching are tested on the Aura and One Pro+. Experimental Pro 2 head tracking. Brightness, volume, and display switching are not supported yet. Picture position + Landscape picture position + Portrait picture position Top Left Right Bottom - Center (default) + Center 6DoF virtual screen Positional tracking — experimental Physical movement in VR and around virtual screens. Restarting tracking takes a moment. @@ -4369,6 +4417,7 @@ Volume No audio files found in this soundtrack Launch unavailable + Image not found: %1$s No web browser is available to open this link. Grab Drop @@ -4497,4 +4546,6 @@ Close Steam first Pause the Steam download first This game installs its Linux build. Install it from Steam. + Direct game frames (experimental) + With Zero-copy enabled, compatible Steam games can avoid a frame copy. Takes effect next session. diff --git a/app/src/main/res/values/zerofg_framegen.xml b/app/src/main/res/values/zerofg_framegen.xml new file mode 100644 index 0000000000..0f98cf7e8e --- /dev/null +++ b/app/src/main/res/values/zerofg_framegen.xml @@ -0,0 +1,4 @@ + + + ZeroFG %1$d× + diff --git a/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt index 63c1003b4f..f104ed089b 100644 --- a/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt @@ -176,4 +176,68 @@ class PulseAudioComponentTest { pool.shutdownNow() } } + + @Test + fun startupCrashDowngradesToStandardModeAndCapsRestartLoop() { + val host = PulseAudioComponent.HostLifecycle { } + val generation = host.begin() + assertFalse(host.preferStandardPerformanceMode()) + + var pid = 31500 + for (i in 0 until PulseAudioComponent.HostLifecycle.MAX_STARTUP_CRASH_RESTARTS) { + assertTrue(host.launch(generation) { pid++ }) + assertTrue(host.exited(generation)) + val delay = host.nextRestartDelayMs(generation) + assertTrue("expected positive backoff on startup crash #$i, got $delay", delay > 0L) + assertTrue(host.preferStandardPerformanceMode()) + } + + // One more crash before any sink comes up must stop the hot crash-restart loop. + assertTrue(host.launch(generation) { pid++ }) + assertTrue(host.exited(generation)) + assertEquals(-1L, host.nextRestartDelayMs(generation)) + + // A fresh session resets both the fallback preference and the crash counter. + val next = host.begin() + assertFalse(host.preferStandardPerformanceMode()) + assertTrue(host.launch(next) { pid++ }) + assertTrue(host.exited(next)) + assertTrue(host.nextRestartDelayMs(next) > 0L) + } + + @Test + fun healthySinkResetsCrashCounterAndRestartsImmediately() { + val host = PulseAudioComponent.HostLifecycle { } + val generation = host.begin() + + // First startup crashes -> switches to standard mode with backoff. + assertTrue(host.launch(generation) { 31600 }) + assertTrue(host.exited(generation)) + assertTrue(host.nextRestartDelayMs(generation) > 0L) + assertTrue(host.preferStandardPerformanceMode()) + + // Replacement host brings up a working sink -> later runtime exit restarts immediately. + assertTrue(host.launch(generation) { 31601 }) + host.markSinkReady(host.token()) + assertTrue(host.exited(generation)) + assertEquals(0L, host.nextRestartDelayMs(generation)) + assertTrue(host.preferStandardPerformanceMode()) + } + + @Test + fun markLowLatencyFailedIgnoresStaleTokens() { + val host = PulseAudioComponent.HostLifecycle { } + val generation = host.begin() + assertTrue(host.launch(generation) { 31700 }) + val first = host.token() + val next = host.begin() + // Before the replacement launches, token still equals launches, but pid is stopped. + host.markLowLatencyFailed(first) + assertFalse(host.preferStandardPerformanceMode()) + assertTrue(host.launch(next) { 31701 }) + host.markLowLatencyFailed(first) + assertFalse(host.preferStandardPerformanceMode()) + host.markLowLatencyFailed(host.token()) + assertTrue(host.preferStandardPerformanceMode()) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt index 219ecad5a1..f4a27ea825 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt @@ -20,6 +20,24 @@ class GameEnvironmentTest { assertEquals("1", GameEnvironment.effective(config, "", "43", forceSsbs = true)[GameEnvironment.FORCE_SSBS]) } + @Test fun knownGameFixesBeatSharedSettingsButNotTheGamesOwn() { + val shared = GameEnvironment.Config(shared = mapOf("FEX_X87REDUCEDPRECISION" to "1")) + assertEquals("0", GameEnvironment.effective(shared, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"]) + assertEquals("1", GameEnvironment.effective(shared, "PERFORMANCE_TSO", "12110")["FEX_X87REDUCEDPRECISION"]) + val own = shared.withEntries("12100", mapOf("FEX_X87REDUCEDPRECISION" to "1")) + assertEquals("1", GameEnvironment.effective(own, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"]) + assertEquals("1", GameEnvironment.withKnownGames(own).games["12100"]?.get("FEX_X87REDUCEDPRECISION")) + assertEquals("0", GameEnvironment.withKnownGames(shared).games["12100"]?.get("FEX_X87REDUCEDPRECISION")) + } + + @Test fun aGamePresetKeepsTheGamesKnownFix() { + val picked = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "12100", "PERFORMANCE") + assertEquals("0", GameEnvironment.effective(picked, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"]) + assertEquals("PERFORMANCE", GameEnvironment.gameFexPreset(picked, "12100")) + val other = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "12110", "PERFORMANCE") + assertEquals("1", GameEnvironment.effective(other, "PERFORMANCE_TSO", "12110")["FEX_X87REDUCEDPRECISION"]) + } + @Test fun gameOverridesSharedAndPresetWithoutLeakingToOtherGames() { val config = GameEnvironment.Config( shared = mapOf("FEX_MULTIBLOCK" to "0", "VKD3D_FEATURE_LEVEL" to "12_2"), diff --git a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt index 3f05d01a36..5ea537d73f 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt @@ -81,4 +81,10 @@ class PhantomProcessLimitTest { assertFalse(PhantomProcessLimit.hasDeveloperToggle(33)) assertTrue(PhantomProcessLimit.hasDeveloperToggle(34)) } + + @Test + fun theLimitOnDoesNotBlockSteamWhenTheSessionStaysOutOfItsCount() { + assertFalse(PhantomProcessLimit.blocksSteam(PhantomProcessStatus.UNCOUNTED)) + assertTrue(PhantomProcessLimit.blocksSteam(PhantomProcessStatus.ENABLED)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt index 5afd7f83a9..0eda995f76 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt @@ -30,6 +30,16 @@ class FrameGenTest { assertEquals(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 90), FrameGen.mode(context)) } + @Test fun zeroFgModeRoundTrips() { + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3)) + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), FrameGen.mode(context)) + } + + @Test fun zeroFgDoesNotKeepAdaptiveTarget() { + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_ZEROFG, multiplier = 4, target = 60)) + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 4), FrameGen.mode(context)) + } + @Test fun fixedMultiplierReplacesATarget() { FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 120)) FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, 3)) diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt index 1583514770..23098cc9c0 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt @@ -40,9 +40,39 @@ class LosslessTest { assertTrue(Lossless.owned(context)) } - @Test fun importIsRefusedWithoutOwnership() { - val dll = File(context.cacheDir, "Lossless.dll").apply { writeText("not a dll") } - assertFalse(Lossless.owned(context)) - assertEquals(Lossless.ImportResult.NOT_OWNED, Lossless.import(context, dll)) + @Test fun anOldManualImportCannotBeUsedOrRebuiltEvenWhenOwned() { + val prefs = context.getSharedPreferences("lossless", Context.MODE_PRIVATE) + prefs.edit().putBoolean("owned", true).putString("source", "IMPORT").putString("id", "legacy") + .putString("steamStamp", "old stamp").commit() + val dir = File(context.filesDir, "lsfg").apply { mkdirs() } + File(dir, "Lossless.dll").writeText("legacy DLL") + File(dir, "shaders-legacy.cache").writeText("legacy cache") + + assertFalse(Lossless.state(context).ready) + assertNull(Lossless.cacheFile(context)) + assertEquals(LsfgNative.STATUS_NOT_INSTALLED, Lossless.sync(context)) + assertFalse(prefs.contains("steamStamp")) + assertTrue(Lossless.owned(context)) + } + + @Test fun aPreviouslyPreparedSteamCacheRemainsAvailable() { + val prefs = context.getSharedPreferences("lossless", Context.MODE_PRIVATE) + prefs.edit().putBoolean("owned", true).putString("source", "STEAM").putString("id", "steam").commit() + val cache = File(File(context.filesDir, "lsfg").apply { mkdirs() }, "shaders-steam.cache") + cache.writeText("cache") + + assertEquals(cache, Lossless.cacheFile(context)) + assertTrue(Lossless.state(context).ready) + } + + @Test fun looseDllWithoutAnInstallManifestDoesNotCountAsASteamInstall() { + val library = File(context.cacheDir, "library") + val dll = File(library, "steamapps/common/Lossless Scaling/Lossless.dll") + dll.parentFile!!.mkdirs() + dll.writeText("fixture") + + assertNull(Lossless.installedSteamDll(listOf(library))) + File(library, "steamapps/appmanifest_993090.acf").writeText("fixture") + assertEquals(dll, Lossless.installedSteamDll(listOf(library))) } } diff --git a/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudClippingTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudClippingTest.kt new file mode 100644 index 0000000000..00ece3479d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudClippingTest.kt @@ -0,0 +1,81 @@ +package com.droiddeck.launcher.hud + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.view.View +import android.view.ViewGroup.LayoutParams.WRAP_CONTENT +import android.widget.FrameLayout +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], qualifiers = "xhdpi") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class DroidDeckHudClippingTest { + @Test fun aLargerLayoutDrawsItsWholePanelAfterBeingMovedBackOnScreen() { + val app = RuntimeEnvironment.getApplication() + val root = FrameLayout(app) + val hud = DroidDeckHudView(app) + root.addView(hud, FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)) + val config = DroidDeckHudConfig.DEFAULTS + ("hudScale" to "200") + fun select(size: String) { + hud.applyConfig(DroidDeckHudConfig.encode(config + ("hudSize" to size))) + hud.showForTest(DroidDeckHudPanelTest.SNAPSHOT, "DXVK", 0L) + } + fun layout(w: Int, h: Int) { + root.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY)) + root.layout(0, 0, w, h) + } + fun frame() = Bitmap.createBitmap(root.width, root.height, Bitmap.Config.ARGB_8888) + .also { root.draw(Canvas(it)) } + + select("tiles") + layout(3000, 2000) + val naturalWidth = hud.width + val naturalHeight = hud.height + val viewportWidth = naturalWidth + 30 + val viewportHeight = naturalHeight / 2 + + select("pill") + layout(viewportWidth, viewportHeight) + hud.y = viewportHeight - 10f + select("tiles") + layout(viewportWidth, viewportHeight) + hud.x = 10f + hud.y = 0f + + val afterMove = frame() + val middle = hud.x.toInt() + hud.width / 2 + assertTrue("the HUD is drawn", Color.alpha(afterMove.getPixel(middle, hud.height / 2)) > 0) + val lastDrawnRow = (hud.height - 1 downTo 0).first { Color.alpha(afterMove.getPixel(middle, it)) > 0 } + assertTrue("the bottom edge and its outer inset are visible after the move; cutoff row $lastDrawnRow", + lastDrawnRow < hud.height - 1) + assertTrue("vertical fitting preserves the panel aspect instead of clipping it", hud.width < naturalWidth) + + layout(3000, 2000) + assertEquals(naturalWidth, hud.width) + assertEquals(naturalHeight, hud.height) + } + + @Test fun aNarrowViewportFitsBothDimensionsAndKeepsThePanelAspect() { + val hud = DroidDeckHudView(RuntimeEnvironment.getApplication()) + hud.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudSize" to "tiles"))) + hud.showForTest(DroidDeckHudPanelTest.SNAPSHOT, "DXVK", 0L) + val unlimited = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) + hud.measure(unlimited, unlimited) + val naturalWidth = hud.measuredWidth + val naturalHeight = hud.measuredHeight + val narrow = View.MeasureSpec.makeMeasureSpec(naturalWidth / 2, View.MeasureSpec.AT_MOST) + hud.measure(narrow, unlimited) + assertEquals(naturalWidth / 2, hud.measuredWidth) + assertEquals(naturalHeight / 2f, hud.measuredHeight.toFloat(), 2f) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudPanelTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudPanelTest.kt index 54d3e5584e..e39a1b2ee7 100644 --- a/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudPanelTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudPanelTest.kt @@ -204,6 +204,24 @@ class DroidDeckHudPanelTest { assertEquals(ramFirst.toString(), listOf("RAM", "FPS", "PWR"), ramFirst.map { it.take(3) }) } + @Test fun optionalLowsCanBeSavedAndResetToOff() { + val app = RuntimeEnvironment.getApplication() + val defaults = DroidDeckHudConfig.load(app) + assertEquals("1", defaults["showFPS"]) + assertEquals("1", defaults["showLow1"]) + assertEquals("0", defaults["showLow01"]) + assertEquals("0", defaults["showLow001"]) + + val switches = mapOf("showLow01" to true, "showLow001" to true) + DroidDeckHudConfig.choose(app, switches, emptyList()) + val saved = DroidDeckHudConfig.load(app) + for (key in switches.keys) assertEquals("1", saved[key]) + + DroidDeckHudConfig.reset(app) + val reset = DroidDeckHudConfig.load(app) + for (key in switches.keys) assertEquals("0", reset[key]) + } + @Test fun aSaveKeepsTheLegacyOrderForTheOtherSizes() { val app = RuntimeEnvironment.getApplication() SessionPrefs.setDroidDeckHudConfig(app, "hudSize=strip,hudOrder=showRAM|showFPS") @@ -251,7 +269,9 @@ class DroidDeckHudPanelTest { val lines = view.linesForTest() assertEquals(lines.toString(), 1, lines.size) val line = lines.single() - listOf("DXVK", "fps", "GPU", "CPU", "RAM", "BAT 79%").forEach { assertTrue(line, it in line) } + listOf("DXVK", "fps", "1%", "GPU", "CPU", "RAM", "BAT 79%").forEach { assertTrue(line, it in line) } + assertFalse(line, "0.1%" in line) + assertFalse(line, "0.01%" in line) assertTrue(line, line.indexOf("DXVK") < line.indexOf("GPU") && line.indexOf("GPU") < line.indexOf("BAT")) val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888) diff --git a/app/src/test/java/com/droiddeck/launcher/input/HeldInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/HeldInputTest.kt new file mode 100644 index 0000000000..bf25bf731f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/HeldInputTest.kt @@ -0,0 +1,57 @@ +package com.droiddeck.launcher.input + +import org.junit.Assert.assertEquals +import org.junit.Test + +class HeldInputTest { + @Test + fun normalRoutingUsesDefaultEmitter() { + val events = mutableListOf>() + val input = HeldInput { code, down -> events.add(code to down) } + input.set(1, 30, true) + input.set(1, 30, false) + assertEquals(listOf(30 to true, 30 to false), events) + } + + @Test + fun orderedSenderHandlesDownRepeatedDownSecondOwnerAndFinalRelease() { + val defaultEvents = mutableListOf>() + val orderedEvents = mutableListOf>() + val input = HeldInput { code, down -> defaultEvents.add(code to down) } + val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) } + input.set(1, 30, true, ordered) + input.set(1, 30, true, ordered) + input.set(2, 30, true, ordered) + input.set(1, 30, false) + input.set(2, 30, false) + assertEquals(listOf(30 to true, 30 to false), orderedEvents) + assertEquals(emptyList>(), defaultEvents) + } + + @Test + fun releaseChoosesMatchingRoute() { + val defaultEvents = mutableListOf>() + val orderedEvents = mutableListOf>() + val input = HeldInput { code, down -> defaultEvents.add(code to down) } + val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) } + input.set(1, 31, true, ordered) + input.set(2, 32, true) + input.release(2) + input.release(1) + assertEquals(listOf(31 to true, 31 to false), orderedEvents) + assertEquals(listOf(32 to true, 32 to false), defaultEvents) + } + + @Test + fun clearChoosesMatchingRoute() { + val defaultEvents = mutableListOf>() + val orderedEvents = mutableListOf>() + val input = HeldInput { code, down -> defaultEvents.add(code to down) } + val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) } + input.set(1, 40, true, ordered) + input.set(2, 41, true) + input.clear() + assertEquals(listOf(40 to true, 40 to false), orderedEvents) + assertEquals(listOf(41 to true, 41 to false), defaultEvents) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt index 1f669d1567..0b8d28a23b 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.input import android.content.Context import android.content.ContextWrapper import android.content.SharedPreferences +import android.graphics.Rect import org.json.JSONObject import org.junit.Assert.* import org.junit.Before @@ -428,23 +429,53 @@ class InputLibraryTest { assertTrue(left.width > left.height * 800f / 1200f && right.width > right.height * 800f / 1200f) } + @Test fun theFreshOverlayShowsBothSticksAtRestInEitherOrientation() { + val overlay = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!! + assertFalse(ControllerPrefs.read(context).adaptiveSticks) + assertEquals(false, overlay.adaptiveSticks) + for ((width, height) in listOf(1080 to 1920, 1920 to 1080)) { + val sticks = OnScreenLayout.elements(context, overlay, width, height, Rect()) + .filter { it.kind == InputElementKind.STICK } + assertEquals(setOf(InputControl.LS, InputControl.RS), sticks.map { it.control }.toSet()) + assertTrue(sticks.none { it.floating || it.hideWhenIdle }) + } + } + + @Test fun anExistingAdaptivePreferenceStillAppliesWhenImportingAnOverlay() { + ControllerPrefs.setAdaptiveSticks(context, true) + val overlay = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!! + assertEquals(true, overlay.adaptiveSticks) + } + + @Test fun onScreenOpacityDefaultsToFullAndClampsWithoutChangingLayoutStyle() { + ControllerPrefs.setOpacity(context, 60) + val layout = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!! + assertEquals(100, ControllerPrefs.read(context).onScreenOpacity) + for ((requested, expected) in listOf(0 to 10, 45 to 45, 101 to 100)) { + ControllerPrefs.setOnScreenOpacity(context, requested) + assertEquals(expected, ControllerPrefs.read(context).onScreenOpacity) + assertEquals(60, ControllerPrefs.read(context).opacity) + assertEquals(layout, InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)) + } + } + @Test fun adaptiveSticksToggleChangesOnlyTheSticksOfThatLayout() { val library = InputLibraries.read(context) val overlay = library.layouts.single { it.id == InputLibraries.OVERLAY } - assertEquals(true, overlay.adaptiveSticks) - InputLibraries.setAdaptiveSticks(context, overlay.id, false) - val off = InputLibraries.read(context) - val changed = off.layouts.single { it.id == overlay.id } - assertEquals(false, changed.adaptiveSticks) - assertFalse(ControllerPrefs.read(context).adaptiveSticks) - assertEquals(overlay.elements.filter { it.kind != InputElementKind.STICK }, changed.elements.filter { it.kind != InputElementKind.STICK }) - assertEquals(library.layouts.filter { it.id != overlay.id }, off.layouts.filter { it.id != overlay.id }) - assertNull(off.layouts.single { it.id == InputLibraries.DECK }.adaptiveSticks) + assertEquals(false, overlay.adaptiveSticks) assertTrue(InputLibraries.setAdaptiveSticks(context, overlay.id, true)) - assertEquals(true, InputLibraries.read(context).layouts.single { it.id == overlay.id }.adaptiveSticks) - prefs.edit().putString("library", JSONObject().put("version", 99).toString()).commit() - assertFalse(InputLibraries.setAdaptiveSticks(context, overlay.id, false)) + val enabled = InputLibraries.read(context) + val changed = enabled.layouts.single { it.id == overlay.id } + assertEquals(true, changed.adaptiveSticks) assertTrue(ControllerPrefs.read(context).adaptiveSticks) + assertEquals(overlay.elements.filter { it.kind != InputElementKind.STICK }, changed.elements.filter { it.kind != InputElementKind.STICK }) + assertEquals(library.layouts.filter { it.id != overlay.id }, enabled.layouts.filter { it.id != overlay.id }) + assertNull(enabled.layouts.single { it.id == InputLibraries.DECK }.adaptiveSticks) + assertTrue(InputLibraries.setAdaptiveSticks(context, overlay.id, false)) + assertEquals(false, InputLibraries.read(context).layouts.single { it.id == overlay.id }.adaptiveSticks) + prefs.edit().putString("library", JSONObject().put("version", 99).toString()).commit() + assertFalse(InputLibraries.setAdaptiveSticks(context, overlay.id, true)) + assertFalse(ControllerPrefs.read(context).adaptiveSticks) } @Test fun savedGamepadsFromTheFirstUnifiedBuildGetTheRoundLookOnce() { diff --git a/app/src/test/java/com/droiddeck/launcher/input/KeyboardHostTest.kt b/app/src/test/java/com/droiddeck/launcher/input/KeyboardHostTest.kt index eff9197525..9961c1d2f8 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/KeyboardHostTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/KeyboardHostTest.kt @@ -3,9 +3,15 @@ package com.droiddeck.launcher.input import android.app.Activity import android.content.Context import android.os.Looper +import android.text.InputType +import android.view.KeyEvent +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -20,11 +26,13 @@ import org.robolectric.annotation.Config class KeyboardHostTest { private lateinit var imm: InputMethodManager private lateinit var host: KeyboardHost + private val keys = mutableListOf() + private val texts = mutableListOf() @Before fun setUp() { val activity = Robolectric.buildActivity(Activity::class.java).setup().get() imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager - host = KeyboardHost(activity) + host = KeyboardHost(activity, { keys += it; true }, { texts += it }) activity.setContentView(FrameLayout(activity).apply { addView(host) }) idle() } @@ -41,6 +49,36 @@ class KeyboardHostTest { assertTrue(host.shown) } + @Config(sdk = [33]) + @Test fun shownEditorIsNotDescribedAsAPasswordField() { + host.show() + idle() + + val attrs = EditorInfo() + val connection = host.onCreateInputConnection(attrs) + + assertNotNull("shown host must expose an input connection", connection) + assertEquals( + "editor must be declared as a text field", + InputType.TYPE_CLASS_TEXT, + attrs.inputType and InputType.TYPE_MASK_CLASS, + ) + + val variation = attrs.inputType and InputType.TYPE_MASK_VARIATION + assertFalse( + "text field must not be a password field", + variation == InputType.TYPE_TEXT_VARIATION_PASSWORD, + ) + assertFalse( + "text field must not be a visible password field", + variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD, + ) + assertFalse( + "text field must not be a web password field", + variation == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD, + ) + } + @Config(sdk = [28]) @Test fun toggleHidesAKeyboardThatIsShowing() { host.show() @@ -51,5 +89,436 @@ class KeyboardHostTest { assertFalse(host.shown) } + @Config(sdk = [33]) + @Test fun mixedScriptTextIsCommittedOnceWithoutKeyEvents() { + host.show() + idle() + val text = "中文ABC123,。é😀" + + assertTrue(connection().commitText(text, 1)) + idle() + + assertEquals("the whole string must reach the guest once", listOf(text), texts) + assertTrue("non-ASCII text must not be turned into key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun latestCompositionIsCommittedOnceWhenFinished() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("zhong", 1) + connection.setComposingText("中文", 1) + assertTrue(texts.isEmpty()) + connection.finishComposingText() + connection.finishComposingText() + idle() + + assertTrue(keys.isEmpty()) + assertEquals(listOf("中文"), texts) + } + + @Config(sdk = [33]) + @Test fun finishedCandidateIsCommittedExactlyOnce() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("zhong", 1) + connection.deleteSurroundingText(1, 0) + connection.commitText("中文", 1) + connection.finishComposingText() + connection.setComposingText("ab", 1) + connection.deleteSurroundingText(1, 0) + connection.setComposingText("xy", 1) + connection.finishComposingText() + idle() + + assertEquals(listOf("中文", "xy"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun emptyCompositionCancelsPendingText() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("zhong", 1) + connection.setComposingText("", 1) + connection.finishComposingText() + idle() + + assertTrue(texts.isEmpty()) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun deleteWithinCompositionShortensPendingTextWithoutGuestBackspace() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("abc", 1) + connection.deleteSurroundingText(1, 0) + idle() + assertTrue(texts.isEmpty()) + assertTrue(keys.isEmpty()) + + connection.finishComposingText() + idle() + + assertEquals(listOf("ab"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun deleteBeyondCompositionForwardsOnlyResidualCountsWithoutResurrectingText() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("ab", 1) + connection.deleteSurroundingText(3, 1) + connection.finishComposingText() + connection.setComposingText("cd", 0) + connection.deleteSurroundingText(1, 3) + connection.finishComposingText() + idle() + + assertEquals(listOf("\b\u007f", "\b\u007f"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun composingCursorAtStartConsumesForwardDeleteAndForwardsBackspace() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("abc", 0) + connection.deleteSurroundingText(1, 0) + assertEquals(listOf("\b"), texts) + + connection.deleteSurroundingText(0, 1) + connection.finishComposingText() + idle() + + assertEquals(listOf("\b", "bc"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun utf16DeleteOfTrailingEmojiInCompositionPreservesChineseText() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("中文😀", 1) + connection.deleteSurroundingText(2, 0) + connection.finishComposingText() + idle() + + assertEquals(listOf("中文"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun chinesePendingTextFinishesBeforeEditorActionWithoutDuplication() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("中文", 1) + connection.performEditorAction(EditorInfo.IME_ACTION_SEND) + connection.finishComposingText() + idle() + + assertEquals(listOf("中文", "\r"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun chinesePendingTextFinishesBeforePlainSoftEnterWithoutDuplication() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("中文", 1) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)) + connection.finishComposingText() + idle() + + assertEquals(listOf("中文", "\r"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun unknownUtf16DeleteOfCommittedEmojiIsRejectedWithoutGuestEdit() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.commitText("A\uD83D\uDE00", 1)) + idle() + texts.clear() + + assertFalse("unknown committed UTF-16 deletion must be rejected", + connection.deleteSurroundingText(2, 0)) + idle() + assertTrue("a rejected deletion must not edit the guest", texts.isEmpty()) + + assertTrue(connection.deleteSurroundingTextInCodePoints(1, 0)) + idle() + assertEquals(listOf("\b"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun codePointDeleteAtEndOfComposingSurrogateSendsOnlyTextBeforeEmoji() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("A\uD83D\uDE00", 1) + assertFalse("half-surrogate UTF-16 deletion must be rejected", + connection.deleteSurroundingText(1, 0)) + idle() + assertTrue("a rejected half-surrogate deletion must retain original text", texts.isEmpty()) + + assertTrue(connection.deleteSurroundingTextInCodePoints(1, 0)) + connection.finishComposingText() + idle() + + assertEquals(listOf("A"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun codePointDeleteBeyondCompositionForwardsBothResidualControls() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.commitText("abcd", 1)) + idle() + texts.clear() + + assertTrue(connection.deleteSurroundingTextInCodePoints(2, 2)) + idle() + + assertEquals(listOf("\b\b\u007f\u007f"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun asciiTextIsCommittedAsOneTextCallback() { + host.show() + idle() + + assertTrue(connection().commitText("ab", 1)) + idle() + + assertEquals("ASCII must reach the guest as one whole commit", listOf("ab"), texts) + assertTrue("ASCII must not take the key event path", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun adjacentCommitsKeepTheirOrder() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.commitText("中文", 1)) + assertTrue(connection.commitText("中文", 1)) + assertTrue(connection.commitText(" ", 1)) + assertTrue(connection.commitText("abc", 1)) + idle() + + assertEquals("every commit must keep the order the IME sent it", listOf("中文", "中文", " ", "abc"), texts) + assertTrue("no commit may take the key event path", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun backspaceAndEnterQueueOrderedControls() { + host.show() + idle() + val connection = connection() + + connection.deleteSurroundingText(1, 0) + connection.performEditorAction(EditorInfo.IME_ACTION_SEND) + idle() + + assertEquals( + "soft edits must ride the ordered text FIFO, not the key event route", + listOf("\b", "\r"), texts, + ) + assertTrue("soft edits must not become key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun deleteSurroundingTextQueuesBackspaceThenForwardDelete() { + host.show() + idle() + + assertTrue(connection().deleteSurroundingText(1, 1)) + idle() + + assertEquals(listOf("\b\u007f"), texts) + assertTrue("deletions must not become key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun commitThenDeleteThenEditorActionKeepTheirOrder() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.commitText("中文", 1)) + assertTrue(connection.deleteSurroundingText(1, 0)) + assertTrue(connection.performEditorAction(EditorInfo.IME_ACTION_SEND)) + idle() + + assertEquals("a Chinese commit must not be overtaken by the soft edits after it", + listOf("中文", "\b", "\r"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun softEditKeysQueueExactlyOneControlPerPress() { + host.show() + idle() + val connection = connection() + + for ((keyCode, control) in listOf( + KeyEvent.KEYCODE_DEL to "\b", + KeyEvent.KEYCODE_FORWARD_DEL to "\u007f", + KeyEvent.KEYCODE_ENTER to "\r", + KeyEvent.KEYCODE_TAB to "\t", + )) { + texts.clear() + assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, keyCode))) + assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, keyCode))) + assertEquals("one down plus one up must queue exactly one control", + listOf(control), texts) + } + assertTrue("soft edit keys must not reach the key event route", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun modifiedSoftKeysStillTravelAsKeyEvents() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.sendKeyEvent( + keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, + KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON))) + idle() + + assertEquals("a modifier shortcut must keep using key events", + listOf(KeyEvent.KEYCODE_ENTER), keys.map { it.keyCode }) + assertTrue(texts.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun unmodifiedSoftDownStaysSoftWhenTheUpGainsAModifier() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))) + assertTrue(connection.sendKeyEvent( + keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, KeyEvent.META_CTRL_ON))) + idle() + + assertEquals("a plain press must stay a soft edit for its whole press", listOf("\r"), texts) + assertTrue("the matching up must follow the route picked on down", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun modifiedSoftDownStaysAKeyEventWhenTheUpLosesTheModifier() { + host.show() + idle() + val connection = connection() + + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, KeyEvent.META_SHIFT_ON)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)) + idle() + + assertEquals("a shortcut press keeps both of its key events", + listOf(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_ENTER), keys.map { it.keyCode }) + assertTrue("a shortcut press must not leak into the text channel", texts.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun repeatedSoftDownKeepsOneRouteAcrossModifierChanges() { + host.show() + idle() + val connection = connection() + + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) + connection.sendKeyEvent( + keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON, repeat = 2)) + connection.sendKeyEvent( + keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON)) + idle() + + assertEquals("autorepeat must stay on the soft control route", listOf("\b", "\b"), texts) + assertTrue("autorepeat must not turn into key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun interleavedSoftKeysKeepTheirOwnRoutes() { + host.show() + idle() + val connection = connection() + + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, KeyEvent.META_CTRL_ON)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_TAB)) + idle() + + assertEquals("only the plain press is a soft edit", listOf("\b"), texts) + assertEquals("the shortcut press keeps both of its key events", + listOf(KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_TAB), keys.map { it.keyCode }) + } + + @Config(sdk = [33]) + @Test fun typedChatTextAndSoftEditsStayOrdered() { + host.type("你好😀") + host.tap(KeyEvent.KEYCODE_DEL) + host.tap(KeyEvent.KEYCODE_ENTER) + idle() + + assertEquals("text, delete and enter must keep their order", + listOf("你好😀", "\b", "\r"), texts) + assertTrue("chat text and edits must not become key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun tappingEscapeStillSendsKeyEvents() { + host.tap(KeyEvent.KEYCODE_ESCAPE) + idle() + + assertEquals("escape must keep its down/up pair", + listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP), keys.map { it.action }) + assertEquals("escape must target the escape key", + listOf(KeyEvent.KEYCODE_ESCAPE, KeyEvent.KEYCODE_ESCAPE), keys.map { it.keyCode }) + assertTrue("escape must not use the text channel", texts.isEmpty()) + } + + private fun keyEvent(action: Int, keyCode: Int, metaState: Int = 0, repeat: Int = 0) = + KeyEvent(0L, 0L, action, keyCode, repeat, metaState) + + private fun connection(): InputConnection { + val connection = host.onCreateInputConnection(EditorInfo()) + assertNotNull("shown host must expose an input connection", connection) + return connection!! + } + private fun idle() = shadowOf(Looper.getMainLooper()).idle() } diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index 3b02f4db38..ba74358841 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -506,6 +506,20 @@ class OnScreenLayoutTest { } } + @Test fun controlsBelowTheGameKeepRearButtonsAtTheEdgesAndSticksInView() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val w = 1216 + val placed = OnScreenLayout.elements(context, gamepad(), w, 1900, Rect(), dock = OnScreenLayout.Dock.deck(true, null)) + fun centre(control: InputControl) = placed.single { it.control == control }.let { it.x + it.width / 2f } + assertTrue(centre(InputControl.L4) < centre(InputControl.L5)) + assertTrue(centre(InputControl.L5) < .5f && centre(InputControl.R5) > .5f) + assertTrue(centre(InputControl.R5) < centre(InputControl.R4)) + val shoulder = placed.single { it.control == InputControl.LB } + assertTrue(placed.filter { it.control in setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) } + .all { it.width < shoulder.width }) + assertTrue(placed.filter { it.kind == InputElementKind.STICK }.none { it.hideWhenIdle }) + } + private val legacyKeys = "29+33:0.3,0.7,44::Find::0.6:1:1:1" private fun importedOn(library: InputLibrary) = library.activeLayout(false, InputRole.PRIMARY)!!.elements.filter { it.id.startsWith("imported:") } diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt index 879c18233c..f4eac6423c 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt @@ -46,6 +46,7 @@ class SessionInputPointerTest { CompositorShadow.pointers.clear() CompositorShadow.events.clear() CompositorShadow.keys.clear() + CompositorShadow.ordered.clear() WriterShadow.mouse.clear() WriterShadow.beforeWheel = null } @@ -151,7 +152,8 @@ class SessionInputPointerTest { fun hardwareCtrl(down: Boolean) = ReflectionHelpers.callInstanceMethod(activity, "sendGuestKey", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 97), ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, down), - ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 8)) + ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 8), + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false)) output.key(29, true) hardwareCtrl(true) hardwareCtrl(false) @@ -249,10 +251,26 @@ class SessionInputPointerTest { @Test fun wowFieldSelectionPreservesCtrlHeldByTheInputProfile() { output.key(29, true) ReflectionHelpers.callInstanceMethod(activity, "selectGameField", - ReflectionHelpers.ClassParameter.from(IntArray::class.java, intArrayOf(46))) - assertEquals(listOf(29 to 1, 30 to 1, 30 to 0, 46 to 1, 46 to 0), CompositorShadow.keys) + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + assertEquals(listOf("select:true"), CompositorShadow.ordered) + assertEquals(listOf(29 to 1), CompositorShadow.keys) output.key(29, false) - assertEquals(29 to 0, CompositorShadow.keys.last()) + assertEquals(listOf(29 to 1, 29 to 0), CompositorShadow.keys) + } + + @Test fun wowChatQueuesCaretKeysBeforeAtomicTextAndSubmit() { + ReflectionHelpers.setField(activity, "keyboard", + KeyboardHost(activity, { false }, WaylandCompositor::textInputCommit)) + fun send(replace: Boolean) = ReflectionHelpers.callInstanceMethod(activity, "sendWowChat", + ReflectionHelpers.ClassParameter.from(String::class.java, "中文"), + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType!!, replace)) + send(true) + assertEquals(listOf("select:false", "submit:中文"), + CompositorShadow.ordered) + CompositorShadow.ordered.clear() + send(false) + assertEquals(listOf("key:107:1", "key:107:0", "submit:中文"), CompositorShadow.ordered) + assertEquals(emptyList>(), CompositorShadow.keys) } @Test fun horizontalWheelFinishesBeforeRawMouseDestruction() { @@ -311,10 +329,15 @@ class SessionInputPointerTest { val pointers = mutableListOf>() val events = mutableListOf>() val keys = mutableListOf>() + val ordered = mutableListOf() @JvmStatic @Implementation fun __staticInitializer__() {} @JvmStatic @Implementation fun nativeSendPointer(action: Int, x: Int, y: Int) { pointers += Triple(action, x, y) } @JvmStatic @Implementation fun nativeSendSceneInput(type: Int, code: Int, value: Int) { events += Triple(type, code, value) } @JvmStatic @Implementation fun nativeSendKey(code: Int, value: Int) { keys += code to value } + @JvmStatic @Implementation fun nativeSendKeyOrdered(code: Int, value: Int) { ordered += "key:$code:$value" } + @JvmStatic @Implementation fun nativeSelectGameField(copy: Boolean) { ordered += "select:$copy" } + @JvmStatic @Implementation fun textInputCommit(text: String) { ordered += "text:$text" } + @JvmStatic @Implementation fun textInputCommitAndSubmit(text: String) { ordered += "submit:$text" } } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionTextInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionTextInputTest.kt new file mode 100644 index 0000000000..9304c242c6 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionTextInputTest.kt @@ -0,0 +1,314 @@ +package com.droiddeck.launcher.input + +import android.net.LocalSocket +import android.net.LocalSocketAddress +import android.os.Looper +import android.system.Os +import android.system.OsConstants +import com.droiddeck.launcher.wayland.WaylandCompositor +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.annotation.LooperMode +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], shadows = [SessionTextInputTest.ShadowLocalSocket::class, SessionTextInputTest.ShadowWaylandCompositor::class]) +@LooperMode(LooperMode.Mode.PAUSED) +class SessionTextInputTest { + + @Before + fun setUp() { + ShadowLocalSocket.reset() + ShadowWaylandCompositor.reset() + shadowOf(Looper.getMainLooper()).idle() + } + + @After + fun tearDown() { + shadowOf(Looper.getMainLooper()).idle() + } + + @Test + fun retriesUntilGuestProvesReadyThenCompletes() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + assertTrue(ShadowWaylandCompositor.submit(73)) + shadowOf(Looper.getMainLooper()).idle() + val negative = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS) + assertEquals(73 to WaylandCompositor.TEXT_UNRESOLVED, negative) + + val firstAttempt = ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS) + assertEquals(1, firstAttempt) + val retryAttempt = ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS) + assertEquals(2, retryAttempt) + + ShadowLocalSocket.proofAvailable.set(true) + shadowOf(Looper.getMainLooper()).idle() + + val completion = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS) + assertEquals(73 to WaylandCompositor.TEXT_NOT_DELIVERED, completion) + assertEquals(1, ShadowLocalSocket.frameCount.get()) + assertNull(ShadowWaylandCompositor.completions.poll()) + } finally { + input.stop() + } + } + + @Test + fun stopCancelsPendingRetryAndNewGenerationCanSucceed() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + assertTrue(ShadowWaylandCompositor.submit(74)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(1, ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS)) + val negative = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS) + assertEquals(74 to WaylandCompositor.TEXT_UNRESOLVED, negative) + + input.stop() + shadowOf(Looper.getMainLooper()).idle() + + val extra = ShadowLocalSocket.attemptsQueue.poll(600, TimeUnit.MILLISECONDS) + assertNull(extra) + + ShadowLocalSocket.proofAvailable.set(true) + input.start() + shadowOf(Looper.getMainLooper()).idle() + + val completion = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS) + assertEquals(74 to WaylandCompositor.TEXT_NOT_DELIVERED, completion) + assertEquals(1, ShadowLocalSocket.frameCount.get()) + } finally { + input.stop() + } + } + + @Test + fun replacementActivityRecoversPendingTokenAndKeepsItsListener() { + val app = RuntimeEnvironment.getApplication() + val first = SessionTextInput(app) { true } + val replacement = SessionTextInput(app) { true } + try { + first.start() + assertTrue(ShadowWaylandCompositor.submit(80)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(80 to WaylandCompositor.TEXT_UNRESOLVED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + first.stop() + replacement.start() + first.stop() + ShadowLocalSocket.proofAvailable.set(true) + assertEquals(80 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(1, ShadowLocalSocket.frameCount.get()) + ShadowLocalSocket.frameAck.set(1) + assertTrue(ShadowWaylandCompositor.submit(81)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(81 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(2, ShadowLocalSocket.frameCount.get()) + } finally { + replacement.stop() + first.stop() + } + } + + @Test + fun guestRefusalCompletesWithoutProbeAndNextCommitIsDelivered() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + ShadowLocalSocket.frameAck.set(0) + assertTrue(ShadowWaylandCompositor.submit(75)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(75 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertNull(ShadowLocalSocket.attemptsQueue.poll()) + ShadowLocalSocket.frameAck.set(1) + assertTrue(ShadowWaylandCompositor.submit(76)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(76 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertNull(ShadowLocalSocket.attemptsQueue.poll()) + } finally { + input.stop() + } + } + + @Test + fun successfulProbeDoesNotConvertMissingCommitAckToDelivered() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + ShadowLocalSocket.proofAvailable.set(true) + assertTrue(ShadowWaylandCompositor.submit(77)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(77 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(1, ShadowLocalSocket.attemptsQueue.poll()) + assertNull(ShadowWaylandCompositor.completions.poll()) + } finally { + input.stop() + } + } + + @Test + fun nativeReadTimeoutCancelsThenHonorsDeliveredAck() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + ShadowLocalSocket.frameReadError = IOException(Os.strerror(OsConstants.EAGAIN)) + ShadowLocalSocket.frameAck.set(1) + assertTrue(ShadowWaylandCompositor.submit(82)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(82 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(1, ShadowLocalSocket.shutdowns.get()) + assertNull(ShadowLocalSocket.attemptsQueue.poll()) + } finally { + input.stop() + } + } + + @Test + fun brokenSocketUsesRecoveryAfterFinalAckReadAlsoFails() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + ShadowLocalSocket.frameReadError = IOException("Connection reset by peer") + ShadowLocalSocket.finalFrameReadError = IOException("Socket closed") + ShadowLocalSocket.proofAvailable.set(true) + assertTrue(ShadowWaylandCompositor.submit(83)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(83 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(1, ShadowLocalSocket.shutdowns.get()) + assertEquals(1, ShadowLocalSocket.attemptsQueue.poll()) + } finally { + input.stop() + } + } + + @Implements(LocalSocket::class) + class ShadowLocalSocket { + private val written = ByteArrayOutputStream() + private var connected = false + + @Implementation + fun connect(address: LocalSocketAddress) { connected = true } + + @Implementation + fun setSoTimeout(timeout: Int) { + if (!connected) throw IOException("socket not created") + } + + @Implementation + fun getOutputStream(): OutputStream = object : OutputStream() { + override fun write(b: Int) { written.write(b) } + override fun write(b: ByteArray, off: Int, len: Int) { written.write(b, off, len) } + } + + @Implementation + fun getInputStream(): InputStream { + val bytes = written.toByteArray() + val isProbe = bytes.size == 4 && bytes.all { it == 0.toByte() } + return if (isProbe) { + probeCount.incrementAndGet() + val allowProof = proofAvailable.get() + attemptsQueue.offer(probeCount.get()) + ByteArrayInputStream(byteArrayOf(if (allowProof) 0 else 42)) + } else { + frameCount.incrementAndGet() + object : InputStream() { + private var attempts = 0 + override fun read(): Int { + val error = if (attempts++ == 0) frameReadError else finalFrameReadError + if (error != null) throw error + return frameAck.get() + } + } + } + } + + @Implementation + fun close() {} + + @Implementation + fun shutdownOutput() { shutdowns.incrementAndGet() } + + companion object { + private val probeCount = AtomicInteger(0) + val attemptsQueue = LinkedBlockingQueue() + val frameCount = AtomicInteger(0) + val frameAck = AtomicInteger(42) + val shutdowns = AtomicInteger(0) + @Volatile var frameReadError: IOException? = null + @Volatile var finalFrameReadError: IOException? = null + val proofAvailable = java.util.concurrent.atomic.AtomicBoolean(false) + + fun reset() { + probeCount.set(0) + attemptsQueue.clear() + frameCount.set(0) + frameAck.set(42) + shutdowns.set(0) + frameReadError = null + finalFrameReadError = null + proofAvailable.set(false) + } + } + } + + @Implements(WaylandCompositor::class, isInAndroidSdk = false) + class ShadowWaylandCompositor { + companion object { + val completions = LinkedBlockingQueue>() + @Volatile private var listener: WaylandCompositor.TextInputFallbackListener? = null + + fun reset() { + completions.clear() + listener = null + } + + fun submit(token: Int): Boolean = listener!!.onTextInputFallback("abc", token) + + @Implementation + @JvmStatic + fun __staticInitializer__() {} + + @Implementation + @JvmStatic + fun completeTextInputFallback(token: Int, result: Int) { + completions.offer(token to result) + } + + @Implementation + @JvmStatic + fun setTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?) { + listener = l + } + + @Implementation + @JvmStatic + fun isTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?): Boolean = + listener != null && listener === l + + @Implementation + @JvmStatic + fun clearTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?) { + if (listener === l) listener = null + } + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/ElfSeccompPatchTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/ElfSeccompPatchTest.kt index 386017d154..2863c8ffb1 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/ElfSeccompPatchTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/ElfSeccompPatchTest.kt @@ -44,6 +44,40 @@ class ElfSeccompPatchTest { } } + @Test + fun terminalRequestsUseTheOnesAndroidAllowsOnAPseudoTerminal() { + // glibc 2.43's tcsetattr: TCSETS2 into x0, TCGETS2 into x1, with an unrelated instruction between + val data = elfWith( + 0xd28a8560.toInt(), 0x910123e2.toInt(), 0xf2a80580.toInt(), + 0xd28a8541.toInt(), 0x93407ea0.toInt(), 0xf2b00581.toInt(), + 0x528a85a3.toInt(), 0x72a80583.toInt(), + ) + assertEquals(3, ElfSeccompPatch.patch(data)) + val b = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN) + val nop = 0xd503201f.toInt() + assertEquals(0xd28a8040.toInt(), b.getInt(0x100)) // mov x0, #0x5402 (TCSETS) + assertEquals(nop, b.getInt(0x108)) + assertEquals(0xd28a8021.toInt(), b.getInt(0x10c)) // mov x1, #0x5401 (TCGETS) + assertEquals(nop, b.getInt(0x114)) + assertEquals(0x528a8083.toInt(), b.getInt(0x118)) // mov w3, #0x5404 (TCSETSF) + assertEquals(nop, b.getInt(0x11c)) + assertEquals(0, ElfSeccompPatch.patch(data)) + } + + @Test + fun aLookalikeConstantIsLeftAlone() { + // 0x542a with another high half, and one whose high half goes to another register + val data = elfWith(0xd28a8541.toInt(), 0xf2a00021.toInt(), 0xd28a8541.toInt(), 0xf2b00582.toInt()) + assertEquals(0, ElfSeccompPatch.patch(data)) + } + + @Test + fun aSiteWhoseRegisterIsReadBeforeTheHighHalfIsLeftAlone() { + // movz x1, #0x542a; add x2, x1, #1; movk x1, #0x802c, lsl #16; movk x2, #0x402c, lsl #16 + val data = elfWith(0xd28a8541.toInt(), 0x91000422.toInt(), 0xf2b00581.toInt(), 0xf2a80582.toInt()) + assertEquals(0, ElfSeccompPatch.patch(data)) + } + @Test fun otherSystemCallsAreLeftAlone() { val svc = 0xd4000001.toInt() diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt new file mode 100644 index 0000000000..f771031b4c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt @@ -0,0 +1,117 @@ +package com.droiddeck.launcher.runtime + +import java.io.File +import java.nio.file.Files +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class FrameAcquireWorkerProbeTest { + @Test fun requiresExactSteamScriptInTheAppIssuedGuestRoot() { + val dir = Files.createTempDirectory("worker-probe-script").toFile().canonicalFile + try { + val root = File(dir, "root").apply { mkdir() } + val configured = File(dir, "configured") + Files.createSymbolicLink(configured.toPath(), root.toPath()) + val untrustedAlias = File(dir, "other-alias") + Files.createSymbolicLink(untrustedAlias.toPath(), root.toPath()) + val script = "/usr/local/bin/droiddeck-session" + val expected = File(root.path + script).apply { parentFile!!.mkdirs(); writeText("#!/bin/bash\n") } + val otherRoot = File(dir, "sibling") + File(otherRoot.path + script).apply { parentFile!!.mkdirs(); writeText("#!/bin/bash\n") } + val otherScript = File(expected.parentFile, "other-script").apply { writeText("#!/bin/bash\n") } + + val args = listOf("gamescope", "--backend", "wayland", "--expose-wayland", "-f", + "-W", "1280", "-H", "720", "-w", "1280", "-h", "720", "-r", "60", + "-e", "--xwayland-count", "2", "--default-touch-mode", "4", "--hdr-enabled", + "--", script, "steam") + fun valid(argv: List) = FrameAcquireWorkerProbe.exactGamescopeArgs(argv) { + FrameAcquireWorkerProbe.exactSteamScript(it, root, configured) + } + fun child(path: String) = args.dropLast(2) + listOf(path, "steam") + + assertTrue(valid(args)) + assertTrue(valid(args.toMutableList().also { it[0] = "/usr/local/bin/gamescope" })) + assertFalse(valid(args.toMutableList().also { it[0] = "/opt/droiddeck-agent/bin/gamescope" })) + assertTrue(valid(child(root.path + script))) + assertTrue(valid(child(configured.path + script))) + for (path in listOf(otherRoot.path + script, untrustedAlias.path + script, + root.path + "/usr/local/bin/./droiddeck-session", root.path + "/../sibling" + script, + otherScript.path, "droiddeck-session")) { + assertFalse(valid(child(path))) + } + for (bad in listOf(listOf("gamescope", "--version"), args + "", + args + "steam://open/library", args.dropLast(1) + "desktop", + args.take(5) + "--unknown-flag" + args.drop(5), + args.take(5) + listOf("-W", "64") + args.drop(5))) { + assertFalse(valid(bad)) + } + + assertTrue(expected.delete()) + Files.createSymbolicLink(expected.toPath(), otherScript.toPath()) + assertFalse(valid(args)) + assertFalse(valid(child(configured.path + script))) + } finally { + // Don't follow the intentionally broken/foreign symlinks in this fixture. + Files.walk(dir.toPath()).use { paths -> + paths.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) } + } + } + } + @Test fun warmSteamAndExactlyExpectedFirstPartyColdLaunchOnly() { + val probe = FrameAcquireWorkerProbe + val script = "/usr/local/bin/droiddeck-session" + val args = listOf("gamescope", "--backend", "wayland", "--expose-wayland", "-f", + "-W", "1280", "-H", "720", "-w", "1280", "-h", "720", "--", script, "steam") + val url = com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl("3902570") + fun valid(actual: List, expected: String?) = probe.exactGamescopeArgs(actual, expected) { it == script } + + assertTrue(probe.permittedLaunch(null, false)) + assertFalse(probe.permittedLaunch(null, true)) + assertTrue(probe.permittedLaunch(url, true)) + assertFalse(probe.permittedLaunch(url, false)) + assertTrue(valid(args, null)) + assertTrue(valid(args + url, url)) + assertFalse(valid(args + url, null)) + assertFalse(valid(args, url)) + assertFalse(valid(args + "steam://rungameid/3902571", url)) + assertFalse(valid(args + listOf(url, ""), url)) + assertFalse(valid(args + listOf(url, "--version"), url)) + assertFalse(valid(args + listOf(url, url), url)) + assertFalse(valid(args.dropLast(2) + listOf("/tmp/droiddeck-session", "steam", url), url)) + for (bad in listOf("steam://open/library", "steam://run/3902570", "Steam://rungameid/3902570", + "steam://rungameid/03902570", "$url/", "$url?x=1", "$url#x", "$url%20", + "$url --version", "steam://rungameid/18446744073709551616", "https://example.test/")) { + assertFalse(probe.permittedLaunch(bad, true)) + assertFalse(valid(args + bad, bad)) + } + } + + @Test fun selfStatAndFixedBinderReceiptRejectWrongWorkerAndExtraBytes() { + val probe = FrameAcquireWorkerProbe + val fields = (1..18).joinToString(" ") + fun stat(pid: Int, ticks: String) = "$pid (guest )worker) S $fields $ticks 123\n" + assertTrue(probe.parseSelfStat(stat(400, "125"), 400) == 125L) + for (bad in listOf(stat(401, "125"), stat(400, "0"), stat(400, "-1"), + stat(400, "1x"), stat(400, "9223372036854775808"), "400 (guest)")) { + assertTrue(probe.parseSelfStat(bad, 400) == 0L) + } + val size = probe.RECEIPT_BYTES + assertTrue(probe.validReceipt(400, 400, 125L, size) == 125L) + assertTrue(probe.validReceipt(400, 401, 125L, size) == 0L) + assertTrue(probe.validReceipt(1, 1, 125L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, 0L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, -1L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, 125L, size - 4) == 0L) + assertTrue(probe.validReceipt(400, 400, 125L, size + 4) == 0L) + } + + @Test fun anyCustomOrAgentEnvironmentDisablesTheProductionTicket() { + val probe = FrameAcquireWorkerProbe + assertTrue(probe.validEnvironment(emptyList(), emptyList())) + assertFalse(probe.validEnvironment(listOf("PATH=/opt/droiddeck-agent/bin"), emptyList())) + assertFalse(probe.validEnvironment(emptyList(), listOf("LD_PRELOAD=/tmp/custom.so"))) + assertFalse(probe.validEnvironment(listOf("DD_THOR_WORKER_ACQUIRE_TEST=1"), emptyList())) + } + +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt index 027ed9359b..bb9d5e4671 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt @@ -35,6 +35,37 @@ class LegacyNamesTest { assertEquals("droiddeck", link("etc/bannerlator")) } + @Test fun theEmptyStandInIsEmptiedAndThermalZonesGetTheirOwn() { + write("etc/droiddeck/empty/thermal_zone26/temp", "") + LegacyNames.migrateEtc(root) + assertEquals(emptyList(), File(root, "etc/droiddeck/empty").list()!!.toList()) + assertTrue(File(root, LegacyNames.NO_THERMAL).isDirectory) + } + + @Test fun clearingTheEmptyStandInRemovesLinksWithoutTouchingWhatTheyPointAt() { + write("home/keep/file", "kept") + val links = File(root, "etc/droiddeck/empty").apply { mkdirs() } + val made = runCatching { + Files.createSymbolicLink(File(links, "dir").toPath(), File(root, "home/keep").toPath()) + Files.createSymbolicLink(File(links, "dangling").toPath(), File(root, "missing").toPath()) + }.isSuccess + org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made) + LegacyNames.migrateEtc(root) + assertEquals(emptyList(), links.list()!!.toList()) + assertEquals("kept", File(root, "home/keep/file").readText()) + } + + @Test fun aLinkInPlaceOfTheEmptyStandInIsReplacedWithoutTouchingItsTarget() { + write("home/keep/file", "kept") + val empty = File(root, "etc/droiddeck/empty").also { it.parentFile!!.mkdirs() } + val made = runCatching { Files.createSymbolicLink(empty.toPath(), File(root, "home/keep").toPath()) }.isSuccess + org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made) + LegacyNames.migrateEtc(root) + assertFalse(Files.isSymbolicLink(empty.toPath())) + assertEquals(emptyList(), empty.list()!!.toList()) + assertEquals("kept", File(root, "home/keep/file").readText()) + } + @Test fun aFreshRuntimeGetsNoOldNames() { write("usr/local/bin/droiddeck-session", "new") LegacyNames.migrateRootfs(root) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt index d8ea5ee185..563b09dd36 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt @@ -12,6 +12,14 @@ class NativeGuestTest { File(it, "usr/lib/ld-linux-aarch64.so.1").writeText("") } + @Test + fun aRuntimeStillToBeInstalledRunsTheNextSessionNatively() { + val empty = Files.createTempDirectory("native-root").toFile() + assertTrue(NativeGuest.willRun(empty, installed = false)) + assertEquals(false, NativeGuest.willRun(empty, installed = true)) + assertTrue(NativeGuest.willRun(rootWithLoader(), installed = true)) + } + @Test fun theSeccompSwitchNamesAHelperAndItsArgumentsInTheRootfs() { val root = Files.createTempDirectory("rootfs").toFile() diff --git a/app/src/test/java/com/droiddeck/launcher/session/BottomDesktopInputTest.kt b/app/src/test/java/com/droiddeck/launcher/session/BottomDesktopInputTest.kt new file mode 100644 index 0000000000..f5ceb5b623 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/BottomDesktopInputTest.kt @@ -0,0 +1,94 @@ +package com.droiddeck.launcher.session + +import android.os.Handler +import android.os.Looper +import android.os.Messenger +import android.view.KeyEvent +import android.view.inputmethod.EditorInfo +import com.droiddeck.launcher.input.KeyboardHost +import com.droiddeck.launcher.wayland.BottomDesktopCompositorService +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = android.app.Application::class) +class BottomDesktopInputTest { + + private data class Sent(val what: Int, val arg1: Int, val arg2: Int, val text: String?) + + private val sent = ArrayList() + private val key = BottomDesktopCompositorService.MSG_KEY + private val text = BottomDesktopCompositorService.MSG_TEXT + private val textKey = BottomDesktopCompositorService.KEY_TEXT + + private lateinit var desktop: BottomDesktop + private var original: Messenger? = null + + @Before + fun setUp() { + desktop = BottomDesktop + original = ReflectionHelpers.getField(desktop, "service") + sent.clear() + val recorder = Handler(Looper.getMainLooper(), Handler.Callback { msg -> + sent.add(Sent(msg.what, msg.arg1, msg.arg2, msg.data?.getString(textKey))) + true + }) + ReflectionHelpers.setField(desktop, "service", Messenger(recorder)) + } + + @After + fun tearDown() { + shadowOf(Looper.getMainLooper()).idle() + ReflectionHelpers.setField(desktop, "service", original) + } + + @Test + fun pureControlBatchSendsOneDownAndOneUpPerChar() { + BottomDesktop.sendText("\r\n\b\u007f\t") + shadowOf(Looper.getMainLooper()).idle() + assertEquals( + press(28) + press(28) + press(14) + press(111) + press(15), + sent + ) + assertTrue(sent.none { it.what == text }) + } + + @Test + fun ordinaryTextIncludingSupplementaryAndNewlineIsOneTextMessage() { + val value = "中文😀\nline" + BottomDesktop.sendText(value) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(listOf(Sent(text, 0, 0, value)), sent) + } + + @Test + fun keyboardHostOrderMatchesImeEditingSequence() { + val host = KeyboardHost(RuntimeEnvironment.getApplication(), { true }, { BottomDesktop.sendText(it) }) + ReflectionHelpers.setField(host, "shown", true) + val connection = host.onCreateInputConnection(EditorInfo())!! + connection.commitText("中文", 1) + connection.performEditorAction(EditorInfo.IME_ACTION_NONE) + connection.deleteSurroundingText(1, 0) + connection.deleteSurroundingText(0, 1) + assertTrue(connection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB))) + assertTrue(connection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_TAB))) + shadowOf(Looper.getMainLooper()).idle() + assertEquals( + listOf(Sent(text, 0, 0, "中文")) + press(28) + press(14) + press(111) + press(15), + sent + ) + assertEquals(1, sent.count { it.what == key && it.arg1 == 15 && it.arg2 == 1 }) + assertEquals(1, sent.count { it.what == key && it.arg1 == 15 && it.arg2 == 0 }) + } + + private fun press(evdev: Int) = listOf(Sent(key, evdev, 1, null), Sent(key, evdev, 0, null)) +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt index 99bd6ef90e..d0e3c22361 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt @@ -77,6 +77,16 @@ class ComponentsBionicFexTest { assertEquals("fex", ComponentsManager.assetComp("FexCore-Linux", "FEXCore-2611.1-linux.wcp")) } + @Test fun originalXboxFexIsListedButNeverAnAutomaticUpdate() { + assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_XBOX, "FEXCore-2611.1-xbox-bionic.wcp")) + fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "fex", release, "", 1L, "sha256:00") + val items = listOf(item("FEXCore-2611.1-bionic.wcp", ComponentsManager.DD_BIONIC), + item("FEXCore-2611.1-xbox-bionic.wcp", ComponentsManager.DD_XBOX), item("FEXCore-2611.1-PPA-bionic.wcp", ComponentsManager.DD_BIONIC)) + val line = ComponentUpdates.fexLine(proton(bionicTool)) + assertEquals("FEXCore-2611.1-bionic.wcp", ComponentUpdates.pick(items, line, emptySet())?.file) + assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-xbox-bionic.wcp")) + } + @Test fun aGameFexChoiceKeepsItsTwinInUseWhileTheOtherFlavorIsInstalled() { val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp"))) assertEquals(setOf("FEXCore-2611.1-linux.wcp"), ComponentsManager.packagesInUse(state, listOf(proton(ownTool)))) diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt index 3765997350..f48d51b1ca 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt @@ -202,11 +202,19 @@ class GameEnvironmentStoreTest { assertEquals("false", published.shared["MESA_SHADER_CACHE_DISABLE"]) assertFalse(published.shared.containsKey("VKD3D_FEATURE_LEVEL")) assertFalse(published.shared.containsKey("VKD3D_SHADER_MODEL")) - assertEquals(config.games, published.games) + assertEquals(config.games + GameEnvironment.knownGames, published.games) assertEquals(config.shared["LITERAL"], published.shared["LITERAL"]) assertEquals("", published.shared["EMPTY"]) } + @Test fun aKnownGamesFixReachesTheGuestWithoutBeingSavedAsTheUsersSetting() { + GameEnvironmentStore.save(context, GameEnvironment.Config()) + assertEquals(emptyMap>(), GameEnvironmentStore.read(context).games) + val published = GameEnvironmentStore.decode(JSONObject(guest.readText())) + assertEquals(GameEnvironment.knownGames, published.games) + assertEquals("0", published.entries("12100")["FEX_X87REDUCEDPRECISION"]) + } + @Test fun publishingPreservesExplicitSharedGraphicsCapabilities() { val config = GameEnvironment.Config(shared = mapOf( "VKD3D_FEATURE_LEVEL" to "12_1", "VKD3D_SHADER_MODEL" to "6_6", @@ -266,7 +274,7 @@ class GameEnvironmentStoreTest { assertEquals(original.entries("43"), saved.entries("43")) assertEquals("PERFORMANCE_TSO", SessionPrefs.fexPreset(context)) val published = GameEnvironmentStore.decode(JSONObject(guest.readText())) - assertEquals(saved.games, published.games) + assertEquals(saved.games + GameEnvironment.knownGames, published.games) assertEquals("0", published.shared["FEX_HALFBARRIERTSOENABLED"]) assertEquals("1", published.entries("42")["FEX_HALFBARRIERTSOENABLED"]) } diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt index a6b50eb1cc..c34cf0c854 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt @@ -114,6 +114,19 @@ class GameStorageTest { assertFalse(GameStorage.disconnected(app)) } + @Test fun aRawCardPathTheProcessCannotUseFallsBackToItsStoragePath() { + val usable = setOf("/storage/A042-9B16/Games") + assertEquals("/storage/A042-9B16/Games", GameStorage.reachable("/mnt/media_rw/A042-9B16/Games") { it.path in usable }) + } + + @Test fun aUsableRawPathAndOtherPathsAreKept() { + assertEquals("/mnt/media_rw/A042-9B16/Games", GameStorage.reachable("/mnt/media_rw/A042-9B16/Games") { true }) + assertEquals("/mnt/media_rw/0000-0000/Games", GameStorage.reachable("/mnt/media_rw/0000-0000/Games") { false }) + assertEquals("/storage/A042-9B16/Games", GameStorage.reachable("/storage/A042-9B16/Games") { false }) + val folder = tmp.newFolder("library").path + assertEquals(folder, GameStorage.reachable(folder) { false }) + } + @Test fun onlyAVfatMountCountsAsFat32() { val mounts = """ /dev/fuse /storage/emulated fuse rw 0 0 diff --git a/app/src/test/java/com/droiddeck/launcher/session/OrientationTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OrientationTest.kt index 1801ce756c..377e0a8790 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/OrientationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/OrientationTest.kt @@ -80,6 +80,24 @@ class OrientationTest { assertFalse(SessionPrefs.portrait(landscape)) } + @Test fun modeOrientationControlsWindowFollowAndPortraitResolution() { + SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.windowOrientation(context, true, 700, SessionService.MODE_STEAM)) + + SessionPrefs.setOrientation(context, "steam", ActivityInfo.SCREEN_ORIENTATION_USER) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, true, 700, SessionService.MODE_STEAM)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, false, 400, SessionService.MODE_RUN)) + + val config = android.content.res.Configuration(context.resources.configuration) + config.orientation = android.content.res.Configuration.ORIENTATION_PORTRAIT + val portrait = context.createConfigurationContext(config) + config.orientation = android.content.res.Configuration.ORIENTATION_LANDSCAPE + val landscape = context.createConfigurationContext(config) + assertTrue(SessionPrefs.portrait(portrait, SessionService.MODE_STEAM)) + assertFalse(SessionPrefs.portrait(landscape, SessionService.MODE_STEAM)) + assertTrue(SessionPrefs.portrait(landscape, SessionService.MODE_DESKTOP)) + } + @Test fun invalidLauncherOrientationFallsBackAndInvalidChoicePreservesPreference() { context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", 999).commit() assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, AppUiPrefs.orientation(context)) @@ -88,4 +106,20 @@ class OrientationTest { assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, AppUiPrefs.orientation(context)) } + @Test fun steamAndDesktopOrientationsAreIndependentAndFallBackToLegacyChoice() { + assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context, "steam")) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context, "desktop")) + + SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) + SessionPrefs.setOrientation(context, "steam", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) + SessionPrefs.setOrientation(context, "desktop", ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) + + assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, "steam")) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_STEAM)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_RUN)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context, "desktop")) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_DESKTOP)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.orientation(context)) + } + } diff --git a/app/src/test/java/com/droiddeck/launcher/session/OutputPacingTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OutputPacingTest.kt index c2d0ca8356..03b7e14f3d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/OutputPacingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/OutputPacingTest.kt @@ -30,4 +30,16 @@ class OutputPacingTest { @Test fun mirroringKeepsTheGlassesRate() { assertEquals(60, SessionPrefs.compositorFpsLimit(60)) } + + @Test fun gameModeOverrideCapsAPanelThatRunsFaster() { + assertEquals(60, SessionPrefs.hostFrameCap(60.000004f, 120.00001f)) + assertEquals(0, SessionPrefs.hostFrameCap(120.00001f, 120.00001f)) + assertEquals(0, SessionPrefs.hostFrameCap(0f, 120f)) + } + + @Test fun hostCapPacesSteamSessionsAndYieldsToLowerLimits() { + assertEquals(60, SessionPrefs.compositorFpsLimit(0, 0, hostCap = 60)) + assertEquals(45, SessionPrefs.compositorFpsLimit(0, 45, hostCap = 60)) + assertEquals(SessionPrefs.PIP_FPS, SessionPrefs.compositorFpsLimit(0, 0, pip = true, hostCap = 60)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt new file mode 100644 index 0000000000..1eed5c83ac --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt @@ -0,0 +1,18 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class PageCacheTrimTest { + private val meminfo = "MemFree: 1048576 kB\nActive(file): 2097152 kB\nInactive(file): 1048576 kB\n" + + @Test fun parsesFreeAndFileLru() = assertEquals(PageCacheTrim.Mem(1048576, 3145728), PageCacheTrim.parse(meminfo)) + @Test fun rejectsMissingFields() = assertNull(PageCacheTrim.parse("MemFree: 1 kB\n")) + @Test fun trimsWhenCacheBuiltUpAndFreeIsLow() = assertTrue(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(2000 * 1024, 2000 * 1024), 1000 * 1024)) + @Test fun skipsSmallBuildUp() = assertFalse(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(2000 * 1024, 1200 * 1024), 1000 * 1024)) + @Test fun skipsWhenPlentyFree() = assertFalse(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(6000 * 1024, 5000 * 1024), 1000 * 1024)) + @Test fun lowFreeAcceptsSmallerBuildUp() = assertTrue(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(500 * 1024, 1200 * 1024), 1000 * 1024)) +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt index f010e97a65..a5c3d057fb 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -20,7 +20,18 @@ class PortraitResolutionTest { app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() } - @Test fun portraitFollowsLandscapeUntilItIsSet() { + @Test fun steamPortraitStartsWithA16By10PictureWithoutChangingLandscapeOrDesktop() { + assertEquals(SessionDisplay.DEFAULT_RESOLUTION, SessionPrefs.resolutionChoice(app, "steam", panel)) + assertEquals(SessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION, SessionPrefs.resolutionStored(app, "steam", panel, true)) + val choice = SessionPrefs.resolutionChoice(app, "steam", panel, true) + assertEquals(1280 to 800, SessionDisplay.resolveChoice(panel, choice, portrait = true)) + assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true)) + SessionPrefs.setResolutionChoice(app, "steam", "900p") + assertEquals(choice, SessionPrefs.resolutionChoice(app, "steam", panel, true)) + } + + @Test fun explicitlyLinkedPortraitKeepsFollowingLandscape() { + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_LANDSCAPE, portrait = true) assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "steam", panel, true)) SessionPrefs.setResolutionChoice(app, "steam", "900p") assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, false)) @@ -45,6 +56,7 @@ class PortraitResolutionTest { @Test fun followingEachOtherNeverLoops() { SessionPrefs.setResolutionChoice(app, "steam", "900p") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_LANDSCAPE, portrait = true) SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, false)) assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, true)) @@ -53,6 +65,7 @@ class PortraitResolutionTest { @Test fun aGeneratedPortraitSizeSurvivesAReload() { SessionPrefs.setResolutionChoice(app, "steam", "2560x1440") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_LANDSCAPE, portrait = true) SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true)) assertEquals("2560x1440", SessionPrefs.resolutionChoice(app, "steam", panel, false)) @@ -89,6 +102,8 @@ class PortraitResolutionTest { @Test fun followScalesKeepLinkedAndFixedChoices() { SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(1.5f)) + assertEquals(1.5f to null, SessionPrefs.followScales(app, "steam", panel)) + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_LANDSCAPE, portrait = true) assertEquals(1.5f to 1.5f, SessionPrefs.followScales(app, "steam", panel)) SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true) SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SecondaryLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SecondaryLibraryTest.kt index a58e075380..47c55f349d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SecondaryLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SecondaryLibraryTest.kt @@ -21,6 +21,24 @@ class SecondaryLibraryTest { assertFalse(SecondaryLibrary.privateRoot(files, content).exists()) } + @Test fun aCardReachedThroughItsOtherPathKeepsItsPrivateDirectories() { + val files = tmp.newFolder("files") + val raw = SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/A042-9B16/Games")).apply { mkdirs() } + assertEquals(raw, SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games"))) + val storage = SecondaryLibrary.privateRoot(files, File("/storage/B2BD-BCFC/Games")).apply { mkdirs() } + assertEquals(storage, SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/B2BD-BCFC/Games"))) + } + + @Test fun aLibraryWithItsOwnPrivateDirectoriesKeepsThem() { + val files = tmp.newFolder("files") + val own = SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")).apply { mkdirs() } + val raw = File(own.parentFile, SecondaryLibrary.privateRoot(tmp.newFolder("other"), File("/mnt/media_rw/A042-9B16/Games")).name) + raw.mkdirs() + assertEquals(own, SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games"))) + assertEquals(raw, SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/A042-9B16/Games"))) + assertFalse(SecondaryLibrary.privateRoot(files, File("/storage/emulated/0/Games")).exists()) + } + @Test fun aWritableAliasIsSelectedAndItsProbeIsRemoved() { val library = tmp.newFolder("shared") val candidate = File(tmp.root, "direct") diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsZeroCopyTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsZeroCopyTest.kt new file mode 100644 index 0000000000..8f34aef2e8 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsZeroCopyTest.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class SessionPrefsZeroCopyTest { + private val app get() = RuntimeEnvironment.getApplication() + + @Test fun standaloneGamesUseTheSteamPresentationSetting() { + SessionPrefs.setZeroCopy(app, SessionService.MODE_STEAM, false) + + assertFalse(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN)) + assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_DESKTOP)) + + SessionPrefs.setZeroCopy(app, SessionService.MODE_RUN, true) + + assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_STEAM)) + assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN)) + } + + @Test fun aRawRunKeyCannotDisagreeWithTheSteamSetting() { + app.getSharedPreferences("session", Context.MODE_PRIVATE) + .edit().putBoolean("zeroCopy.run", false).commit() + SessionPrefs.setZeroCopy(app, SessionService.MODE_STEAM, true) + + assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt index 3d0e420001..023aa85553 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt @@ -72,6 +72,33 @@ class SessionScalingPrefsTest { assertEquals("1024x768", SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080)) } + @Test fun picturePositionDefaultsToTopInPortraitAndCenterInLandscape() { + val ctx = RuntimeEnvironment.getApplication() + assertEquals("top", SessionPrefs.picturePosition(ctx, portrait = true)) + assertEquals("center", SessionPrefs.picturePosition(ctx, portrait = false)) + } + + @Test fun eachOrientationKeepsItsOwnPicturePosition() { + val ctx = RuntimeEnvironment.getApplication() + SessionPrefs.setPicturePosition(ctx, portrait = true, position = "bottom") + assertEquals("center", SessionPrefs.picturePosition(ctx, portrait = false)) + SessionPrefs.setPicturePosition(ctx, portrait = false, position = "right") + assertEquals("bottom", SessionPrefs.picturePosition(ctx, portrait = true)) + assertEquals("right", SessionPrefs.picturePosition(ctx, portrait = false)) + } + + @Test fun legacyPicturePositionIsPreservedUntilEachOrientationIsChanged() { + val ctx = RuntimeEnvironment.getApplication() + ctx.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putString("picturePosition", "left").commit() + assertEquals("left", SessionPrefs.picturePosition(ctx, portrait = true)) + assertEquals("left", SessionPrefs.picturePosition(ctx, portrait = false)) + SessionPrefs.setPicturePosition(ctx, portrait = true, position = "top") + assertEquals("top", SessionPrefs.picturePosition(ctx, portrait = true)) + assertEquals("left", SessionPrefs.picturePosition(ctx, portrait = false)) + assertTrue(SettingsReset.isSessionSetting("picturePosition.portrait")) + assertTrue(SettingsReset.isSessionSetting("picturePosition.landscape")) + } + @Test fun legacySavedFiltersStillResolveToAVisibleEquivalentChoice() { val context = RuntimeEnvironment.getApplication() val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt index 5e16af444f..ef987bb0ed 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.session +import com.droiddeck.launcher.ui.MainMenuLayout import com.droiddeck.launcher.ui.QamFit import com.droiddeck.launcher.ui.QamLayout import org.junit.Assert.assertEquals @@ -51,6 +52,7 @@ class SteamQamTest { val program = "const g = {};\n" + steps.joinToString("\n") { step -> when (step) { is Triple<*, *, *> -> SteamQam.leaseScript(step.first as Boolean, step.second as Long, step.third as Float) + is SplitStep -> SteamQam.leaseScript(true, step.owner, 0.5f, step.split) is Pair<*, *> -> if (step.second == EXPIRE) "g.__ddQamUntil = Date.now() - 1;" else SteamQam.leaseScript(step.first as Boolean, step.second as Long) else -> error("unknown step $step") } @@ -85,14 +87,17 @@ class SteamQamTest { @Test fun theQuickAccessButtonTogglesTheTopScreenAndTheWideLayoutFollows() { val script = SteamQam.script(true) - assertTrue(script.contains("const ours = () => held() && m.m_eOpenSideMenu === QAM && !g.__ddQamTop;")) + assertTrue(script.contains("const ours = () => held() && !g.__ddQamTop && (m.m_eOpenSideMenu === QAM || (probing() && m.m_eOpenSideMenu === MAIN));")) assertTrue(script.contains("if (press !== g.__ddQamPress) {")) assertTrue(QamLayout.contentScript(true).contains("max-width: none !important")) assertFalse(QamLayout.contentScript(false).contains("max-width: none")) + // The empty in-game button-hint footer is hidden only while the menu is parked, in every layout. + assertTrue(QamLayout.contentScript(false, parked = true).contains("#Footer { display: none !important; }")) + assertFalse(QamLayout.contentScript(false).contains("#Footer")) } @Test fun theMenuIsLaidOutAtThePanelsShapeOnlyWhileHeld() { - assertTrue(SteamQam.script(true, 1.5f, owner = 3).contains("g.__ddQamOwner = 3; g.__ddQamUntil = Date.now() + ${SteamQam.LEASE_MS}; g.__ddQamAspect = 1.5; }")) + assertTrue(SteamQam.script(true, 1.5f, owner = 3).contains("g.__ddQamOwner = 3; g.__ddQamUntil = Date.now() + ${SteamQam.LEASE_MS}; g.__ddQamAspect = 1.5; g.__ddQamSplit = false; }")) assertFalse(SteamQam.script(true).contains("g.__ddQamAspect =")) assertFalse(SteamQam.script(false, 1.5f).contains("g.__ddQamAspect =")) } @@ -114,8 +119,8 @@ class SteamQamTest { @Test fun whileHeldTheMenuStaysOffTheTopScreenAndOutOfTheGamesWay() { val script = SteamQam.script(true) assertTrue(script.contains("return without >= 2 ? v : 1;")) - assertTrue(script.contains("if (w > 0 && ours()) { x = popup.m_popup.innerWidth + 64; w = width(h) || w; }")) - assertTrue(script.contains("nav.m_LastActiveNavTree?.m_ID?.startsWith(\"QuickAccess\")")) + assertTrue(script.contains("if (w > 0 && ours() && isQam(v)) { x = parkX(); [w, h] = size(w, h); }")) + assertTrue(script.contains("/^(QuickAccess|MainMenu)/.test(nav.m_LastActiveNavTree?.m_ID ?? \"\")")) assertTrue(script.contains("if (m.m_eOpenSideMenu === QAM) m.CloseSideMenus();")) } @@ -134,8 +139,9 @@ class SteamQamTest { assertEquals(0f, QamLayout.fit(1280f, 832f, 1280f, 640f, 1).second, 0.001f) } - @Test fun theLayoutButtonCyclesFullLeftCenterRight() { - assertEquals(listOf(QamFit.LEFT, QamFit.CENTER, QamFit.RIGHT, QamFit.FULL), QamFit.entries.map { it.next }) + @Test fun theLayoutButtonCyclesFullLeftCenterRightSplit() { + assertEquals(listOf(QamFit.LEFT, QamFit.CENTER, QamFit.RIGHT, QamFit.SPLIT, QamFit.FULL), QamFit.entries.map { it.next }) + assertEquals(QamFit.SPLIT, QamFit.from("split")) assertEquals(QamFit.FULL, QamFit.from(null)) assertEquals(QamFit.RIGHT, QamFit.from("right")) assertEquals(QamFit.FULL, QamFit.from("sideways")) @@ -147,6 +153,61 @@ class SteamQamTest { assertEquals(0f, left, 0.001f) } + @Test fun findsTheMainMenuPageBesideQuickAccess() { + val json = """[ + {"title":"MainMenu_uid2","webSocketDebuggerUrl":"ws://127.0.0.1:8080/devtools/page/M41N"}, + {"title":"QuickAccess_uid2","webSocketDebuggerUrl":"ws://127.0.0.1:8080/devtools/page/0F3A-b9"} + ]""" + assertEquals(SteamQam.Target(4321, "/devtools/page/0F3A-b9", "/devtools/page/M41N"), SteamQam.parseTarget(4321, json)) + assertNull(SteamQam.parseTarget(1, """[{"title":"MainMenu_uid2","webSocketDebuggerUrl":"ws://127.0.0.1:1/devtools/page/A"}]""")) + } + + @Test fun theSplitLayoutIsPartOfTheLease() { + assertEquals("true", runLease(listOf(SplitStep(1L, true)), "g.__ddQamSplit")) + // A rejected hold from an older panel leaves the newer panel's split choice alone. + assertEquals("true", runLease(listOf(SplitStep(2L, true), SplitStep(1L, false)), "g.__ddQamSplit")) + assertTrue(SteamQam.script(true, 0.5f, owner = 3, split = true).contains("g.__ddQamSplit = true; }")) + } + + @Test fun onlyTheQuickAccessViewIsParked() { + val script = SteamQam.script(true, 1.3f, owner = 3) + // Store and other web pages live in the header's view, which keeps the bounds Steam gives it. + assertTrue(script.contains("const isQam = (v) => !v.__ddMain && v !== headerView() &&")) + assertTrue(script.contains("if (on && m.m_eOpenSideMenu === QAM && !v.__ddMain && v !== headerView()) {")) + assertTrue(script.contains("if (!isQam(v)) {")) + // A parked menu leaves the Store page unfrosted. + assertTrue(script.contains("inst.__ddQamGlass.call(this, ours() ? 0 : e)")) + } + + @Test fun mainMenuDiscoveryRecoversAfterFailedProbes() { + val script = SteamQam.script(true, 1.3f, owner = 3, split = true) + assertTrue(script.contains("if (split() !== !!g.__ddQamSplitOn) { g.__ddQamSplitOn = split(); if (split()) g.__ddMainProbes = 0; }")) + assertTrue(script.contains("if ((g.__ddMainProbes || 0) >= 3 && Date.now() - (g.__ddMainProbeLast || 0) > 30000) g.__ddMainProbes = 0;")) + } + + @Test fun theMainMenuStaysInPlaceOnlyWhileParked() { + val script = SteamQam.script(true, 0.5f, owner = 3, split = true) + assertTrue(script.contains("transform: none !important")) + assertTrue(script.contains("mainStyle(!!mv && mainParked() && !probing());")) + // Steam sizing the main menu for the top screen drops the parked style at once. + assertTrue(script.contains("if (v.__ddMain && w > 0) mainStyle(false);")) + } + + @Test fun theScriptsParse() { + val node = runCatching { ProcessBuilder("node", "--version").start().waitFor() == 0 }.getOrDefault(false) + org.junit.Assume.assumeTrue("node is not installed", node) + val scripts = listOf(SteamQam.script(true, 0.5f, 3, split = true), SteamQam.script(false, owner = 3), + QamLayout.contentScript(true), MainMenuLayout.CONTENT_SCRIPT) + val program = scripts.joinToString(";") { "new Function(" + org.json.JSONObject.quote(it) + ")" } + // Passed on stdin: Windows argument quoting would mangle the quotes in the scripts. + val p = ProcessBuilder("node").redirectErrorStream(true).start() + p.outputStream.use { it.write(program.toByteArray()) } + val out = p.inputStream.bufferedReader().readText() + assertEquals(out, 0, p.waitFor()) + } + + private data class SplitStep(val owner: Long, val split: Boolean) + private companion object { /** A lease step that lets the current lease run out. */ const val EXPIRE = -1L diff --git a/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt new file mode 100644 index 0000000000..cc6b4c2d07 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt @@ -0,0 +1,71 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.github.luben.zstd.ZstdOutputStream +import org.apache.commons.compress.archivers.tar.TarArchiveEntry +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.BufferedOutputStream +import java.io.File +import java.io.FileOutputStream + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class XboxBackCompatAssignTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + File(context.filesDir, "components").deleteRecursively() + LinuxRuntime.rootDir(context).deleteRecursively() + ComponentsManager.importPackage(context, wcp("a.src", "A"), "dxvk-a.wcp") + ComponentsManager.importPackage(context, wcp("b.src", "B"), "dxvk-b.wcp") + } + + @Test fun aChoiceMadeDuringTheDownloadIsKept() { + ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk-b.wcp") + var marked = false + val result = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-a.wcp", "unused", expected = null) { marked = true } + assertEquals(ComponentsManager.Assigned.CHANGED, result) + assertEquals("dxvk-b.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + assertFalse(marked) + } + + @Test fun anUnchangedComponentIsSetAndMarked() { + var marked = false + val result = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-a.wcp", "unused", expected = null) { marked = true } + assertEquals(ComponentsManager.Assigned.SET, result) + assertEquals("dxvk-a.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + assertTrue(marked) + val newer = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-b.wcp", "unused", expected = "dxvk-a.wcp") + assertEquals(ComponentsManager.Assigned.SET, newer) + assertEquals("dxvk-b.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + } + + private fun wcp(fileName: String, version: String): File { + val out = File(context.cacheDir, fileName) + val profile = JSONObject().put("type", "DXVK-Linux").put("versionName", version).put("description", "DXVK $version") + .toString().toByteArray(Charsets.UTF_8) + val dll = "dxvk-dll-$version".toByteArray(Charsets.UTF_8) + TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(out)))).use { tar -> + tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX) + tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() }) + tar.write(profile) + tar.closeArchiveEntry() + tar.putArchiveEntry(TarArchiveEntry("files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply { size = dll.size.toLong() }) + tar.write(dll) + tar.closeArchiveEntry() + } + return out + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt new file mode 100644 index 0000000000..b52a2cc085 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt @@ -0,0 +1,33 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.gpu.GpuInfo +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class XboxBackCompatComponentsTest { + private val fex = "FEXCore-2611.1-xbox-bionic.wcp" + + @Test fun aComponentIsSetOnceAndNeverOverAPlayersChoice() { + assertEquals(fex, XboxBackCompatComponents.decide(current = null, assigned = null, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = "FEXCore-2611.1-bionic.wcp", assigned = null, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = null, assigned = fex, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = fex, assigned = fex, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = "DD-FEXCore-2611+76-nightly.wcp", assigned = fex, wanted = "FEXCore-2612-xbox-bionic.wcp")) + } + + @Test fun aComponentSetHereFollowsANewerBuild() { + assertEquals("FEXCore-2612-xbox-bionic.wcp", XboxBackCompatComponents.decide(current = fex, assigned = fex, wanted = "FEXCore-2612-xbox-bionic.wcp")) + } + + @Test fun eachComponentComesFromTheReleaseThatListsIt() { + val wanted = XboxBackCompatComponents.wanted(GpuInfo.Family.A7XX) + assertEquals(listOf("fex", "vkd3d", "dxvk"), wanted.map { it.comp }) + assertEquals(ComponentsManager.DD_XBOX, wanted[0].release) + assertEquals("vkd3d-proton-arm64ec-3.1-xbox-linux.wcp" to "Vkd3d-proton-Linux", wanted[1].file to wanted[1].release) + assertEquals("dxvk-gplasync-3.2-1-linux.wcp" to "Dxvk-gplasync-Linux", wanted[2].file to wanted[2].release) + for (w in wanted) assertEquals(w.comp, ComponentsManager.assetComp(w.release, w.file)) + assertEquals("dxvk-gplasync-3.2-a6xx-1-linux.wcp", XboxBackCompatComponents.wanted(GpuInfo.Family.A6XX)[2].file) + assertEquals("dxvk-gplasync-3.2-1-linux.wcp", XboxBackCompatComponents.wanted(null)[2].file) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrGestureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrGestureTest.kt new file mode 100644 index 0000000000..525de1aefb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrGestureTest.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class XrGestureTest { + private fun hand(x: Float, active: Boolean = true) = + XrHand(Pose(), Pose(Quat.IDENTITY, Vec3(x, 1.2f, -0.3f)), 0f, 0f, 0f, 0f, 0, active) + + @Test + fun holdingTheControllersTogetherFiresAfterTheHold() { + val gesture = XrGesture() + assertFalse(gesture.update(hand(-0.03f), hand(0.03f), 0)) + assertEquals(XrGesture.Phase.ARMING, gesture.phase) + assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS / 2)) + assertEquals(0.5f, gesture.progress, 0.01f) + assertEquals(0f, gesture.midpoint.x, 1e-6f) + assertTrue(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS)) + } + + @Test + fun pullingApartCancels() { + val gesture = XrGesture() + gesture.update(hand(-0.03f), hand(0.03f), 0) + gesture.update(hand(-0.06f), hand(0.06f), 500) + assertEquals(XrGesture.Phase.ARMING, gesture.phase) + gesture.update(hand(-0.08f), hand(0.08f), 600) + assertEquals(XrGesture.Phase.IDLE, gesture.phase) + assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS + 600)) + assertEquals(0f, gesture.progress, 0f) + } + + @Test + fun itDoesNotFireAgainUntilTheControllersPart() { + val gesture = XrGesture() + gesture.update(hand(-0.03f), hand(0.03f), 0) + assertTrue(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS)) + for (t in 1..5) assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS * (t + 1))) + gesture.update(hand(-0.2f), hand(0.2f), 20_000) + gesture.update(hand(-0.03f), hand(0.03f), 21_000) + assertTrue(gesture.update(hand(-0.03f), hand(0.03f), 21_000 + XrGesture.HOLD_MS)) + } + + @Test + fun aLostControllerStopsIt() { + val gesture = XrGesture() + gesture.update(hand(-0.03f), hand(0.03f), 0) + assertFalse(gesture.update(hand(-0.03f), hand(0.03f, active = false), XrGesture.HOLD_MS)) + assertEquals(XrGesture.Phase.IDLE, gesture.phase) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrHostTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrHostTest.kt new file mode 100644 index 0000000000..8a8c50c02c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrHostTest.kt @@ -0,0 +1,84 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class XrHostTest { + private fun buffer(size: Int) = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()) + + @Test + fun readsHandsAtTheNativeOffsets() { + val state = buffer(XrHostLayout.STATE_SIZE) + state.putInt(8, XrHostLayout.FLAG_FOCUSED or XrHostLayout.FLAG_SURFACE_SWAPCHAIN) + state.putLong(16, 42L) + XrHost.writePose(state, XrHostLayout.STATE_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f))) + val right = XrHostLayout.STATE_HANDS + XrHostLayout.HAND_SIZE + XrHost.writePose(state, right + XrHostLayout.HAND_AIM, Pose(Quat.IDENTITY, Vec3(0.2f, 1.2f, -0.3f))) + state.putFloat(right + XrHostLayout.HAND_TRIGGER, 0.75f) + state.putFloat(right + XrHostLayout.HAND_STICK + 4, -0.5f) + state.putInt(right + XrHostLayout.HAND_BUTTONS, XrHostLayout.SECONDARY_CLICK) + state.putInt(right + XrHostLayout.HAND_ACTIVE, 1) + + val frame = XrHost(state, buffer(XrHostLayout.CONTROL_SIZE)).read() + + assertTrue(frame.focused) + assertTrue(frame.surfaces) + assertEquals(42L, frame.frame) + assertEquals(1.6f, frame.head.position.y, 0f) + assertFalse(frame.hands[0].active) + val hand = frame.hands[1] + assertTrue(hand.active) + assertTrue(hand.secondary) + assertEquals(0.75f, hand.trigger, 0f) + assertEquals(-0.5f, hand.stickY, 0f) + assertEquals(Vec3(0.2f, 1.2f, -0.3f), hand.aim.position) + } + + @Test + fun writesControlAtTheNativeOffsets() { + val control = buffer(XrHostLayout.CONTROL_SIZE) + val host = XrHost(buffer(XrHostLayout.STATE_SIZE), control) + val out = XrControlOut().apply { + masks[1] = true + lasers[1] = 0.8f + haptics[0] = XrHaptic(20, 0.5f) + orb = XrControlOut.Orb(Vec3(0f, 1f, -0.5f), 0.04f, 0.25f, 0f) + layers += XrLayerOut(3, Pose(Quat.IDENTITY, Vec3(0f, 1.5f, -1f)), 0.9f, 0.6f, order = 2) + } + host.write(out) + + assertEquals(XrHostLayout.VERSION, control.getInt(0)) + val right = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_SIZE + assertEquals(XrHostLayout.MASK_INPUT, control.getInt(right)) + assertEquals(0.8f, control.getFloat(right + XrHostLayout.HAND_CONTROL_LASER), 0f) + assertEquals(0, control.getInt(XrHostLayout.CONTROL_HANDS)) + val haptic = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_HAPTIC + assertEquals(1L, control.getLong(haptic)) + assertEquals(20_000_000L, control.getLong(haptic + 8)) + assertEquals(1, control.getInt(XrHostLayout.CONTROL_ORB)) + assertEquals(0.25f, control.getFloat(XrHostLayout.CONTROL_ORB + 4), 0f) + val layer = XrHostLayout.CONTROL_LAYERS + assertEquals(3, control.getInt(layer)) + assertEquals(1, control.getInt(layer + 4)) + assertEquals(2, control.getInt(layer + 12)) + assertEquals(-1f, control.getFloat(layer + 16 + 24), 0f) + assertEquals(0.9f, control.getFloat(layer + 48), 0f) + assertEquals(-1, control.getInt(layer + XrHostLayout.LAYER_SIZE)) + } + + @Test + fun aHapticIsSentOnceAndTheNextGetsANewId() { + val control = buffer(XrHostLayout.CONTROL_SIZE) + val host = XrHost(buffer(XrHostLayout.STATE_SIZE), control) + val haptic = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_HAPTIC + host.write(XrControlOut().apply { haptics[0] = XrHaptic(10, 0.3f) }) + host.write(XrControlOut()) + assertEquals(1L, control.getLong(haptic)) + host.write(XrControlOut().apply { haptics[0] = XrHaptic(10, 0.3f) }) + assertEquals(2L, control.getLong(haptic)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrInteractionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrInteractionTest.kt new file mode 100644 index 0000000000..92ee0cdfb3 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrInteractionTest.kt @@ -0,0 +1,246 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class XrInteractionTest { + private val head = Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f)) + + /** A panel 1 m ahead facing the user, 1 m wide and 0.6 m high. */ + private fun panel(kind: XrPanelKind = XrPanelKind.MENU, z: Float = -1f) = + XrPanelState(kind, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, z)), 1f, 0.6f) + + /** A controller at the head's height pointing straight ahead at ([x], [y]) on the panel's plane. */ + private fun aim(x: Float = 0f, y: Float = 0f, trigger: Float = 0f, squeeze: Float = 0f, stickY: Float = 0f, + buttons: Int = 0, active: Boolean = true) = + XrHand(Pose(), Pose(Quat.IDENTITY, Vec3(x, 1.6f + y, 0f)), trigger, squeeze, 0f, stickY, buttons, active) + + private val idle = XrHand.IDLE + + @Test + fun aRayHitsThePanelInItsPixels() { + val panel = panel() + val hit = panel.hit(aim(0.25f, 0.15f).aim) + assertNotNull(hit) + assertEquals(1f, hit!!.distance, 1e-4f) + assertEquals(panel.pixelWidth * 0.75f, panel.pixelX(hit.x), 0.5f) + assertEquals(panel.pixelHeight * 0.25f, panel.pixelY(hit.y), 0.5f) + assertNull(panel.hit(aim(0.7f).aim)) + } + + @Test + fun aPanelBehindTheControllerOrSeenFromBehindIsMissed() { + assertNull(panel(z = 1f).hit(aim().aim)) + val turned = XrPanelState(XrPanelKind.MENU, Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, -1f)), 1f, 0.6f) + assertNull(turned.hit(aim().aim)) + } + + @Test + fun theNearestPanelTakesTheRay() { + val far = panel(z = -2f) + val near = panel(z = -1f) + val out = XrInteraction().update(head, listOf(aim(trigger = 0f), idle), listOf(far, near), 0.014f) + assertTrue(out.cursors.containsKey(near)) + assertFalse(out.cursors.containsKey(far)) + } + + @Test + fun onlyTheControllerPointingAtAPanelIsTakenFromTheGame() { + val panel = panel() + val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true) + val out = XrInteraction().update(head, listOf(away, aim()), listOf(panel), 0.014f) + assertFalse(out.masks[0]) + assertEquals(0f, out.lasers[0], 0f) + assertTrue(out.masks[1]) + assertEquals(1f, out.lasers[1], 1e-4f) + } + + @Test + fun theTriggerPressesMovesAndReleases() { + val panel = panel() + val interaction = XrInteraction() + val down = interaction.update(head, listOf(aim(0f, 0f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue(down.events.single() is XrPointerEvent.Down) + val moved = interaction.update(head, listOf(aim(0.1f, 0f, trigger = 0.5f), idle), listOf(panel), 0.014f) + assertTrue(moved.events.single() is XrPointerEvent.Move) + assertTrue(moved.masks[0]) + val up = interaction.update(head, listOf(aim(0.1f, 0f, trigger = 0.1f), idle), listOf(panel), 0.014f) + val release = up.events.single() as XrPointerEvent.Up + assertEquals(panel.pixelWidth * 0.6f, release.x, 0.5f) + } + + @Test + fun aHeldPressFollowsTheRayOffThePanelAndAlostControllerCancels() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + val off = interaction.update(head, listOf(aim(0.9f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue((off.events.single() as XrPointerEvent.Move).x >= panel.pixelWidth - 0.5f) + assertTrue(off.masks[0]) + val lost = interaction.update(head, listOf(aim(active = false), idle), listOf(panel), 0.014f) + assertTrue(lost.events.single() is XrPointerEvent.Cancel) + } + + @Test + fun theStickScrollsAndBGoesBack() { + val panel = panel() + val interaction = XrInteraction() + val scroll = interaction.update(head, listOf(aim(stickY = 1f), idle), listOf(panel), 0.1f) + assertTrue((scroll.events.single() as XrPointerEvent.Scroll).amount > 0f) + val back = interaction.update(head, listOf(aim(buttons = XrHostLayout.SECONDARY_CLICK), idle), listOf(panel), 0.014f) + assertTrue(back.events.single() is XrPointerEvent.Back) + val held = interaction.update(head, listOf(aim(buttons = XrHostLayout.SECONDARY_CLICK), idle), listOf(panel), 0.014f) + assertTrue(held.events.isEmpty()) + } + + @Test + fun gripCarriesThePanelAndTheStickPushesItAway() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(squeeze = 0.9f), idle), listOf(panel), 0.014f) + interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(0.3f, panel.pose.position.x, 1e-4f) + assertEquals(1.7f, panel.pose.position.y, 1e-4f) + val before = panel.pose.position.z + repeat(10) { interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f, stickY = 1f), idle), listOf(panel), 0.1f) } + assertTrue(panel.pose.position.z < before) + repeat(200) { interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f, stickY = 1f), idle), listOf(panel), 0.1f) } + assertTrue((panel.pose.position - Vec3(0.3f, 1.7f, 0f)).length <= XrUnits.MAX_DISTANCE + 1e-3f) + val dropped = interaction.update(head, listOf(aim(0.3f, 0.1f), idle), listOf(panel), 0.014f) + assertTrue(dropped.events.single() is XrPointerEvent.Moved) + val facingHead = panel.pose.orientation.rotate(Vec3(0f, 0f, 1f)) + val toHead = (head.position - panel.pose.position).let { Vec3(it.x, 0f, it.z).normalized() } + assertEquals(1f, facingHead dot toHead, 1e-3f) + } + + @Test + fun theBottomBarCarriesThePanelButItsButtonIsClicked() { + val panel = panel() + val interaction = XrInteraction() + val barY = -0.3f + XrUnits.BAR_METRES / 2f + val bar = interaction.update(head, listOf(aim(0.1f, barY, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue(bar.events.isEmpty()) + interaction.update(head, listOf(aim(0.2f, barY, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(0.1f, panel.pose.position.x, 1e-4f) + interaction.update(head, listOf(aim(0.2f, barY), idle), listOf(panel), 0.014f) + + val chat = panel(XrPanelKind.PET_CHAT) + val button = XrInteraction().update(head, listOf(aim(-0.48f, barY, trigger = 0.9f), idle), listOf(chat), 0.014f) + assertTrue(button.events.single() is XrPointerEvent.Down) + + val menu = panel() + val noButton = XrInteraction().update(head, listOf(aim(-0.48f, barY, trigger = 0.9f), idle), listOf(menu), 0.014f) + assertTrue(noButton.events.isEmpty()) + } + + @Test + fun theCornerResizesWithTheTopLeftCornerFixed() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(1f, panel.width, 1e-4f) + assertEquals(0.6f, panel.height, 1e-4f) + interaction.update(head, listOf(aim(0.78f, -0.48f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(1.3f, panel.width, 1e-3f) + assertEquals(0.8f, panel.height, 1e-3f) + assertEquals(-0.5f, panel.pose.position.x - panel.width / 2f, 1e-3f) + assertEquals(1.9f, panel.pose.position.y + panel.height / 2f, 1e-3f) + interaction.update(head, listOf(aim(-2f, 2f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(XrUnits.MIN_METRES, panel.width, 1e-4f) + assertEquals(XrUnits.MIN_METRES, panel.height, 1e-4f) + val done = interaction.update(head, listOf(aim(-2f, 2f), idle), listOf(panel), 0.014f) + assertTrue(done.events.single() is XrPointerEvent.Resized) + } + + @Test + fun thePetHeadClicksOrIsDragged() { + val head0 = XrPanelState(XrPanelKind.PET_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, -1f)), 0.12f, 0.12f) + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(head0), 0.014f) + val click = interaction.update(head, listOf(aim(), idle), listOf(head0), 0.014f) + assertTrue(click.events.single() is XrPointerEvent.Click) + + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(head0), 0.014f) + interaction.update(head, listOf(aim(0.05f, trigger = 0.9f), idle), listOf(head0), 0.014f) + interaction.update(head, listOf(aim(0.2f, trigger = 0.9f), idle), listOf(head0), 0.014f) + assertEquals(0.2f, head0.pose.position.x, 1e-3f) + val dropped = interaction.update(head, listOf(aim(0.2f), idle), listOf(head0), 0.014f) + assertTrue(dropped.events.single() is XrPointerEvent.Moved) + } + + @Test + fun aClosingPanelLetsGo() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + val out = XrInteractionOut() + interaction.release(panel, out) + assertTrue(out.events.single() is XrPointerEvent.Cancel) + assertFalse(interaction.holding(panel)) + } + + @Test + fun aReleaseAimedAwayFromThePanelCancels() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true) + val out = interaction.update(head, listOf(away, idle), listOf(panel), 0.014f) + assertTrue(out.events.single() is XrPointerEvent.Cancel) + } + + @Test + fun aPanelOneControllerHoldsCannotBeTakenByTheOther() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), idle), listOf(panel), 0.014f) + interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), aim(squeeze = 0.9f)), listOf(panel), 0.014f) + val out = interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), aim(0.3f, squeeze = 0.9f)), listOf(panel), 0.014f) + assertEquals(0f, panel.pose.position.x, 1e-3f) + assertTrue(out.events.isEmpty()) + } + + @Test + fun losingFocusCancelsAndAButtonStillHeldNeedsANewPress() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + val out = XrInteractionOut() + interaction.cancel(out) + assertTrue(out.events.single() is XrPointerEvent.Cancel) + assertFalse(interaction.holding(panel)) + val stillHeld = interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue(stillHeld.events.isEmpty()) + interaction.update(head, listOf(aim(), idle), listOf(panel), 0.014f) + val pressed = interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue(pressed.events.single() is XrPointerEvent.Down) + } + + @Test + fun bothControllersPressOnePanelAtOnce() { + val panel = panel() + val interaction = XrInteraction() + val first = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f)), listOf(panel), 0.014f) + assertEquals(2, first.cursors.getValue(panel).size) + assertEquals(0, (first.events.single() as XrPointerEvent.Down).hand) + val second = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f, trigger = 0.9f)), listOf(panel), 0.014f) + assertEquals(1, (second.events.single() as XrPointerEvent.Down).hand) + val up = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f)), listOf(panel), 0.014f) + assertEquals(1, (up.events.single() as XrPointerEvent.Up).hand) + } + + @Test + fun lettingGoOfThePetHeadOffItIsNoClick() { + val pet = XrPanelState(XrPanelKind.PET_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, -1f)), 0.12f, 0.12f) + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(pet), 0.014f) + val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true) + val out = interaction.update(head, listOf(away, idle), listOf(pet), 0.014f) + assertTrue(out.events.isEmpty()) + assertFalse(interaction.holding(pet)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrPanelsGateTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPanelsGateTest.kt new file mode 100644 index 0000000000..0ddd9b33ab --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPanelsGateTest.kt @@ -0,0 +1,113 @@ +package com.droiddeck.launcher.session.xr + +import android.content.Context +import android.view.Surface +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowBuild +import java.nio.ByteBuffer + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE) +class XrPanelsGateTest { + private val layers = object : XrLayerSource { + override val context: Context get() = RuntimeEnvironment.getApplication() + override fun createLayer(width: Int, height: Int) = -1 + override fun layerSurface(id: Int): Surface? = null + override fun destroyLayer(id: Int) = Unit + override fun setOrbImage(image: android.graphics.Bitmap) = Unit + override fun leave() = Unit + } + + private fun attach() = XrPanels.attach( + layers, ByteBuffer.allocateDirect(XrHostLayout.STATE_SIZE), ByteBuffer.allocateDirect(XrHostLayout.CONTROL_SIZE), + ) + + @After + fun detach() = XrPanels.detach() + + @Test + fun onlyAQuestInTheImmersiveViewOpensTheGate() { + assertTrue(XrPanels.gateOpen("Quest 3", "eureka", "Oculus", immersive = true)) + assertTrue(XrPanels.gateOpen("Quest 3S", "panther", "Oculus", immersive = true)) + assertFalse(XrPanels.gateOpen("Quest 3", "eureka", "Oculus", immersive = false)) + assertFalse(XrPanels.gateOpen("BKQ_N49", "BKQ", "HONOR", immersive = true)) + assertFalse(XrPanels.gateOpen("Pixel 9", "tokay", "Google", immersive = true)) + assertFalse(XrPanels.gateOpen("Rift", "rift", "Oculus", immersive = true)) + } + + @Test + fun offQuestTheMenuStaysInTheSessionWindow() { + ShadowBuild.setModel("BKQ_N49") + ShadowBuild.setDevice("BKQ") + ShadowBuild.setManufacturer("HONOR") + attach() + assertFalse(XrPanels.immersiveActive) + assertFalse(XrPanels.showMenu()) + } + + @Test + fun onQuestTheImmersiveViewTakesTheMenu() { + ShadowBuild.setModel("Quest 3") + ShadowBuild.setDevice("eureka") + ShadowBuild.setManufacturer("Oculus") + assertFalse(XrPanels.showMenu()) + attach() + assertTrue(XrPanels.immersiveActive) + assertTrue(XrPanels.showMenu()) + XrPanels.detach() + assertFalse(XrPanels.immersiveActive) + assertFalse(XrPanels.showMenu()) + } + + private class Host : XrMenuHost { + val immersive = mutableListOf() + @androidx.compose.runtime.Composable + override fun XrMenuContent() = Unit + override fun xrSetMenuOpen(open: Boolean) = Unit + override fun xrMenuBack() = Unit + override fun xrSendKey(code: Int, down: Boolean) = Unit + override fun xrTypeText(text: String) = Unit + override fun xrTapKey(keyCode: Int) = Unit + override fun xrImmersiveChanged(active: Boolean) { immersive += active } + } + + @Test + fun aFocusChangeInTheImmersiveViewSizesSteamsScreenAgain() { + ShadowBuild.setModel("Quest 3") + ShadowBuild.setDevice("eureka") + ShadowBuild.setManufacturer("Oculus") + val host = Host() + XrPanels.setMenuHost(host) + try { + attach() + settle() + val opened = host.immersive.size + assertTrue(opened >= 1 && host.immersive.all { it }) + com.droiddeck.launcher.agent.AgentGuest.focusRevision++ + settle() + assertTrue(host.immersive.size > opened) + assertTrue(host.immersive.all { it }) + XrPanels.detach() + val left = host.immersive.size + com.droiddeck.launcher.agent.AgentGuest.focusRevision++ + settle() + assertEquals(false, host.immersive.last()) + assertEquals(left, host.immersive.size) + } finally { + XrPanels.clearMenuHost(host) + } + } + + private fun settle() { + androidx.compose.runtime.snapshots.Snapshot.sendApplyNotifications() + org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrPcTextTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPcTextTest.kt new file mode 100644 index 0000000000..89b35ee470 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPcTextTest.kt @@ -0,0 +1,72 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Test + +class XrPcTextTest { + private class Field : XrKeyTarget { + val text = StringBuilder() + var entered = 0 + override fun type(text: String) { this.text.append(text) } + override fun backspace() { if (text.isNotEmpty()) text.setLength(text.length - 1) } + override fun enter() { entered++ } + } + + private fun XrPcText.tap(code: Int) { key(code, true); key(code, false) } + + @Test + fun pcKeysTypeIntoAPanelField() { + val field = Field() + val keys = XrPcText(field) + keys.key(42, true); keys.tap(35); keys.key(42, false) + keys.tap(18); keys.tap(57); keys.key(54, true); keys.tap(2); keys.key(54, false) + assertEquals("He !", field.text.toString()) + keys.tap(58); keys.tap(30); keys.tap(58); keys.tap(30) + assertEquals("He !Aa", field.text.toString()) + keys.tap(14); keys.tap(28) + assertEquals("He !A", field.text.toString()) + assertEquals(1, field.entered) + } + + private class FakeTimer : XrTimer { + var pending: (() -> Unit)? = null + override fun after(ms: Long, action: () -> Unit): () -> Unit { + pending = action + return { if (pending === action) pending = null } + } + fun fire() = pending!!.invoke() + } + + @Test + fun holdingBackspaceKeepsDeletingUntilItIsLetGo() { + val field = Field().apply { text.append("hello") } + val timer = FakeTimer() + val keys = XrPcText(field, timer) + keys.key(14, true) + assertEquals("hell", field.text.toString()) + timer.fire(); timer.fire() + assertEquals("he", field.text.toString()) + keys.key(14, false) + assertEquals(null, timer.pending) + assertEquals("he", field.text.toString()) + } + + @Test + fun anotherKeyLetGoLeavesBackspaceRepeating() { + val field = Field().apply { text.append("hello") } + val timer = FakeTimer() + val keys = XrPcText(field, timer) + keys.key(14, true) + keys.key(30, false) + timer.fire() + assertEquals("hel", field.text.toString()) + } + + @Test + fun keysWithNoCharacterTypeNothing() { + val field = Field() + val keys = XrPcText(field) + for (code in listOf(1, 59, 29, 56, 103, 105, 15, 111)) keys.tap(code) + assertEquals("", field.text.toString()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrPlacementTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPlacementTest.kt new file mode 100644 index 0000000000..6892d056e1 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPlacementTest.kt @@ -0,0 +1,67 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Test + +class XrPlacementTest { + @Test + fun aPanelComesBackAtTheSamePlaceRelativeToWhereTheUserFaces() { + val head = Pose(Quat.yaw(0.4f), Vec3(0.5f, 1.6f, 0.2f)) + val placed = XrPlacement.place(XrPanelKind.MENU, head, yaw = 0.3f, distance = 1.1f, dy = -0.2f) + val (yaw, distance, dy) = XrPlacement.relative(head, placed.position) + assertEquals(0.3f, yaw, 1e-4f) + assertEquals(1.1f, distance, 1e-4f) + assertEquals(-0.2f, dy, 1e-4f) + + val turned = Pose(Quat.yaw(1.4f), Vec3(-1f, 1.5f, 3f)) + val again = XrPlacement.place(XrPanelKind.MENU, turned, yaw, distance, dy) + val (yaw2, distance2, dy2) = XrPlacement.relative(turned, again.position) + assertEquals(yaw, yaw2, 1e-4f) + assertEquals(distance, distance2, 1e-4f) + assertEquals(dy, dy2, 1e-4f) + } + + @Test + fun aPlacedPanelFacesTheHead() { + val head = Pose(Quat.yaw(-0.8f), Vec3(0f, 1.6f, 0f)) + val placed = XrPlacement.place(XrPanelKind.MENU, head, yaw = 0.5f, distance = 0.9f, dy = 0f) + val front = placed.orientation.rotate(Vec3(0f, 0f, 1f)) + val toHead = (head.position - placed.position).normalized() + assertEquals(1f, front dot toHead, 1e-4f) + } + + @Test + fun straightAheadIsStraightAhead() { + val placed = XrPlacement.place(XrPanelKind.MENU, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f)), 0f, 1f, 0f) + assertEquals(0f, placed.position.x, 1e-5f) + assertEquals(-1f, placed.position.z, 1e-5f) + } + + @Test + fun theKeyboardLeansBackLikeOneOnADeskAndStillTakesTheLaser() { + val head = Pose(Quat.yaw(0.6f), Vec3(0f, 1.6f, 0f)) + val placed = XrPlacement.place(XrPanelKind.KEYBOARD, head, yaw = 0f, distance = 0.5f, dy = -0.5f) + val front = placed.orientation.rotate(Vec3(0f, 0f, 1f)) + val level = (head.position - placed.position).let { Vec3(it.x, 0f, it.z).normalized() } + assertEquals(0.7071f, front.y, 1e-3f) + assertEquals(0.7071f, front dot level, 1e-3f) + + val keyboard = XrPanelState(XrPanelKind.KEYBOARD, placed, 0.8f, 0.36f) + val hand = placed.position + Vec3(0f, 0.25f, 0f) + level * 0.15f + val down = (placed.position - hand).normalized() + val aim = Pose(rotationFromForward(down), hand) + val hit = keyboard.hit(aim) + assertNotNull(hit) + assertEquals(0f, hit!!.x, 1e-3f) + assertEquals(0f, hit.y, 1e-3f) + } + + private fun rotationFromForward(direction: Vec3): Quat { + val axis = Vec3.FORWARD cross direction + val angle = kotlin.math.acos((Vec3.FORWARD dot direction).coerceIn(-1f, 1f)) + val unit = axis.normalized() + val s = kotlin.math.sin(angle / 2f) + return Quat(unit.x * s, unit.y * s, unit.z * s, kotlin.math.cos(angle / 2f)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrSteamScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrSteamScreenTest.kt new file mode 100644 index 0000000000..2829772d20 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrSteamScreenTest.kt @@ -0,0 +1,23 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class XrSteamScreenTest { + @Test fun steamAndSteamVrAloneAreSteamsScreen() { + assertTrue(XrSteamScreen.shown(250820L, listOf(769L, 250820L))) + assertTrue(XrSteamScreen.shown(0L, listOf(769L))) + } + + @Test fun aRunningGameKeepsItFlatEvenWithSteamVrFocused() { + assertFalse(XrSteamScreen.shown(250820L, listOf(769L, 250820L, 1245620L))) + assertFalse(XrSteamScreen.shown(1245620L, null)) + } + + @Test fun aReportWithNoFocusIsUnknown() { + assertFalse(XrSteamScreen.shown(null, null)) + assertFalse(XrSteamScreen.shown(null, emptyList())) + assertFalse(XrSteamScreen.shown(0L, emptyList())) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt index ec8c63d100..b0c62a41e6 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt @@ -15,4 +15,19 @@ class WebCookiesTest { assertTrue(lines.none { it.startsWith("galaxy-login-al=c") }) assertEquals(emptyList(), WebCookies.expired(null, GogAuth.COOKIE_DOMAIN, listOf("/"), "login.gog.com")) } + + @Test fun cookiesScopedUnderTheSignInPathAreExpiredAtThatPath() { + val paths = WebCookies.scopes("https://accounts.ea.com/connect/auth", listOf("/")) + assertEquals(listOf("/", "/connect", "/connect/auth"), paths) + val lines = WebCookies.expired("sid=a; remid=b", ".ea.com", paths, "accounts.ea.com") + assertTrue(lines.contains("sid=; Max-Age=0; Path=/connect; Secure")) + assertTrue(lines.contains("remid=; Max-Age=0; Path=/connect; Secure; Domain=accounts.ea.com")) + assertEquals(listOf("/p", "/", "/p/juno", "/p/juno/login"), WebCookies.scopes("https://signin.ea.com/p/juno/login", listOf("/p", "/"))) + } + + @Test fun rootSignInUrlsKeepOnlyTheGivenPaths() { + assertEquals(listOf("/"), WebCookies.scopes("https://login.gog.com/", listOf("/"))) + assertEquals(listOf("/"), WebCookies.scopes("https://connect.ubisoft.com", listOf("/"))) + assertEquals(listOf("/", "/id", "/id/login"), WebCookies.scopes("https://www.epicgames.com/id/login", listOf("/", "/id"))) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetLibraryTest.kt new file mode 100644 index 0000000000..39f6d59448 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetLibraryTest.kt @@ -0,0 +1,34 @@ +package com.droiddeck.launcher.stores.battlenet + +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class BattleNetLibraryTest { + private val app get() = RuntimeEnvironment.getApplication() + @get:Rule val tmp = TemporaryFolder() + + @Test fun aMissingLibraryLeavesBattleNetsInstallFolderAlone() { + SessionPrefs.setGameStorage(app, "/storage/0000-0000/Games", "SD card") + assertTrue(BattleNetClient.library(app).isEmpty()) + } + + @Test fun anAttachedLibraryIsHandedToBattleNet() { + SessionPrefs.setGameStorage(app, tmp.newFolder("card").path, "SD card") + assertEquals("--library", BattleNetClient.library(app).firstOrNull()) + } + + @Test fun internalStorageIsHandedToBattleNetWhenItIsTheChoice() { + SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "") + assertEquals("--library", BattleNetClient.library(app).firstOrNull()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt index 84500376ca..5cafddc391 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt @@ -132,6 +132,45 @@ class EaTest { dir.deleteRecursively() } + private object LsxAccount : EaLsx.Account { + override val userId = "1000000000042" + override val personaId = "1000000000043" + override val persona = "Player" + override fun authCode(clientId: String, scope: String?) = "code" + override fun license(contentId: String, requestTicket: String, ticketEngine: String) = "licence" + override fun entitlements(group: String) = emptyList>() + override fun token() = "token" + } + + private fun lsx(body: String) = EaLsx.parse("$body")!! + + @Test fun theGamesSecondSessionGetsTheProfileButNoSecrets() { + EaLsx.account = LsxAccount + try { + val sdk = EaLsx.Session(java.net.Socket(), java.io.ByteArrayOutputStream(), false, unverifiable = true).apply { claimed = true } + val profile = EaLsx.answer(sdk, lsx(""))!! + assertTrue(profile, profile.contains("UserId=\"1000000000042\"")) + assertTrue(profile, profile.contains("PersonaId=\"1000000000043\"")) + assertTrue(profile, profile.contains("Persona=\"Player\"")) + assertTrue(EaLsx.answer(sdk, lsx(""))!!.contains("UserId=\"1000000000042\"")) + assertEquals("", EaLsx.answer(sdk, lsx(""))) + assertEquals("", EaLsx.answer(sdk, lsx(""))) + + val stranger = EaLsx.Session(java.net.Socket(), java.io.ByteArrayOutputStream(), false, unverifiable = true) + assertTrue(EaLsx.answer(stranger, lsx(""))!!.contains("UserId=\"\"")) + } finally { + EaLsx.account = null + } + } + + @Test fun getSettingsAnswersWithTheSdksSettingsType() { + val session = EaLsx.Session(java.net.Socket(), java.io.ByteArrayOutputStream(), false) + assertEquals( + "", + EaLsx.answer(session, lsx("")), + ) + } + @Test fun lsxRequestsAreParsed() { val m = EaLsx.parse("")!! assertEquals("GetSetting", m.name) diff --git a/app/src/test/java/com/droiddeck/launcher/stores/steam/SteamPickingSnapshotTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/steam/SteamPickingSnapshotTest.kt new file mode 100644 index 0000000000..6193a037bf --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/steam/SteamPickingSnapshotTest.kt @@ -0,0 +1,37 @@ +package com.droiddeck.launcher.stores.steam + +import androidx.compose.runtime.State +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.runtime.snapshots.StateObject +import com.droiddeck.launcher.stores.StoresState +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import kotlin.concurrent.thread + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE) +class SteamPickingSnapshotTest { + @Test + fun theInstallPickerIsReadableInASnapshotOpenedBeforeTheSteamEngineStarts() { + StoresState.steamPicking = null + val snapshot = Snapshot.takeMutableSnapshot() + try { + thread { SteamStore.hashCode() }.join() + assertNull(snapshot.enter { StoresState.steamPicking }) + } finally { + snapshot.dispose() + } + } + + @Test + fun theSteamEngineHoldsNoComposeState() { + val stateFields = SteamStore::class.java.declaredFields.filter { + StateObject::class.java.isAssignableFrom(it.type) || State::class.java.isAssignableFrom(it.type) + } + assertTrue(stateFields.joinToString { it.name }, stateFields.isEmpty()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt index 810c2f8642..fcb2e77286 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt @@ -201,6 +201,22 @@ class XboxCatalogTest { assertTrue(retail.xboxPc); assertEquals("EAPPX", retail.extra["format"]); assertEquals(7L, retail.sizeBytes) } + @Test fun anOriginalXboxGameShowsTheSizeOfItsConsolePackage() { + fun pkg(family: String?, format: String, platform: String, size: Long) = JSONObject().put("PackageFormat", format) + .put("MaxDownloadSizeInBytes", size).apply { if (family != null) put("PackageFamilyName", family) } + .put("PlatformDependencies", JSONArray().put(JSONObject().put("PlatformName", platform))) + fun offer(vararg packages: JSONObject) = JSONObject().put("ProductId", game).put("ProductType", "Game") + .put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "Fuzion Frenzy"))) + .put("DisplaySkuAvailabilities", JSONArray().put(JSONObject().put("Sku", JSONObject().put("Properties", + JSONObject().put("Packages", JSONArray(packages.toList())))))) + val console = pkg(null, "XVC", "Windows.Xbox", 2_670_796_800L) + val emulator = pkg("Xbox360BackwardCompatibil.PrimaryFuzionFrenzyFuzio_ksqcvrsvwz2jp", "MSIXVC", "Windows.Desktop", 753_313L) + assertEquals(2_670_796_800L, XboxCatalog.product(offer(console, emulator), mapOf(game to "gamepass"))!!.sizeBytes) + assertEquals(753_313L, XboxCatalog.product(offer(emulator), mapOf(game to "gamepass"))!!.sizeBytes) + val native = pkg("Microsoft.SomeGame_8wekyb3d8bbwe", "MSIXVC", "Windows.Desktop", 40_000_000L) + assertEquals(40_000_000L, XboxCatalog.product(offer(console, native), mapOf(game to "owned"))!!.sizeBytes) + } + @Test fun aCloudOnlyEditionFoldsIntoThePcCardWithTheSameTitle() { val cloud = XboxCloudCatalog(gamePass = setOf(parent), all = emptySet()) val pc = XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), cloud)!! diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XodusDiagnosticsTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XodusDiagnosticsTest.kt index 3e2310be5c..6b9ecb4918 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XodusDiagnosticsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XodusDiagnosticsTest.kt @@ -9,6 +9,25 @@ import org.junit.Test class XodusDiagnosticsTest { private val rejected = Regex(Xodus.SIGN_IN_REJECTED) + @Test fun aDeviceLimitReachesTheInstallerWithoutBecomingASignInFailure() { + val line = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200" + val tail = listOf(line).filter { it.matches(Xodus.reportable) } + assertEquals(listOf(line), tail) + assertFalse(line.matches(rejected)) + assertEquals(com.droiddeck.launcher.R.string.stores_xbox_device_group_full, XboxInstaller.licenseRefusal(tail)) + } + + @Test fun aLaterLicenseSuccessClearsTheDeviceLimitThroughTheDiagnosticFilter() { + val stderr = listOf( + "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200", + "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-parsed 200", + "NEXUS_EXTRACT_DIAGNOSTIC_V1 extract-failed" + ) + val tail = stderr.filter { it.matches(Xodus.reportable) } + assertEquals(stderr, tail) + assertNull(XboxInstaller.licenseRefusal(tail)) + } + @Test fun aContentLicenseRejectionIsRecognised() { assertTrue("Microsoft content licensing rejected sign-in (HTTP 401). Sign in again in Settings.".matches(rejected)) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AgentPetChatFocusTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AgentPetChatFocusTest.kt new file mode 100644 index 0000000000..e5214e1e98 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AgentPetChatFocusTest.kt @@ -0,0 +1,47 @@ +package com.droiddeck.launcher.ui + +import android.view.KeyEvent as AndroidKeyEvent +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performKeyPress +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], qualifiers = "w411dp-h891dp-port", application = android.app.Application::class) +class AgentPetChatFocusTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun keysStillReachTheEditorAfterTheChatClosesAndOpensAgain() { + val open = mutableStateOf(true) + val text = mutableStateOf("ab") + val motion = PetMotion(RuntimeEnvironment.getApplication()) + compose.setContent { + DroidDeckTheme { + PetChat(open.value, motion, onClose = { open.value = false }, page = { + BasicTextField(text.value, { text.value = it }, Modifier.testTag("editor")) + }) {} + } + } + compose.onNodeWithTag("editor").performClick() + open.value = false + compose.waitForIdle() + open.value = true + compose.waitForIdle() + + compose.onNodeWithTag("editor").performKeyPress(KeyEvent(AndroidKeyEvent(AndroidKeyEvent.ACTION_DOWN, AndroidKeyEvent.KEYCODE_DEL))) + compose.waitForIdle() + + assertEquals("a", text.value) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AgentPetQuestTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AgentPetQuestTest.kt new file mode 100644 index 0000000000..c838ed1bf5 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AgentPetQuestTest.kt @@ -0,0 +1,24 @@ +package com.droiddeck.launcher.ui + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE) +class AgentPetQuestTest { + @Test + fun phonesKeepTheFloatingPetAndItsChat() { + assertTrue(AgentPet.usesOverlayWindows(quest = false)) + assertFalse(AgentPet.chatInOwnWindow(quest = false)) + } + + @Test + fun questUsesNoOverlayWindowsAndOpensTheChatAsItsOwnPanel() { + assertFalse(AgentPet.usesOverlayWindows(quest = true)) + assertTrue(AgentPet.chatInOwnWindow(quest = true)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AgentReplyTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AgentReplyTest.kt new file mode 100644 index 0000000000..9069c6b292 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AgentReplyTest.kt @@ -0,0 +1,37 @@ +package com.droiddeck.launcher.ui + +import org.junit.Assert.assertEquals +import org.junit.Test + +class AgentReplyTest { + @Test + fun anImageOnItsOwnLineSplitsTheReply() { + val parts = replyParts("Here it is:\n\n![Proposed Updates tab](/tmp/updates.png)\n\nWant changes?") + assertEquals( + listOf( + ReplyPart.Prose("Here it is:"), + ReplyPart.Picture("Proposed Updates tab", "/tmp/updates.png"), + ReplyPart.Prose("\nWant changes?"), + ), + parts, + ) + } + + @Test + fun fileUrlsAndAngleBracketsNameTheSamePath() { + assertEquals(listOf(ReplyPart.Picture("", "/root/a b.png")), replyParts("![]()")) + assertEquals(listOf(ReplyPart.Picture("chart", "/root/chart (1).png")), replyParts("![chart]()")) + } + + @Test + fun imagesInCodeInlineOrRemoteStayText() { + val fenced = "```\n![x](/tmp/x.png)\n```" + assertEquals(listOf(ReplyPart.Prose(fenced)), replyParts(fenced)) + val inline = "See ![x](/tmp/x.png) here" + assertEquals(listOf(ReplyPart.Prose(inline)), replyParts(inline)) + val nested = "````\n```\n![x](/tmp/x.png)\n```python\n![y](/tmp/y.png)\n````" + assertEquals(listOf(ReplyPart.Prose(nested)), replyParts(nested)) + val remote = "![x](https://example.com/x.png)" + assertEquals(listOf(ReplyPart.Prose(remote)), replyParts(remote)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt index b16a03071b..186a6c7e4b 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -300,7 +300,7 @@ class CurseLinkTabTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt index 641de899ac..b8e35d27aa 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt @@ -85,7 +85,7 @@ class DesktopUninstallTest { ), FrontEndActions( onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, - onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, + onRuntime = {}, onFrameGenPick = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = { removals++ }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/DrawerSectionTestSupport.kt b/app/src/test/java/com/droiddeck/launcher/ui/DrawerSectionTestSupport.kt new file mode 100644 index 0000000000..e86d0e2201 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/DrawerSectionTestSupport.kt @@ -0,0 +1,12 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.test.SemanticsNodeInteractionsProvider +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo + +/** Session menu groups start folded; a test opens the one whose rows it checks. */ +internal fun SemanticsNodeInteractionsProvider.openSection(key: String) { + if (DrawerSectionState.isOpen(key)) return + onNodeWithTag("drawer-section-$key").performScrollTo().performClick() +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt index b685aac7ec..3891479800 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt @@ -65,7 +65,7 @@ class FlathubFocusTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GameTabBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GameTabBarTest.kt new file mode 100644 index 0000000000..8b7d15e1b7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/GameTabBarTest.kt @@ -0,0 +1,40 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class) +class GameTabBarTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun narrowGameDetailsKeepEachTabInTheStrip() { + compose.setContent { + DroidDeckTheme { + Box(Modifier.width(320.dp)) { + var selected by remember { mutableIntStateOf(0) } + GameTabBar(listOf("About", "Launch", "Install"), selected, { selected = it }, compact = true) + } + } + } + compose.onNodeWithTag("tab-menu").assertDoesNotExist() + for (index in 0..2) { + compose.onNodeWithTag("tab-$index").assertIsDisplayed().performClick().assertIsSelected() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt index 97d1d95094..404cf23731 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt @@ -56,7 +56,7 @@ class GamesClientTagTest { onPlay = {}, onPlaySteamVr = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt index aadb56e753..1a0404f748 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt @@ -16,6 +16,7 @@ import com.droiddeck.launcher.R import com.droiddeck.launcher.glasses.Glasses import com.droiddeck.launcher.glasses.GlassesSettings import com.droiddeck.launcher.glasses.GlassesState +import com.droiddeck.launcher.session.SessionPrefs import kotlinx.coroutines.flow.MutableStateFlow import org.junit.After import org.junit.Assert.assertEquals @@ -71,6 +72,7 @@ class GlobalGlassesSettingsTest { compose.onNodeWithText(text(R.string.setup_glasses_scope)).assertExists() compose.onNodeWithText(text(R.string.setup_glasses_connect)).assertExists() + compose.onNodeWithTag("setting-glasses-shortcut").assertExists() compose.onNodeWithTag("setting-glasses-game").assertDoesNotExist() compose.onNodeWithTag("play-steamvr").assertDoesNotExist() @@ -103,6 +105,29 @@ class GlobalGlassesSettingsTest { assertEquals(saved, Glasses.settings.value) } + @Test fun globalShortcutVisibilitySettingIsSavedAndDefaultsToVisible() { + state().value = connected + val app = RuntimeEnvironment.getApplication() + val prefs = app.getSharedPreferences("session", Context.MODE_PRIVATE) + val hadValue = prefs.contains("showGlassesShortcut") + val previous = prefs.getBoolean("showGlassesShortcut", true) + prefs.edit().remove("showGlassesShortcut").commit() + try { + assertTrue(SessionPrefs.showGlassesShortcut(app)) + show() + openGlasses() + compose.onNodeWithTag("setting-glasses-shortcut").performScrollTo().assert( + SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, text(R.string.widgets_on))) + compose.onNodeWithTag("setting-glasses-shortcut").performClick() + assertEquals(false, SessionPrefs.showGlassesShortcut(app)) + compose.onNodeWithTag("setting-glasses-shortcut").assert( + SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, text(R.string.widgets_off))) + } finally { + if (hadValue) prefs.edit().putBoolean("showGlassesShortcut", previous).commit() + else prefs.edit().remove("showGlassesShortcut").commit() + } + } + @Test fun globalScreenTrackingUsesTheExistingSavedSettings() { state().value = connected settings().value = GlassesSettings(gameOnGlasses = false, headTracking = false) @@ -140,7 +165,7 @@ class GlobalGlassesSettingsTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/IdleFramesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/IdleFramesTest.kt index 860fcc9665..27f1e553c5 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/IdleFramesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/IdleFramesTest.kt @@ -1,19 +1,37 @@ package com.droiddeck.launcher.ui import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test class IdleFramesTest { - @Test - fun idleLoopsDrawThirtyFramesASecondAndShareEachOne() { - val start = 5_000_000_000L - val frame = 8_333_333L - val drawn = (0 until 120).count { IdleFrames.due(start + it * frame) } - assertEquals(30, drawn) + private val start = 5_000_000_000L - val later = start + 1_000_000_000L - assertEquals(listOf(true, true, true), List(3) { IdleFrames.due(later) }) - assertEquals(listOf(false, false), List(2) { IdleFrames.due(later + frame) }) - assertEquals(listOf(true, true), List(2) { IdleFrames.due(later + 4 * frame) }) + @Test + fun idleLoopsDrawAtSixtyOrThePanelRateIfLower() { + for (hz in listOf(30, 60, 90, 120, 144)) { + val gate = IdleFrameGate() + val drawn = (0 until 10 * hz).count { gate.due(start + it * 1_000_000_000L / hz) } + assertEquals("panel at $hz Hz", 10 * minOf(hz, 60), drawn) + } + } + + @Test + fun idleLoopsShareTheDecisionForEachVsync() { + val gate = IdleFrameGate() + assertEquals(List(3) { true }, List(3) { gate.due(start) }) + assertEquals(List(2) { false }, List(2) { gate.due(start + 8_333_333) }) + assertEquals(List(2) { true }, List(2) { gate.due(start + 16_666_666) }) + } + + @Test + fun aLongPauseDoesNotCauseCatchUpDraws() { + val gate = IdleFrameGate() + assertTrue(gate.due(start)) + val resumed = start + 1_000_000_000L + assertTrue(gate.due(resumed)) + assertFalse(gate.due(resumed + 8_333_333)) + assertTrue(gate.due(resumed + 16_666_666)) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt index cd92665cc2..a42a0bf76c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt @@ -227,6 +227,81 @@ class InputSurfaceTouchTest { touch(MotionEvent.ACTION_UP, 1 to (750f to 285f)) } + @Test fun theMiddleOfACrossedDpadPressesTheNearestArmInsteadOfFallingThrough() { + val up = InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f) + val down = InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f) + show(up, down, InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f), + InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f), a) + val missed = mutableListOf() + view.onTouchMiss = { missed += it.actionMasked } + touch(MotionEvent.ACTION_DOWN, 1 to (500f to 170f)) + assertEquals(-1, state().hatY()) + touch(MotionEvent.ACTION_MOVE, 1 to (540f to 215f)) + assertEquals(1, state().hatX()) + assertEquals(0, state().hatY()) + touch(MotionEvent.ACTION_UP, 1 to (540f to 215f)) + assertEquals(0, state().hatX()) + assertTrue(missed.isEmpty()) + assertFalse(view.takesTouchAt(250f, 210f)) + assertFalse(view.takesTouchAt(800f, 500f)) + assertFalse(view.takesTouchAt(350f, 100f)) + show(up, down) + assertFalse(view.takesTouchAt(500f, 210f)) + view.onTouchMiss = null + } + + @Test fun aHandPlacedDpadWithOffArmsStillTakesItsMiddle() { + show(InputSurfaceElement(InputControl.UP, .42f, .1f, .1f, .15f), + InputSurfaceElement(InputControl.DOWN, .42f, .45f, .1f, .15f), + InputSurfaceElement(InputControl.LEFT, .3f, .27f, .15f, .15f), + InputSurfaceElement(InputControl.RIGHT, .5f, .25f, .15f, .2f)) + touch(MotionEvent.ACTION_DOWN, 1 to (475f to 225f)) + assertTrue(state().hatX() != 0 || state().hatY() != 0) + touch(MotionEvent.ACTION_UP, 1 to (475f to 225f)) + assertFalse(view.takesTouchAt(750f, 225f)) + } + + @Test fun aTallGapPicksTheNearestArmAndSplitArmsAreNoCross() { + show(InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f), + InputSurfaceElement(InputControl.DOWN, .45f, .65f, .1f, .15f), + InputSurfaceElement(InputControl.LEFT, .3f, .35f, .15f, .2f), + InputSurfaceElement(InputControl.RIGHT, .55f, .35f, .15f, .2f)) + touch(MotionEvent.ACTION_DOWN, 1 to (530f to 290f)) + assertEquals(1, state().hatX()) + assertEquals(0, state().hatY()) + touch(MotionEvent.ACTION_UP, 1 to (530f to 290f)) + touch(MotionEvent.ACTION_DOWN, 1 to (530f to 180f)) + assertEquals(-1, state().hatY()) + assertEquals(0, state().hatX()) + touch(MotionEvent.ACTION_UP, 1 to (530f to 180f)) + show(InputSurfaceElement(InputControl.UP, .2f, .1f, .1f, .15f), + InputSurfaceElement(InputControl.DOWN, .7f, .6f, .1f, .15f), + InputSurfaceElement(InputControl.LEFT, .1f, .35f, .15f, .2f), + InputSurfaceElement(InputControl.RIGHT, .8f, .35f, .15f, .2f)) + assertFalse(view.takesTouchAt(500f, 300f)) + } + + @Test fun aSecondUpButtonDoesNotHideTheCross() { + show(InputSurfaceElement(InputControl.UP, .1f, .7f, .1f, .15f, "extra-up"), + InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f), + InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f), + InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f), + InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f)) + touch(MotionEvent.ACTION_DOWN, 1 to (500f to 170f)) + assertEquals(-1, state().hatY()) + touch(MotionEvent.ACTION_UP, 1 to (500f to 170f)) + assertEquals(0, state().hatY()) + show(InputSurfaceElement(InputControl.UP, .45f, 0f, .1f, .05f, "extra-up"), + InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f), + InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f), + InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f), + InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f)) + touch(MotionEvent.ACTION_DOWN, 1 to (490f to 170f)) + assertEquals(-1, state().hatY()) + assertEquals(0, state().hatX()) + touch(MotionEvent.ACTION_UP, 1 to (490f to 170f)) + } + @Test fun adaptiveSticksCaptureAroundThemAndTheLeftOneToTheEdge() { val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true) val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, hideWhenIdle = true) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt index 508e2ed4b6..7adbbfacc4 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt @@ -98,7 +98,7 @@ class InputUiLayoutTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, controller = ControllerActions({}), diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt index 65eef5d38f..4fd6e49737 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt @@ -63,7 +63,7 @@ class LaunchSettingsComponentsTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = { defaultOpens++ }, + onProtons = {}, onComponents = { defaultOpens++ }, onGameComponents = { openedGame = it }, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LauncherFrostTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LauncherFrostTest.kt new file mode 100644 index 0000000000..51fb7a92ba --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/LauncherFrostTest.kt @@ -0,0 +1,166 @@ +package com.droiddeck.launcher.ui + +import android.app.Activity +import android.content.Context +import android.view.WindowManager +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.compositeOver +import androidx.compose.ui.graphics.luminance +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class LauncherFrostTest { + private val app get() = RuntimeEnvironment.getApplication() + private val graphite get() = Themes.byId(Themes.GRAPHITE) + private val whiteRed get() = Themes.byId(Themes.WHITE_RED) + + @Before fun clear() { + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + private fun contrast(a: Color, b: Color) = (maxOf(a.luminance(), b.luminance()) + 0.05f) / (minOf(a.luminance(), b.luminance()) + 0.05f) + + private val wallpapers = listOf(Color.White, Color.Black, Color(0xFF808080), Color(0xFFFFE600), Color(0xFF00008B), Color(0xFF20AA96), Color(0xFFE2725B)) + + private val steps = (0..FROST_MAX step FROST_STEP).toList() + + private fun look(theme: Palette, transparency: Int = FROST_WALLPAPER_DEFAULT, cards: Boolean = false, cardTransparency: Int = FROST_DEFAULT) = + frostLook(theme, FrostChoice(transparency, cards, cardTransparency)) + + @Test fun hintTextStaysReadableOnThePageAndOnCardsOverAnyPartOfAnyWallpaper() { + for (theme in Themes.all) for (t in steps) for (c in listOf(0, FROST_DEFAULT, FROST_MAX)) { + val look = look(theme, t, cards = true, cardTransparency = c) + val frosted = theme.frosted(look) + assertTrue("${theme.id} $t/$c veil ${look.veil.alpha}", look.veil.alpha in 0.31f..0.95f) + for (wallpaper in wallpapers) { + val page = look.veil.compositeOver(wallpaper) + val card = frosted.surface.compositeOver(page) + val at = "${theme.id} $t/$c over $wallpaper" + assertTrue("$at page", contrast(frosted.onSurfaceVariant, page) >= 4.5f) + assertTrue("$at card", contrast(frosted.onSurfaceVariant, card) >= 4.5f) + } + } + } + + private fun custom(bg: Color, text: Color) = Palette( + "custom", graphite.label, graphite.detail, + background = bg, surface = bg, surfaceVariant = bg, line = bg, line2 = bg, + onBackground = text, onSurfaceVariant = text, + primary = text, primary2 = text, onPrimary = bg, signal = text, good = text, + ) + + @Test fun aMidGreyCustomPaletteStaysReadableOverBlackAndWhiteWallpaper() { + val grey = custom(Color(0xFF999999), Color.Black) + val look = look(grey, cards = false) + for (wallpaper in listOf(Color.Black, Color.White)) { + assertTrue("over $wallpaper", contrast(Color.Black, look.veil.compositeOver(wallpaper)) >= 4.5f) + } + } + + @Test fun whenNoTintIsReadableTheVeilTurnsSolid() { + val dim = custom(Color.Black, Color(0xFF777777)) + assertEquals(1f, look(dim, cards = false).veil.alpha) + } + + @Test fun aTintThatLosesTheTextOverOneWallpaperTurnsSolid() { + val grey = custom(Color.Black, Color(0xFF757575)) + val look = look(grey, cards = false) + for (wallpaper in listOf(Color.Black, Color.White)) { + assertTrue("over $wallpaper", contrast(Color(0xFF757575), look.veil.compositeOver(wallpaper)) >= 4.5f) + } + } + + @Test fun atTheDefaultTransparencyTheVeilStaysUnderThreeQuarters() { + for (theme in Themes.all) assertTrue(theme.id, look(theme, cards = true).veil.alpha <= 0.75f) + } + + @Test fun moreTransparencyNeverThickensTheVeilOrTheCards() { + for (theme in Themes.all) { + val veils = steps.map { look(theme, it).veil.alpha } + assertTrue("${theme.id}: $veils", veils.zipWithNext().all { (a, b) -> b <= a + 0.005f }) + val cards = steps.map { look(theme, cards = true, cardTransparency = it).cardAlpha } + assertTrue("${theme.id} cards: $cards", cards.zipWithNext().all { (a, b) -> b <= a }) + } + assertTrue(look(graphite, FROST_MAX).veil.alpha < look(graphite).veil.alpha) + assertTrue(look(whiteRed, FROST_MAX).veil.alpha < look(whiteRed).veil.alpha) + } + + @Test fun withoutCardsTheFrostOnlyMovesHintTextTowardTheMainText() { + val frosted = graphite.frosted(look(graphite)) + assertEquals(graphite.background, frosted.background) + assertEquals(graphite.surface, frosted.surface) + assertEquals(graphite.surfaceVariant, frosted.surfaceVariant) + assertEquals(graphite.onBackground, frosted.onBackground) + assertTrue(frosted.onSurfaceVariant.luminance() > graphite.onSurfaceVariant.luminance()) + assertTrue(frosted.onSurfaceVariant.luminance() < graphite.onBackground.luminance()) + } + + @Test fun cardsGoSeeThroughByTheirOwnTransparencyAndAreSolidAtZero() { + for (theme in Themes.all) { + val frosted = theme.frosted(look(theme, cards = true)) + assertTrue(theme.id, frosted.surface.alpha in 0.5f..0.8f && frosted.surfaceVariant.alpha == frosted.surface.alpha) + assertEquals(theme.surface, frosted.surface.copy(alpha = 1f)) + assertEquals(theme.background, frosted.background) + assertEquals(1f, look(theme, cards = true, cardTransparency = 0).cardAlpha) + } + } + + @Test fun firstTurningTheFrostOnFrostsTheWallpaperAndCardsAtTheDefaults() { + assertFalse(SessionPrefs.launcherFrost(app)) + assertTrue(SessionPrefs.frostWallpaper(app)) + assertTrue(SessionPrefs.frostCards(app)) + assertEquals(FROST_WALLPAPER_DEFAULT, SessionPrefs.frostTransparency(app)) + assertEquals(FROST_DEFAULT, SessionPrefs.frostCardTransparency(app)) + SessionPrefs.setLauncherFrost(app, true) + SessionPrefs.setFrostWallpaper(app, false) + SessionPrefs.setFrostCards(app, false) + SessionPrefs.setFrostTransparency(app, 999) + SessionPrefs.setFrostCardTransparency(app, -5) + assertTrue(SessionPrefs.launcherFrost(app)) + assertFalse(SessionPrefs.frostWallpaper(app)) + assertFalse(SessionPrefs.frostCards(app)) + assertEquals(FROST_MAX, SessionPrefs.frostTransparency(app)) + assertEquals(0, SessionPrefs.frostCardTransparency(app)) + } + + @Test fun searchFindsTheFrostOnlyWhereSettingsShowsIt() { + val frosted = SettingsIndex.entries.single { it.frost } + assertTrue(frosted in SettingsIndex.search(app, "transparency", frost = true)) + assertFalse(frosted in SettingsIndex.search(app, "transparency", frost = false)) + assertTrue(SettingsIndex.search(app, "theme", frost = false).isNotEmpty()) + } + + @Test fun theWindowIsPreparedWhileBlurIsOffAndShowsNoWallpaperUntilShown() { + val activity = Robolectric.buildActivity(Activity::class.java).setup().get() + val frost = LauncherFrost(activity) + val flags = WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER or WindowManager.LayoutParams.FLAG_BLUR_BEHIND + frost.prepare(true) + assertFalse(frost.available) + assertTrue(frost.prepared) + assertEquals(0, activity.window.attributes.flags and flags) + frost.show(true) + assertEquals(flags, activity.window.attributes.flags and flags) + } + + @Test fun aWindowThatWasNotPreparedKeepsItsBackgroundAndShowsNoWallpaper() { + val activity = Robolectric.buildActivity(Activity::class.java).setup().get() + val before = activity.window.decorView.background + val frost = LauncherFrost(activity) + frost.prepare(false) + frost.show(true) + assertFalse(frost.prepared) + assertEquals(before, activity.window.decorView.background) + assertEquals(0, activity.window.attributes.flags and (WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER or WindowManager.LayoutParams.FLAG_BLUR_BEHIND)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryDisplayTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryDisplayTest.kt new file mode 100644 index 0000000000..90f44b6c98 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryDisplayTest.kt @@ -0,0 +1,35 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class LibraryDisplayTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + + @Before fun reset() { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + LibraryDisplay.load(context) + } + + @Test fun titleAndSizeDefaultOff() { + assertFalse(LibraryDisplay.title) + assertFalse(LibraryDisplay.size) + } + + @Test fun savedChoicesStillLoad() { + LibraryDisplay.toggleTitle(context) + LibraryDisplay.toggleSize(context) + LibraryDisplay.load(context) + assertTrue(LibraryDisplay.title) + assertTrue(LibraryDisplay.size) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt index 87e1d0bbb3..c82f031233 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt @@ -51,6 +51,7 @@ class LibraryVisibilityTest { StoreAccounts.keys = CredentialCipher.KeyProvider { SecretKeySpec(ByteArray(32) { 7 }, "AES") } StoreAccounts.keystoreFailed = false ctx.getSharedPreferences("session", 0).edit().clear().commit() + SessionPrefs.setLibraryShowTitle(ctx, true) LibraryView.source = LIBRARY_ALL LibraryView.query = "" LibraryView.focusFirst = false @@ -72,6 +73,7 @@ class LibraryVisibilityTest { StoresState.library.clear() StoresState.accounts.clear() ctx.getSharedPreferences("session", 0).edit().clear().commit() + SessionPrefs.setLibraryShowTitle(ctx, true) LibraryView.source = LIBRARY_ALL LibraryView.query = "" LibraryView.focusFirst = false @@ -249,7 +251,7 @@ class LibraryVisibilityTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt index 72546927c7..3205eddb63 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -77,6 +77,17 @@ class NavTabsTest { assertFalse("desktop" in navigationKeys(s)) } + @Test fun moreStaysOnTheBarWhenNoTabIsShelvedSoTabsCanStillBeEdited() { + NavTabs.more(state()).forEach { place(it, TabPlace.HIDDEN) } + assertTrue(NavTabs.more(state()).isEmpty()) + assertEquals(NavTabs.MORE, navigationKeys(state()).last()) + NavTabs.reset(ctx) + NavTabs.more(state()).forEach { place(it, TabPlace.BAR) } + assertTrue(NavTabs.more(state()).isEmpty()) + assertEquals(NavTabs.MORE, navigationKeys(state()).last()) + assertEquals(1, navigationKeys(state()).count { it == NavTabs.MORE }) + } + @Test fun appsAndTheDevHarnessCanBeShownWithoutHomeScreenOrDeveloperTools() { place("android-apps", TabPlace.MORE) assertTrue("android-apps" in NavTabs.more(state())) @@ -275,7 +286,7 @@ class NavTabsTest { private fun actions() = FrontEndActions( onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, - onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, + onRuntime = {}, onFrameGenPick = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = {}, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt index 004fe8cd64..6fba8b7e8c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt @@ -92,7 +92,7 @@ class NavigationSelectionTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PenSettingsGroupTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PenSettingsGroupTest.kt index cc416ce52c..fd650cf014 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PenSettingsGroupTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PenSettingsGroupTest.kt @@ -31,7 +31,9 @@ class PenSettingsGroupTest { @Test fun theDrawerHasNoPenGroupUntilAPenIsKnown() { compose.setContent { DroidDeckTheme { SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(pen = null)) } } + compose.openSection("controller-touch") compose.onNodeWithTag("setting-touch").assertExists() + compose.onNodeWithTag("drawer-section-controller-pen").assertDoesNotExist() compose.onNodeWithTag("setting-pen").assertDoesNotExist() compose.onNodeWithTag("setting-pen-button").assertDoesNotExist() } @@ -43,6 +45,7 @@ class PenSettingsGroupTest { SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(SessionPrefs.Pen()) { k, v -> picks += k to v }) } } + compose.openSection("controller-pen") compose.onNodeWithTag("setting-pen-button").performScrollTo().performClick() compose.onNodeWithText(context.getString(R.string.gesture_middle_click)).performScrollTo().performClick() compose.onNodeWithTag("setting-pen").performScrollTo().performClick() @@ -92,7 +95,7 @@ class PenSettingsGroupTest { suspendPolicy = "auto", backActionsInverted = false, touchMode = "auto", touchAuto = "touchpad", pen = pen, onPen = onPen, fexPreset = "default", secondScreenMode = SecondScreenMode.NONE, secondScreenDisplays = emptyList(), selectedSecondScreenDisplay = 1, - onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, + onHud = {}, onFrameGenPick = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {}, onTouch = {}, onFexPreset = {}, onSecondScreenMode = {}, onSecondScreenDisplay = {}, onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {}) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt index f5988c0b80..42603b4571 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt @@ -150,7 +150,7 @@ class PortraitLayoutTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt index 2239382b37..f9f1979206 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt @@ -297,9 +297,23 @@ class SecondScreenBarTest { } finally { panel()?.closeControls() } } - @Test fun unfoldedControlsGetTheSessionBar() { - SessionState.mode = SessionService.MODE_STEAM - val activity = Robolectric.buildActivity(SessionActivity::class.java).get() - assertTrue(ReflectionHelpers.callInstanceMethod(activity, "unfoldedBar") is ComposeView) + @Test fun unfoldedPadHasSteamQuickAccessAndDrawerWithoutTheSecondScreenBar() { + val actions = mutableListOf() + compose.setContent { DroidDeckTheme { PadKeys(true, { actions += "menu" }, { actions += "steam" }, { actions += "qam" }) } } + compose.onNodeWithTag("bottom-bar-tabs").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-close").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-steam").assertIsDisplayed().performClick() + compose.onNodeWithTag("bottom-bar-menu").assertIsDisplayed().performClick() + compose.onNodeWithTag("bottom-bar-qam").assertIsDisplayed().performClick() + assertEquals(listOf("steam", "menu", "qam"), actions) + } + + @Test fun unfoldedPadKeepsTheDrawerReachableOutsideSteam() { + var drawerOpened = false + compose.setContent { DroidDeckTheme { PadKeys(false, { drawerOpened = true }, {}, {}) } } + compose.onNodeWithTag("bottom-bar-steam").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-qam").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-menu").assertIsDisplayed().performClick() + assertTrue(drawerOpened) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenImeTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenImeTest.kt new file mode 100644 index 0000000000..d88af65090 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenImeTest.kt @@ -0,0 +1,177 @@ +package com.droiddeck.launcher.ui + +import androidx.activity.ComponentActivity +import android.hardware.display.DisplayManager +import android.os.Looper +import android.view.Display +import android.view.KeyEvent +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection +import com.droiddeck.launcher.SessionActivity +import com.droiddeck.launcher.input.KeyboardHost +import com.droiddeck.launcher.input.SecondScreenMode +import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.wayland.WaylandCompositor +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.android.controller.ActivityController +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.util.ReflectionHelpers +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w800dp-h600dp", shadows = [SecondScreenImeTest.CompositorShadow::class]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class SecondScreenImeTest { + private var previousMode = "" + private var previousDeckPad = false + + @Before fun setUp() { + previousMode = SessionState.mode + previousDeckPad = SessionState.deckPad + SessionState.deckPad = false + CompositorShadow.commits.clear() + } + + @After fun tearDown() { + SessionState.mode = previousMode + SessionState.deckPad = previousDeckPad + } + + @Test fun editorActionClosesFieldKeyboardAfterOneCommit() { + var closes = 0 + val fixture = keyboard(forField = true) { closes++ } + try { + assertTrue(fixture.connection.performEditorAction(EditorInfo.IME_ACTION_SEND)) + idle() + + assertEquals(listOf("\r"), CompositorShadow.commits) + assertEquals(1, closes) + assertFalse(fixture.host.shown) + assertFalse(fixture.panel.fieldKeyboardOpen) + } finally { + fixture.close() + } + } + + @Test fun unmodifiedEnterKeyClosesFieldKeyboard() { + var closes = 0 + val fixture = keyboard(forField = true) { closes++ } + try { + assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))) + assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP))) + idle() + + assertEquals(listOf("\r"), CompositorShadow.commits) + assertEquals(1, closes) + assertFalse(fixture.host.shown) + assertFalse(fixture.panel.fieldKeyboardOpen) + } finally { + fixture.close() + } + } + + @Test fun ordinaryTextAndNewlineLeaveFieldKeyboardOpen() { + var closes = 0 + val fixture = keyboard(forField = true) { closes++ } + try { + assertTrue(fixture.connection.commitText("hello", 1)) + assertTrue(fixture.connection.commitText("line\n", 1)) + idle() + + assertEquals(listOf("hello", "line\n"), CompositorShadow.commits) + assertEquals(0, closes) + assertTrue(fixture.host.shown) + assertTrue(fixture.panel.fieldKeyboardOpen) + } finally { + fixture.close() + } + } + + @Test fun enterLeavesNonFieldKeyboardOpen() { + var closes = 0 + val fixture = keyboard(forField = false) { closes++ } + try { + assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))) + assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP))) + idle() + + assertEquals(listOf("\r"), CompositorShadow.commits) + assertEquals(0, closes) + assertTrue(fixture.host.shown) + assertFalse(fixture.panel.fieldKeyboardOpen) + } finally { + fixture.close() + } + } + + private fun keyboard(forField: Boolean, onClosed: () -> Unit): Fixture { + val activity = Robolectric.buildActivity(SessionActivity::class.java).get() + val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY) + val panel = SecondScreenPresentation(activity, display, {}, {}, {}, onKeyboardClosed = onClosed) + panel.show() + panel.showMode(SecondScreenMode.CUSTOM_CONTROLS) + panel.requestKeyboard(forField) + val host: KeyboardHost = ReflectionHelpers.getField(panel, "keyboardHost") + val root: View = ReflectionHelpers.getField(panel, "root") + val owner = Robolectric.buildActivity(ComponentActivity::class.java).setup() + try { + (root.parent as ViewGroup).removeView(root) + owner.get().setContentView(root) + host.show() + idle() + assertTrue("Presentation root is not attached to window after host.show()", root.isAttachedToWindow) + assertTrue(host.shown) + val connection = host.onCreateInputConnection(EditorInfo()) + assertNotNull(connection) + return Fixture(panel, host, connection!!, owner) + } catch (t: Throwable) { + panel.closeControls() + owner.pause().stop().destroy() + throw t + } + } + + private fun keyEvent(action: Int) = KeyEvent(0L, 0L, action, KeyEvent.KEYCODE_ENTER, 0) + + private fun idle() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(50)) + + private data class Fixture( + val panel: SecondScreenPresentation, + val host: KeyboardHost, + val connection: InputConnection, + val owner: ActivityController, + ) { + fun close() { + panel.closeControls() + owner.pause().stop().destroy() + } + } + + @Implements(WaylandCompositor::class, isInAndroidSdk = false) + class CompositorShadow { + companion object { + val commits = mutableListOf() + + @JvmStatic @Implementation fun __staticInitializer__() {} + + @JvmStatic @Implementation fun textInputCommit(text: String) { + commits += text + } + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt new file mode 100644 index 0000000000..0de1726e21 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt @@ -0,0 +1,232 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.width +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.input.InputModeManager +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsFocused +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.click +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipe +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performSemanticsAction +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.Lossless +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@OptIn(ExperimentalTestApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class SessionControlDesignTest { + @get:Rule val compose = createRobolectricComposeRule() + + private val engineAnchor get() = compose.onNodeWithTag("setting-frame-generation-engine") + private fun engine(name: String) = compose.onNodeWithTag("framegen-engine:$name") + private fun zoom(name: String) = compose.onNodeWithTag("game-zoom-$name") + private fun zoomValue(value: Int) = zoom("value").assertTextEquals("$value%") + + @Test + fun enginePickerStartsOnSelectionSkipsUnavailableEngineAndRestoresFocus() { + val mode = mutableStateOf(FrameGen.Mode(FrameGen.ENGINE_DDFG, 3)) + lateinit var input: InputModeManager + compose.setContent { + DroidDeckTheme { + input = LocalInputModeManager.current + Box(Modifier.width(300.dp)) { + FrameGenMenu(mode.value, Lossless.State.NONE, { mode.value = it }, sessionHost = rememberMenuHost()) + } + } + } + + compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } + engineAnchor.performSemanticsAction(SemanticsActions.RequestFocus) + engineAnchor.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + compose.mainClock.advanceTimeByFrame() + engine(FrameGen.ENGINE_LSFG).assertIsNotEnabled() + engine(FrameGen.ENGINE_DDFG).assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } + engine(FrameGen.ENGINE_OFF).assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } + engine(FrameGen.ENGINE_DDFG).assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } + engine(FrameGen.ENGINE_ZEROFG).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + compose.mainClock.advanceTimeByFrame() + engine(FrameGen.ENGINE_ZEROFG).assertDoesNotExist() + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), mode.value) + engineAnchor.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + compose.mainClock.advanceTimeByFrame() + engine(FrameGen.ENGINE_ZEROFG).assertIsFocused().performKeyInput { pressKey(Key.ButtonB) } + compose.mainClock.advanceTimeByFrame() + engine(FrameGen.ENGINE_ZEROFG).assertDoesNotExist() + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), mode.value) + engineAnchor.assertIsFocused() + } + + @Test + fun gameOverrideCanReturnToGlobalWithoutLosingControllerFocus() { + val override = mutableStateOf(true) + lateinit var input: InputModeManager + compose.setContent { + DroidDeckTheme { + input = LocalInputModeManager.current + FrameGenMenu( + mode = if (override.value) FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 2) else FrameGen.Mode.OFF, + lossless = Lossless.State.NONE, + onPick = {}, + gameProfileId = "8400", + hasGameOverride = override.value, + onResetGame = { override.value = false }, + sessionHost = rememberMenuHost(), + ) + } + } + compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } + val reset = compose.onNodeWithTag("framegen-use-global") + reset.assertTextEquals("Use global setting").performSemanticsAction(SemanticsActions.RequestFocus) + reset.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + reset.assertDoesNotExist() + engineAnchor.assertIsFocused() + } + + @Test + fun frameGenButtonsMoveTheDrawerFocusRing() { + lateinit var input: InputModeManager + lateinit var glide: FocusGlide + compose.setContent { + DroidDeckTheme { + FocusGlideHost { + input = LocalInputModeManager.current + glide = checkNotNull(LocalFocusGlide.current) + FrameGenMenu( + mode = FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 2), + lossless = Lossless.State.NONE, + onPick = {}, + gameProfileId = "8400", + hasGameOverride = true, + sessionHost = rememberMenuHost(), + ) + } + } + } + compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } + var previous: GlideSource? = null + for (label in listOf("2×", "3×", "4×", "ZeroPacer", "Use global setting")) { + val button = if (label == "ZeroPacer") compose.onNodeWithText(label, substring = true) + else compose.onNodeWithText(label) + button.performSemanticsAction(SemanticsActions.RequestFocus).assertIsFocused() + compose.runOnIdle { + assertNotNull("Missing focus ring for $label", glide.current) + assertNotSame("Focus ring did not move to $label", previous, glide.current) + previous = glide.current + } + } + } + + @Test + fun legacyFrameGenerationStillUsesTheFlatOptions() { + compose.setContent { + DroidDeckTheme { + FrameGenMenu(FrameGen.Mode.OFF, Lossless.State.NONE, {}, legacyButtons = true) + } + } + engineAnchor.assertDoesNotExist() + compose.onNodeWithText("ZeroFG 2×").assertExists() + } + + @Test + fun zoomStepsBy25PercentAndDpadCanLeaveIt() { + val value = mutableStateOf(1f) + val changes = mutableListOf() + lateinit var input: InputModeManager + compose.setContent { + DroidDeckTheme { + input = LocalInputModeManager.current + Column(Modifier.width(300.dp)) { + OutlinedButton(onClick = {}, modifier = Modifier.fillMaxWidth().testTag("above")) { Text("Above") } + GameZoomRow(value.value, { Modifier }) { changes += it; value.value = it } + OutlinedButton(onClick = {}, modifier = Modifier.fillMaxWidth().testTag("below")) { Text("Below") } + } + } + } + + compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } + val slider = zoom("slider") + zoomValue(100) + zoom("reset").assertDoesNotExist() + slider.performSemanticsAction(SemanticsActions.RequestFocus) + slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionLeft) } + zoomValue(100) + assertEquals(emptyList(), changes) + slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } + compose.onNodeWithTag("above").assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } + slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } + compose.onNodeWithTag("below").assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } + slider.assertIsFocused() + + for (percent in 125..300 step 25) { + slider.performKeyInput { pressKey(Key.DirectionRight) } + zoomValue(percent) + slider.assertIsFocused() + } + slider.performKeyInput { pressKey(Key.DirectionRight) } + zoomValue(300) + assertEquals((125..300 step 25).map { it / 100f }, changes) + slider.performKeyInput { pressKey(Key.DirectionLeft) } + zoomValue(275) + zoom("reset").assertDoesNotExist() + slider.performKeyInput { pressKey(Key.DirectionDown) } + compose.onNodeWithTag("below").assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } + slider.assertIsFocused() + for (percent in 250 downTo 100 step 25) { + slider.performKeyInput { pressKey(Key.DirectionLeft) } + zoomValue(percent) + } + } + + @Test + fun touchTapAndDragSnapToTheNineValues() { + val value = mutableStateOf(1f) + val changes = mutableListOf() + compose.setContent { + DroidDeckTheme { + Box(Modifier.width(300.dp)) { + GameZoomRow(value.value, { Modifier }) { changes += it; value.value = it } + } + } + } + val slider = zoom("slider").assertIsDisplayed() + slider.performTouchInput { click(center) } + zoomValue(200) + slider.performTouchInput { swipe(center, Offset(width - 2f, center.y)) } + zoomValue(300) + slider.performTouchInput { click(Offset(2f, center.y)) } + zoomValue(100) + val allowed = (100..300 step 25).map { it / 100f }.toSet() + assertEquals(true, changes.all { it in allowed }) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index 18911a3521..ad54fdd9eb 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -4,60 +4,63 @@ import org.junit.Assert.* import org.junit.Test class SessionDrawerPageTest { - @Test fun navigationStartsWithControllerAndGoesStraightToDisplay() { + @Test fun navigationRunsControllerPerformanceFrameGenDisplayEffectsGameSessionMore() { val pages = sessionDrawerPages(hasAgent = false) - assertEquals(SessionDrawerPage.CONTROLLER, pages.first()) - assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1)) - assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1)) - assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) - assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) - assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1)) - assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1)) + assertEquals(DrawerPages.arrange(emptyList()).strip(), pages.strip()) + assertEquals( + listOf(SessionDrawerPage.CONTROLLER, SessionDrawerPage.HUD, SessionDrawerPage.FRAMEGEN, + SessionDrawerPage.DISPLAY, SessionDrawerPage.EFFECTS, SessionDrawerPage.GAMES, + SessionDrawerPage.SESSION, SessionDrawerPage.MORE), + pages.strip(), + ) + assertEquals(SessionDrawerPage.MORE, pages.strip().step(SessionDrawerPage.CONTROLLER, -1)) } - @Test fun moreKeepsSteamVrByDefaultAndStandsInForThePagesInsideIt() { - val pages = sessionDrawerPages(hasAgent = false) - assertEquals(listOf(SessionDrawerPage.VR), pages.inMore()) - assertEquals(SessionDrawerPage.MORE, pages.strip().last()) - assertFalse(SessionDrawerPage.VR in pages.strip()) + @Test fun vrAchievementsAndTheAgentStartInsideMore() { + val pages = sessionDrawerPages(hasAchievements = true, hasAgent = true) + assertEquals(listOf(SessionDrawerPage.VR, SessionDrawerPage.ACHIEVEMENTS, SessionDrawerPage.AGENT), pages.inMore()) assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR)) + assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.ACHIEVEMENTS)) assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES)) val strip = pages.strip() - assertEquals(SessionDrawerPage.MORE, strip.step(SessionDrawerPage.SESSION, 1)) - assertEquals(SessionDrawerPage.CONTROLLER, strip.step(SessionDrawerPage.MORE, 1)) - assertEquals(SessionDrawerPage.SESSION, strip.step(pages.tabFor(SessionDrawerPage.VR), -1)) + assertEquals(SessionDrawerPage.CONTROLLER, strip.step(pages.tabFor(SessionDrawerPage.AGENT), 1)) + } + + @Test fun achievementsAreOfferedOnlyForAGameThatHasThem() { + assertFalse(SessionDrawerPage.ACHIEVEMENTS in sessionDrawerPages(hasAchievements = false, hasAgent = false)) + assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false)) + assertEquals(listOf(SessionDrawerPage.VR), sessionDrawerPages(hasAgent = false).inMore()) } @Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() { - val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION") + val saved = listOf("CONTROLLER", "GLASSES", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION") val out = DrawerPages.arrange(saved) + assertEquals(SessionDrawerPage.entries.toSet(), out.toSet()) assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1]) - assertTrue(out.indexOf(SessionDrawerPage.VR) < out.indexOf(SessionDrawerPage.EFFECTS) + 2) - assertTrue(out.inMore().isEmpty()) + assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS), out.inMore()) + assertTrue(SessionDrawerPage.AGENT in out.strip()) + assertTrue(SessionDrawerPage.VR in out.strip()) + } + + @Test fun aSavedLayoutCanKeepVrOnTheTabStrip() { + val saved = listOf("CONTROLLER", "HUD", "VR", "FRAMEGEN", "DISPLAY", "EFFECTS", + "GAMES", "SESSION", "MORE", "ACHIEVEMENTS", "AGENT") + val out = DrawerPages.arrange(saved) + assertEquals(saved, out.map { it.name }) + assertEquals(SessionDrawerPage.VR, out.tabFor(SessionDrawerPage.VR)) } @Test fun sessionCanBeKeptInsideMore() { val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "GAMES", "AGENT", "MORE", "SESSION", "VR") val out = DrawerPages.arrange(saved) - assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore()) + assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS, SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore()) assertFalse(SessionDrawerPage.SESSION in out.strip()) } @Test fun moreAndSessionCannotBeHidden() { assertFalse(DrawerPages.hideable(SessionDrawerPage.MORE)) - } - - @Test fun glassesAddTheirPageAfterController() { - val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false) - assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1)) - assertEquals(sessionDrawerPages(hasAgent = false), pages.filter { it != SessionDrawerPage.GLASSES }) - } - - @Test fun theAgentPageComesBeforeSessionOnlyWhenTheTabIsShown() { - val with = sessionDrawerPages(hasAgent = true) - assertEquals(SessionDrawerPage.AGENT, with.step(SessionDrawerPage.GAMES, 1)) - assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1)) - assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false)) + assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION)) + assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD)) } @Test fun arrangeKeepsSavedOrderAndSlotsNewPagesAfterTheirNeighbour() { @@ -67,9 +70,4 @@ class SessionDrawerPageTest { assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD), out.filter { it in setOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD) }) assertTrue(out.indexOf(SessionDrawerPage.HUD) < out.indexOf(SessionDrawerPage.CONTROLLER)) } - - @Test fun sessionPageCannotBeHidden() { - assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION)) - assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD)) - } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt index c45b32d234..da99b2f8a9 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -12,11 +12,13 @@ import android.widget.TextView import androidx.compose.ui.test.* import androidx.compose.ui.semantics.SemanticsProperties.StateDescription import androidx.compose.runtime.MutableState +import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.geometry.Offset import com.droiddeck.launcher.R import com.droiddeck.launcher.SessionActivity import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.gpu.Lossless +import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.input.PadBridgeRoutingTest @@ -93,6 +95,22 @@ class SessionSecondScreenTest { assertEquals(SecondScreenMode.CUSTOM_CONTROLS, selected) } + @Test fun onScreenOpacitySliderExposesTheRangeAndUpdatesTheLiveSetting() { + val changed = mutableListOf() + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, + actions(true, emptyList(), controller = ControllerPrefs.read(context), onOpacity = { changed += it })) + } + } + val open = compose.runOnIdle { DrawerSectionState.isOpen("controller-osc") } + if (!open) compose.onNodeWithTag("drawer-section-controller-osc").performScrollTo().performClick() + val slider = compose.onNodeWithTag("controller-opacity").performScrollTo() + slider.assertIsDisplayed().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(0f) } + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(45f) } + assertEquals(listOf(10, 45), changed) + } + @Test fun desktopWithoutASecondDisplayHasNoScreenPicker() { SessionState.mode = SessionService.MODE_DESKTOP compose.setContent { @@ -130,10 +148,45 @@ class SessionSecondScreenTest { actions(true, listOf(SecondScreenDisplay(1, "Bottom screen"), SecondScreenDisplay(2, "Monitor")), gameSwap = true)) } } + compose.onNodeWithText(context.getString(R.string.swap_game_screen)).assertDoesNotExist() + compose.openSection("display-second") compose.onNodeWithText(context.getString(R.string.swap_game_screen)).performScrollTo().assertIsDisplayed() compose.onNodeWithText("Bottom screen").performScrollTo().assertIsDisplayed() } + @Test fun steamDisplayCanChooseTopAndBottomLive() { + SessionState.mode = SessionService.MODE_STEAM + val position = mutableStateOf("center") + val choices = mutableListOf() + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.DISPLAY, false, {}, actions( + true, emptyList(), picturePosition = position.value, + onPicturePosition = { choices += it; position.value = it }, + )) + } + } + compose.openSection("display") + val picker = compose.onNodeWithTag("setting-picture-position") + picker.performScrollTo().assert(hasText(context.getString(R.string.display_position_center))).performClick() + compose.onNodeWithText(context.getString(R.string.display_position_top)).performClick() + picker.assert(hasText(context.getString(R.string.display_position_top))).performClick() + compose.onNodeWithText(context.getString(R.string.display_position_bottom)).performClick() + picker.assert(hasText(context.getString(R.string.display_position_bottom))) + assertEquals(listOf("top", "bottom"), choices) + } + + @Test fun desktopDisplayDoesNotOfferSteamPicturePosition() { + SessionState.mode = SessionService.MODE_DESKTOP + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.DISPLAY, false, {}, actions(false, emptyList())) + } + } + compose.openSection("display") + compose.onNodeWithTag("setting-picture-position").assertDoesNotExist() + } + @Test fun provisionalBottomScreenPanelSettlesOnlyOnceTheSessionIsInFront() { SessionState.mode = SessionService.MODE_STEAM val previousMode = SessionState.secondScreenMode @@ -265,7 +318,7 @@ class SessionSecondScreenTest { state("drawerOpenState").value = true state("drawerControllerActive").value = true state>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen")) - for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.DISPLAY, + for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.HUD, KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) { assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0, device.id, 0, 0, InputDevice.SOURCE_GAMEPAD))) @@ -309,6 +362,7 @@ class SessionSecondScreenTest { actions(true, emptyList(), micAvailable = true, micEnabled = true, onMic = changes::add)) } } + compose.openSection("session-behavior") compose.onNodeWithTag("setting-microphone").assertIsEnabled() .assert(SemanticsMatcher.expectValue(StateDescription, context.getString(R.string.widgets_on))).performClick() assertEquals(listOf(false), changes) @@ -322,6 +376,7 @@ class SessionSecondScreenTest { actions(true, emptyList(), micAvailable = true, onMic = changes::add)) } } + compose.openSection("session-behavior") compose.onNodeWithTag("setting-microphone").assertIsEnabled() .assert(SemanticsMatcher.expectValue(StateDescription, context.getString(R.string.widgets_off))).performClick() assertEquals(listOf(true), changes) @@ -333,6 +388,7 @@ class SessionSecondScreenTest { SessionDrawer(true, SessionDrawerPage.SESSION, false, {}, actions(false, emptyList())) } } + compose.openSection("session-behavior") compose.onNodeWithTag("setting-microphone").assertDoesNotExist() compose.onNodeWithText(context.getString(R.string.mode_mic)).assertDoesNotExist() } @@ -354,6 +410,7 @@ class SessionSecondScreenTest { onInputSelection = { panel.refreshControls() }, onClose = { open.value = false })) } } + compose.openSection("controller-input") compose.onNodeWithTag("setting-input-profile").performScrollTo().performClick() compose.onNodeWithText("Desktop").performScrollTo().performClick() compose.onNodeWithTag("input-profile-expand").performScrollTo().performClick() @@ -402,15 +459,19 @@ class SessionSecondScreenTest { micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {}, desktop: Boolean = !steam, direct: Boolean = false, onInputSelection: (InputRole?) -> Unit = {}, onClose: () -> Unit = {}, mode: SecondScreenMode = SecondScreenMode.NONE, gameSwap: Boolean = false, + picturePosition: String = "center", onPicturePosition: (String) -> Unit = {}, + controller: ControllerPrefs.Settings? = null, onOpacity: (Int) -> Unit = {}, select: (SecondScreenMode) -> Unit = {}) = DrawerActions(steam = steam, desktop = desktop, direct = direct, onInputSelection = onInputSelection, + picturePosition = picturePosition, onPicturePosition = onPicturePosition, isHomeApp = false, androidApps = emptyList(), hudOn = false, + controller = controller, onControllerOpacity = onOpacity, micAvailable = micAvailable, micEnabled = micEnabled, onMicEnabled = onMic, frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never", suspendPolicy = "auto", backActionsInverted = false, touchMode = "auto", touchAuto = "trackpad", fexPreset = "default", secondScreenMode = mode, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1, gameSwapAvailable = gameSwap, - onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, + onHud = {}, onFrameGenPick = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {}, onTouch = {}, onFexPreset = {}, onSecondScreenMode = select, onSecondScreenDisplay = {}, onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = onClose) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SourceTabMenuTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SourceTabMenuTest.kt new file mode 100644 index 0000000000..62d3463b7f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SourceTabMenuTest.kt @@ -0,0 +1,79 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreTab +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class) +class SourceTabMenuTest { + @get:Rule val compose = createRobolectricComposeRule() + + private fun showLibrary(width: Int = 360) { + compose.setContent { + DroidDeckTheme { + var source by remember { mutableStateOf(LIBRARY_ALL) } + Box(Modifier.width(width.dp)) { + LibraryFilters(listOf(Library.SOURCE_STEAM, Store.EPIC.id), source, { source = it }, manage = true) + } + } + } + } + + @Test fun portraitLibraryPicksASourceAndKeepsManageVisible() { + showLibrary() + compose.onNodeWithTag("library-manage-stores").assertIsDisplayed() + val menu = compose.onNodeWithTag("tab-menu") + menu.assert(hasText("All")).performClick() + compose.onNodeWithTag("tab-menu:2").assertIsDisplayed().performClick() + menu.assert(hasText(Store.EPIC.shortLabel)) + } + + @Test @Config(qualifiers = "w900dp-h500dp-land") + fun wideLandscapeLibraryKeepsTheChips() { + showLibrary(width = 740) + compose.onNodeWithTag("tab-menu").assertDoesNotExist() + compose.onNodeWithTag("library-source-epic").assertIsDisplayed() + } + + @Test @Config(qualifiers = "w900dp-h500dp-land") + fun narrowLibraryPaneUsesTheMenuEvenInLandscape() { + showLibrary(width = 270) + compose.onNodeWithTag("tab-menu").assertIsDisplayed() + } + + @Test fun portraitStoreUsesTheMenuEvenWithOnlyTwoVisibleStores() { + compose.setContent { + DroidDeckTheme { + var selected by remember { mutableStateOf(Store.EPIC.id) } + StoreChips( + selected, null, listOf(StoreTab(Store.EPIC, true), StoreTab(Store.GOG, true), StoreTab(Store.EA, false)), + onStore = { selected = it.id }, onSettings = {}, onFocusChip = {}, + ) + } + } + val menu = compose.onNodeWithTag("tab-menu") + menu.assert(hasText(Store.EPIC.shortLabel)).performClick() + compose.onNodeWithTag("tab-menu:2").assertDoesNotExist() + compose.onNodeWithTag("tab-menu:1").assertIsDisplayed().performClick() + menu.assert(hasText(Store.GOG.shortLabel)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt index f4c4688f4a..1f30f896af 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt @@ -99,7 +99,7 @@ class SteamHomeHeadsetTest { onPlay = {}, onPlaySteamVr = { vrStarts++ }, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt index 97f5c16ae9..f2afa15029 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt @@ -143,7 +143,7 @@ class StoreRestorationTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorInputTest.kt b/app/src/test/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorInputTest.kt new file mode 100644 index 0000000000..12811f8d54 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorInputTest.kt @@ -0,0 +1,122 @@ +package com.droiddeck.launcher.wayland + +import android.app.Application +import android.content.Intent +import android.os.Bundle +import android.os.Looper +import android.os.Message +import android.os.Messenger +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = Application::class, shadows = [BottomDesktopCompositorInputTest.CompositorShadow::class]) +class BottomDesktopCompositorInputTest { + @Before fun setUp() { + CompositorShadow.calls.clear() + } + + @Test fun chineseTextThenEnterUsesTheOrderedHostQueue() { + withService { messenger -> + messenger.send(text("中文输入")) + messenger.send(key(KEY_ENTER, PRESSED)) + messenger.send(key(KEY_ENTER, RELEASED)) + idle() + + assertEquals(listOf("text:中文输入", "key:28:1", "key:28:0"), CompositorShadow.calls) + assertTrue(CompositorShadow.calls.none { it.startsWith("unordered") }) + } + } + + @Test fun editingKeysAndTextShareOneOrderedQueue() { + withService { messenger -> + messenger.send(text("ab")) + messenger.send(key(KEY_BACKSPACE, PRESSED)) + messenger.send(key(KEY_BACKSPACE, RELEASED)) + messenger.send(key(KEY_DELETE, PRESSED)) + messenger.send(key(KEY_DELETE, RELEASED)) + messenger.send(key(KEY_TAB, PRESSED)) + messenger.send(key(KEY_TAB, RELEASED)) + messenger.send(text("cd")) + messenger.send(key(KEY_DOWN, PRESSED)) + messenger.send(key(KEY_DOWN, RELEASED)) + messenger.send(key(KEY_UP, PRESSED)) + messenger.send(key(KEY_UP, RELEASED)) + idle() + + assertEquals( + listOf( + "text:ab", + "key:14:1", "key:14:0", + "key:111:1", "key:111:0", + "key:15:1", "key:15:0", + "text:cd", + "key:108:1", "key:108:0", + "key:103:1", "key:103:0", + ), + CompositorShadow.calls, + ) + assertTrue(CompositorShadow.calls.none { it.startsWith("unordered") }) + } + } + + private fun withService(block: (Messenger) -> Unit) { + val controller = Robolectric.buildService(BottomDesktopCompositorService::class.java).create() + try { + val messenger = Messenger(controller.get().onBind(Intent())) + block(messenger) + } finally { + controller.destroy() + } + } + + private fun text(value: String) = Message.obtain(null, BottomDesktopCompositorService.MSG_TEXT).apply { + data = Bundle().apply { putString(BottomDesktopCompositorService.KEY_TEXT, value) } + } + + private fun key(code: Int, state: Int) = + Message.obtain(null, BottomDesktopCompositorService.MSG_KEY, code, state) + + private fun idle() = shadowOf(Looper.getMainLooper()).idle() + + companion object { + private const val KEY_ENTER = 28 + private const val KEY_BACKSPACE = 14 + private const val KEY_DELETE = 111 + private const val KEY_TAB = 15 + private const val KEY_DOWN = 108 + private const val KEY_UP = 103 + private const val PRESSED = 1 + private const val RELEASED = 0 + } + + @Implements(WaylandCompositor::class, isInAndroidSdk = false) + class CompositorShadow { + companion object { + val calls = mutableListOf() + + @JvmStatic @Implementation fun __staticInitializer__() {} + + @JvmStatic @Implementation fun textInputCommit(text: String) { + calls += "text:$text" + } + + @JvmStatic @Implementation fun nativeSendKey(evdev: Int, state: Int) { + calls += "unordered:$evdev:$state" + } + + @JvmStatic @Implementation fun nativeSendKeyOrdered(evdev: Int, state: Int) { + calls += "key:$evdev:$state" + } + } + } +} diff --git a/docs/agent-control.md b/docs/agent-control.md index ac097234cf..6cce0e77df 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -258,8 +258,10 @@ and `--rate` (120 samples a second); `--pressure` and tilt take `FROM:TO` ranges `--tilt-x=-30:30` when they start negative. A gesture lasts at most 30 s. `UINPUT_UNAVAILABLE` means the shell has no `uinput` or cannot write `/dev/uinput`, `NO_VIEWPORT` that there is no internal display or it is off, and `UINPUT_FAILED` that `uinput` stopped early; all three exit 3. -It needs Android 14 QPR2 or later: the `uinput` of Android 12 to 14 QPR1 takes only numeric codes -and the USB or Bluetooth bus, so there the pen ends with `UINPUT_FAILED`. +The `uinput` of Android 12 to 14 QPR1 takes only numeric codes, the USB or Bluetooth bus and no +`sync` command. Below SDK 34 the pen and the gamepad send that form, with the pen on the USB bus, +and success is a clean exit. On SDK 34, which spans both sides of QPR2, the named form goes first +and is resent in that form when `uinput` rejects it before registering the device. ## State (schema 2) diff --git a/docs/compose-previews.md b/docs/compose-previews.md index 1aa5059563..a91a35d37f 100644 --- a/docs/compose-previews.md +++ b/docs/compose-previews.md @@ -24,7 +24,9 @@ ways: | `app/src/testDebug/.../ui/PreviewRenderTest.kt` | The render test | Previews cover the launcher on each tab (Steam, Library, Library with no games, Stores, Downloads, Settings, Settings with -no runtime) and the in-game menu's pages (Controller, Display, HUD, Session, and the Desktop menu). +no runtime), the in-game menu's pages (Controller, Display, HUD, Session, and the Desktop menu), and the frosted +background: the Steam and Library tabs, Settings with frosted cards and with both transparencies at 100 %, and a +settings step opened over frosted page text. ## Adding one diff --git a/docs/development/bottom-screen.md b/docs/development/bottom-screen.md index ba0ce9d065..64758abe32 100644 --- a/docs/development/bottom-screen.md +++ b/docs/development/bottom-screen.md @@ -181,8 +181,10 @@ Plugin loaders expose Steam's CEF DevTools so the menu can be viewed in a deskto - The menu's browser view is placed just outside the Big Picture window through its own `SetBounds`, so it keeps rendering but never shows on top, including while Steam slides it wider for Friends and chat. The view is also given the panel's shape (about 712 × 463 instead of Steam's 856 × 463), so every tab shows at one scale. In Full width, a style on the menu page also lifts Steam's 300 px cap on each tab, so every tab fills the panel and Friends shows its list and chat side by side. - A timer inside Steam keeps this state every 250 ms, so the menu comes back, on the tab it was showing, as soon as Steam's main menu or a full-screen page such as Decky's store closes. It runs on a 5 s lease that the panel renews each second: if the app stops, Steam returns to normal by itself. - The hold starts only once the session is ready: holding the menu before Steam's first frame kept gamescope from presenting anything. -- `droiddeck-qam-relay` relays the app to the DevTools port, which only answers clients inside the guest. The panel streams the menu with `Page.startScreencast`, scales its content to the panel and fills the rest with the menu's own background, and forwards touches on the menu with `Input.dispatchTouchEvent`. A layout button in the panel's bar cycles Full width (every tab stretched to the panel), Left, Center and Right (Steam's own narrow tabs, placed on that side); the choice is kept. Returning to the panel shows the last frame at once while the stream reconnects, and the first frame after a cold start takes about 1.4 s. +- `droiddeck-qam-relay` relays the app to the DevTools port, which only answers clients inside the guest. The panel streams the menu with `Page.startScreencast`, scales its content to the panel and fills the rest with the menu's own background, and forwards touches on the menu with `Input.dispatchTouchEvent`. A layout button in the panel's bar cycles Full width (every tab stretched to the panel), Left, Center and Right (Steam's own narrow tabs, placed on that side) and Split (below); the choice is kept. Returning to the panel shows the last frame at once while the stream reconnects, and the first frame after a cold start takes about 1.4 s. - The Quick Access button still shows the menu on the top screen, in Steam's own layout and with the controller; closing it there (B or the button again) returns it to the bottom screen on the same tab. +- The Split layout puts Steam's main menu (the Steam button's menu) on the left and Quick Access on the right. Both are laid out 480 CSS pixels tall so they show at one scale: the main menu at Steam's own 240 px width with its rows spread over the full height, Quick Access across the rest. Steam keeps one side menu open at a time and slides the other out, so the main menu's view is kept visible, parked beside Quick Access's, and a style on its page holds it in place. Steam's views carry no names: the main menu's is the one Steam focuses while the main menu is open, so after Steam starts the panel opens it once, parked before it is drawn. Taps on either half go to that menu; in a game, the running game's card at the top of the main menu returns to it. The Steam button still shows the main menu on the top screen in Steam's own layout, and closing it returns both menus to the bottom. Checked on the AYN Thor in Big Picture and in Bomb Rush Cyberfunk, with the game keeping focus. +- Only Quick Access's own view is parked: the one Steam focuses while Quick Access is open. Store and other web pages live in another view, which keeps the bounds Steam gives it, and Steam's frosted glass over the Store page is left off while the menu is parked rather than over it. - Leaving the panel closes the menu and turns the patches off; the Steam button and the normal Quick Access button then work as before. Opening Steam's main menu replaces the Quick Access menu for as long as it is open, as on a Deck. Checked with Decky Loader 3.3.1 enabled: its tab renders and takes touch, and its store opens full screen on top with the controller, then returns to the Decky tab below. Decky hooks the menu after Steam starts, so the panel reopens it once when that happens. @@ -201,6 +203,10 @@ Limits: it relies on Steam's minified UI stores and method names, so a client up | --- | --- | | ![Quick Access in the centred layout](evidence/bottom-screen-qam-center-2026-11-27.png) | ![Quick Access in the right-aligned layout](evidence/bottom-screen-qam-right-2026-11-27.png) | +| Layout: Split | Split, in a game | +| --- | --- | +| ![Steam's main menu and Quick Access side by side on the bottom screen](evidence/bottom-screen-qam-split-2026-11-30.png) | ![The split layout during a game, with the game's card at the top of the main menu](evidence/bottom-screen-qam-split-ingame-2026-11-30.png) | + The top screen during that game, with the menu open on the bottom: ![Top screen during the game, with nothing drawn over it](evidence/bottom-screen-qam-top-ingame-2026-11-27.png) ## Related fixes diff --git a/docs/development/dd-fg.md b/docs/development/dd-fg.md index 81cb43a9ea..1275b18758 100644 --- a/docs/development/dd-fg.md +++ b/docs/development/dd-fg.md @@ -27,6 +27,28 @@ bytes for dimensions at least four pixels: These are pixel payloads, not driver allocation sizes or measured FPS gains. +## Scratch ownership and rebuilds + +Each `FrameGen` instance owns its scratch buffers, mappings and descriptor sets. +A size or live-preset rebuild first confirms GPU completion and resets that +instance's descriptor pool, then releases the old scratch and image resources. +Motion/history validity is reset with the rebuilt images. Repeated preparation +at the same size and ordinary frame recording do not add device-idle waits. + +Healthy destruction releases the descriptor pool, mapped scratch buffers and +images. The native engine releases its input ring only after the chain confirms +completion, so an input image is not destroyed before the wait. + +If `vkDeviceWaitIdle` fails with an error other than +`VK_ERROR_DEVICE_LOST`, the affected instance becomes unusable: further +recording and rebuilding stop, and its Vulkan resources and input ring are +intentionally retained because GPU completion is unknown. Device loss follows +a separate teardown path: `FrameGen::destroy()` releases its owned resources +without another wait and returns true, allowing the Engine to release the +input ring. This is local DD-FG containment, not compositor-wide GPU recovery. +A descriptor-pool reset failure also stops that resize without releasing the +resources, but healthy teardown can still release them. + ## Validation Run `python3 -m unittest discover -s tools/tests -p 'test_ddfg_flow_levels.py'`. @@ -35,4 +57,10 @@ selected through the usual SDK/NDK environment variables. It compiles the actual DD-FG chain against a mock Vulkan dispatch table and checks resource counts, dispatch order and sizes, valid descriptor bindings, both models, every preset, 2x/3x/4x generation, small/odd extents, resize and live preset changes. +The same harness enforces descriptor-pool capacity, accounts for all live +resources, and models pending GPU work to reject early cleanup. Lifecycle cases +cover repeated rebuilds, same-size restarts, two simultaneous instances, +automatic/idempotent destruction, partial resize allocation, failed GPU waits, +and failed descriptor-pool resets. The actual native `Engine` is included to +check the input-ring destruction order. It does not execute shaders on a GPU or replace on-device validation. diff --git a/docs/development/evidence/bottom-screen-qam-split-2026-11-30.png b/docs/development/evidence/bottom-screen-qam-split-2026-11-30.png new file mode 100644 index 0000000000..ad035be63a Binary files /dev/null and b/docs/development/evidence/bottom-screen-qam-split-2026-11-30.png differ diff --git a/docs/development/evidence/bottom-screen-qam-split-ingame-2026-11-30.png b/docs/development/evidence/bottom-screen-qam-split-ingame-2026-11-30.png new file mode 100644 index 0000000000..ba62689cab Binary files /dev/null and b/docs/development/evidence/bottom-screen-qam-split-ingame-2026-11-30.png differ diff --git a/docs/development/framegen-post-upscale.md b/docs/development/framegen-post-upscale.md new file mode 100644 index 0000000000..dcec8257f0 --- /dev/null +++ b/docs/development/framegen-post-upscale.md @@ -0,0 +1,69 @@ +# Experimental spatial upscaling after frame generation + +The compositor limits effects output to the logical scene size while frame +generation is active. This avoids running interpolation over the full phone +panel, but can make FSR/GSR/NIS see equal input and output sizes and skip their +spatial pass. Version 0.5.0 instead upscaled before interpolation, which made +the interpolation workload scale with panel resolution. + +This experiment keeps the existing source-resolution selection and runs frame +generation at the effects input size. Each generated frame and the final real +frame then uses the selected spatial filter at the mapped display size. +It introduces no extra frame queue or CPU fence wait. Performance and latency +improvements are hypotheses, not measured results. + +## Scope and activation + +Use an SDR game with a real input buffer smaller than the mapped output. +Enable frame generation and select AMD FSR 1, FSR Fit, Snapdragon GSR/GSR HQ, +or NIS in the scaling filter setting. Keep additional effects (CAS, color, +FXAA, CRT, etc.) off for this experiment. Sharpen-only, linear, nearest, +frame-generation-off, HDR and cardboard paths retain their existing behavior. +Combining a spatial filter with additional effects also retains the old path; +this experiment does not claim to fix that combination. + +Source selection remains conservative. A game already rendering a native-size +backbuffer cannot recover its lower internal rendering resolution here. +Overlays included in the low-resolution input are interpolated/upscaled with +that input; this is not a separate native-resolution HUD reconstruction. + +GPU targets and source descriptors are separate for each presentation slot so +recording one generated frame cannot replace another frame's bindings. +Source views are released after the existing frame-completion fence; targets +are cached and destroyed with the effects device. This increases GPU memory +use with interpolation multiplier and panel resolution. Allocation failures +retain the input-sized image and the existing screen blit fallback. + +## Applying and reverting + +Install the test APK produced for this PR. Check its signing/package identity +before replacing an installed release: an Actions test-key APK is not a +release-signed update. An official signed test build requires the repository's +normal publication authorization. Back up session logs and record the exact +APK commit, GPU driver, engine and game settings for comparisons. + +No setting migration is required. Disable frame generation or select Linear +to return to the previous presentation path. Do not mix this test with Vulkan +feature-level or game compatibility changes. + +## Device validation required before merge + +- Compare the same scene on baseline main and this branch: FG off/on, Linear, + FSR, GSR, GSR HQ, NIS, FSR Fit, sharpen-only and nearest. +- Test each supported interpolation multiplier on LSFG, DDFG and ZeroFG, + including warm-up/no generated frames, 720p-to-1080p and 1080p-to-panel + scaling, and no upscale. +- Check real and generated frames for consistent sharpness, halos, ghosting, + text/cursor artifacts, black bars, stretching and frame-order errors. +- Change resolution/filter/engine/multiplier live; open Steam/QAM, rotate, + suspend/resume and stop/restart. Verify no stale image, GPU loss or crash. +- Confirm HDR, cardboard, FG-off and additional-effects fallback behavior. +- Compare sustained frame pacing, generated vs real FPS, GPU load, memory, + temperature and battery use after warm-up; do not treat output FPS alone as + lower input latency. Measure input-to-display latency if equipment permits. +- Test memory pressure and allocation failure fallback; inspect Vulkan + validation for descriptor lifetime, image layouts and synchronization. + +Host harnesses exercise resolution routing, generated/real frame counts, +filter gates, fallback and source descriptor lifetime. They do not validate +shader output, mobile-driver behavior, performance or physical input latency. diff --git a/docs/development/producer-acquire-fences.md b/docs/development/producer-acquire-fences.md new file mode 100644 index 0000000000..880f216f0c --- /dev/null +++ b/docs/development/producer-acquire-fences.md @@ -0,0 +1,19 @@ +# Opt-in producer acquire fences for Steam + +[Thor investigation and captured benchmark](https://github.com/Droid-Deck/DroidDeck/pull/3636). + +The existing copy path is the default. In Steam display settings, **Direct game frames (experimental)** is a separate opt-in, applied at the next session. It requires zero-copy presentation, an eligible Adreno/native-worker Steam session, and a signed APK containing a capable Gamescope asset. The next normal session without the option, or a session with custom or Agent launch environment overrides, sees no private host global. Non-compatible clients and older components keep their current path. This is not a trust boundary against arbitrary code already executing as the Android app UID. + +## Source and lifetime + +- APK preparation verifies the Gamescope archive digest. At run time, the app compares the staged executable against the signed APK copy. It also checks the staged session script. No Agent executable, user environment, debug property, or test key can arm the host. Only a launch of the exact staged Gamescope path can qualify. +- One app-owned session prepares a short-lived worker ticket. Only the matching Steam backend launch can consume it. The dedicated, app-bound non-exported Worker reports its own PID/start time through the existing local Binder exchange, not into a guest message. The broker uses a live pidfd, a matching start time, and an exact executable mapping after exec. If Android hides the pre-exec stat entry, the Worker receipt is provisional only until the same timestamp is observable after exec. A malformed or wrong timestamp, wrong executable, stale worker, or no pidfd denies the private global. The bound grant remains scoped to that worker and is revoked on stop or worker exit. +- Gamescope only offers v1 to nested clients after negotiating v1 with that authenticated host. Mesa must export a real native sync_file for that particular attachment. Gamescope ties it to the exact submitted buffer/commit, waits on its duplicate normally, and forwards only a successful, signaled fence for unchanged source content. It cannot use a source fence as proof for composited output. The host consumes only a matching attachment's genuine successful fence and retains existing release and copy behavior. No fence, failed export, unsupported buffer, missing global, or X11-only path is not a license to scan out unsynchronized content. + +## Validation and rollout gates + +The historical controlled build on Thor used the same APK/components in both arms, the same Bright Family House camera with 120/no VSync and Steam limiter off at 60 Hz. Independent Android actual-presentation timestamps measured **21.08 FPS OFF → 37.42 FPS ON**. The compositor separately submitted 42.5–42.6 FPS on the direct path. This validates the technical approach, not the final candidate or physical panel behavior. + +Before default changes or release: after testing the exact signed candidate with the intended Gamescope and Turnip binaries, record OFF/ON same-scene timestamps and direct/layer/full/verified-acquire counters; old producer/host, malformed/missing proof, X11/FIFO and unsupported import should use safe fallback. Exercise cap changes, pause/resume, Home→return, and a cold restart to verify no stale fence/buffer/cap state. Test boot with the option off. Use an external camera on the actual panel for tearing/corruption; Android captures cannot settle it. Keep the feature off by default and hold rollout if these checks do not pass. + +The APK pins the SHA-256 of [the exact tested Gamescope archive](https://github.com/Droid-Deck/DroidDeck-Components/releases/tag/gamescope-3.16.29-verified-acquire-v1), promoted without rebuilding or replacing the previous release. It includes the signed APK capability marker. A compatible DD-Turnip producer is still required for actual direct frames: an older driver or missing fence retains the copy path even if the option is enabled. diff --git a/docs/development/screen-effects.md b/docs/development/screen-effects.md new file mode 100644 index 0000000000..2551c65a38 --- /dev/null +++ b/docs/development/screen-effects.md @@ -0,0 +1,28 @@ +# Screen-effect pipeline creation + +The screen-effect chain creates its shared render passes, sampler, descriptor +layout/pool and pipeline layout when first used. Graphics pipelines are created +only when the frame's settings require them, then reused until output-format +reset or explicit chain teardown. Source-image and size changes keep the cache. + +Pipeline preparation happens before any effect draw is recorded. If a required +pipeline fails to initialize, the chain follows its existing whole-chain +fallback and returns the unprocessed scene; it does not record a partial stack. +Settings are snapshotted at frame entry, so changes during recording apply to +the next invocation. + +Spatial upscalers are prepared only when their dispatch path is active. FSR +creates EASU and creates RCAS only when sharpening is enabled; sharpen-only +mode creates RCAS. SMAA prepares its three passes only when selected, while +keeping FXAA available for the existing SMAA scratch-allocation fallback. +Half-precision shaders remain selected by the existing debug property. The +optional fast NIS path and its coefficient resources are deferred until NIS is +actually used; the existing fragment-shader fallback is retained. + +This reduces unused pipeline creation and first-use setup work. It does not +reduce the shader work performed each frame, and first use of a newly selected +effect may still compile its pipelines. No background precompilation is added. +Pipeline-count reductions are not measurements of startup latency or FPS. + +Validation still requires the native effect-chain tests and on-device visual +testing. Static source checks alone do not establish Vulkan runtime correctness. diff --git a/docs/development/themes.md b/docs/development/themes.md index 8fbae55688..619dc43b8f 100644 --- a/docs/development/themes.md +++ b/docs/development/themes.md @@ -42,3 +42,37 @@ Gradient in the list, and Setup shows a Speed slider (1 to 10, `SessionPrefs.rgb Compose applies Android's animator scale to it, and the colour holds still when animations are off in the app (`Motion.scale`) or in Android's own settings. The hue is written to `Themes.rgbHue` in 3° steps, which restyles the app only when the colour visibly moves; a slow cycle costs few recompositions. +## Frosted background + +Setup › Launcher › Frosted (`SessionPrefs.launcherFrost`, off by default) is the master switch. Under it, while it is +on, sit Frosted wallpaper and Frosted cards (`frostWallpaper`, `frostCards`, both on by default, so the first time +Frosted is turned on both apply at their defaults), each with its own transparency from 0 to 100 % in steps of 10 +(`frostTransparency` from 80 %, `frostCardTransparency` from 50 %). Frosted cards is greyed out while Frosted wallpaper is +off, since a card can only show the wallpaper the page behind it shows; each slider stays in place and is greyed out +while it has nothing to set. + +Frosted wallpaper shows the device's wallpaper, blurred, behind the launcher. Android draws it: the launcher's window +is see-through and carries `FLAG_SHOW_WALLPAPER` and `FLAG_BLUR_BEHIND`, so the app never reads the wallpaper and needs +no permission (`ui/LauncherFrost.kt`). It works with any theme except True black, which keeps the page unlit. + +Over the wallpaper sits one veil of the theme's `background` (`frostLook`). 0 % is nearly solid and 100 % shows the most +wallpaper. While the frost shows, the theme moves `onSurfaceVariant` toward `onBackground` (`Palette.frosted`): halfway +up to 50 %, and further above it, all the way at 100 %. The veil grows past the chosen transparency only as far as that +hint text needs to keep 4.5:1, on the page and on a card (the rail and the bottom bar are cards here), as far as the +theme's own colours allow: a Custom theme whose hint text matches its background stays unreadable with or without the +frost. Android reports only a wallpaper's main colours, and any part of it can sit behind text, so the check takes the +worst wallpaper there is: white under a dark theme and black under the light one. The veil is then about 0.7 at 50 %, +0.63 at 80 % and 0.6 at 100 % on a dark theme, and 0.7, 0.57 and 0.52 on the light one. The wallpaper slider starts at +80 % so the wallpaper shows about as much as the game page's glass (0.58) does. + +`LocalFrost` carries the veil and the launcher's root steps aside. With Frosted cards on, the theme hands out `surface` +and `surfaceVariant` see-through by the card transparency (0.6 on a dark theme and 0.74 on the light one at 50 %, solid at 0 %), and dialogs, popups, menus and +settings steps take the solid palette back (`SolidSurfaces`), so no page text shows through them. The rail and the bottom bar draw +`surface`, so they follow the cards: see-through with them and solid without. + +The rows show on Android 12 and later when the system can blur behind windows, and also while Battery Saver pauses the +blur, when the page shows the plain background until the blur returns. A window is see-through or not from its first +frame, so the launcher prepares its window whenever the wallpaper frost is on at start, whether or not the blur is +available then. Turning the wallpaper frost on restarts the launcher once only if the window was not prepared at start; +otherwise turning it off and on, and the blur pausing and coming back, switch between the frost and the plain +background at once. diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 1a02e3420f..ced25e4c70 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -303,6 +303,16 @@ alone would then read as an installed client. hook records the guest handler as it does for `sigaction()` and keeps its own installed, so a program that sets a crash handler is no longer killed by the next blocked system call (`tools/tests/test_native_hook_sigsys_mask.py`). + - `0020-guest-stack-clear-of-host-stack-reserve`: FEX places the guest's 128 MB stack range + with `MAP_FIXED_NOREPLACE`, scanning down from the top of the address space. With a 39-bit address + space the host stack sits in that top range in about one start in eight, and the guest stack then + landed directly below it, inside the space the kernel keeps free for the host stack to grow + (`RLIMIT_STACK`, at least 128 MB). A deep host call chain (the native userland's `execve` hook + and libc `syscall()` wrappers) then grew the host stack into the top of the guest stack, where + the guest's argument and environment strings live, and the next program started with a corrupted + environment (Proton failing with `KeyError: 'PWD'` or "No compat data path"). The guest stack is + now placed below that reserve. On a Retroid Pocket Duo, 100 nested Proton starts ran clean, 10 of + them with the host stack at the top; without the patch 3 of 25 were corrupted. - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md new file mode 100644 index 0000000000..b3bee82824 --- /dev/null +++ b/docs/phantom-processes.md @@ -0,0 +1,619 @@ +# Android's child-process limit without developer options + +Research log for removing DroidDeck's requirement to turn off "Restrict child processes" (or run +`settings put global settings_enable_monitor_phantom_procs false` over wireless ADB). The goal: +Android must not kill a Steam session for having too many Linux processes, and the user must not +need developer options. + +Status: **working on the AYN Thor (Android 13).** With Android's limit on and no developer option, +a Steam session with a game running keeps 12 processes in the app's counted cgroups (63 without +this work), and Android killed nothing in minutes of forced scans. DroidDeck's Setup reports the +limit as handled and no longer blocks Steam. Both counting gaps below are in identical code on +Android 12 through 16; a stock Android 14+ phone is still to be tested. The experiments are in +`tools/phantomlab` (see the end). + +## How Android counts and kills + +Source: `frameworks/base/services/core/java/com/android/server/am/PhantomProcessList.java` +(android12-release to android16-release and main; the parts below are unchanged across them). + +1. **What is counted.** For every app process AMS knows (`mPidsSelfLocked`), + `lookForPhantomProcessesLocked(app)` reads + `/sys/fs/cgroup/uid_/pid_/cgroup.procs` (`/acct/...` on cgroup v1). Every + pid listed there other than the app process itself is a "phantom process". `cgroup.procs` + lists thread-group ids, so threads never count. +2. **What is skipped.** + - `if (app.appZygote || app.isKilled() || app.isKilledByAm()) return;`. `appZygote` is true + for uids in `FIRST_APP_ZYGOTE_ISOLATED_UID..LAST_APP_ZYGOTE_ISOLATED_UID` (90000–98999), + i.e. every process forked from an app zygote (`ProcessRecord` constructor). + - A pid that is itself an app process (`mPidsSelfLocked.get(pid) != null`). + - A pid whose `/proc//cmdline` cannot be opened, whose uid cannot be read, or for which + `pidfd_open` fails. These only happen once the process is gone (an empty cmdline reads as + `""`, not `null`, so it is still counted). +3. **When.** Only after AMS refreshes CPU stats (`AppProfiler.updateCpuStatsNow` → + `updateProcessCpuStatesLocked`), at most every 5 s (`MONITOR_CPU_MIN_TIME`), and only when + something asks for it: activity and process lifecycle events, mostly. Also from + `setProcessGroupForPhantomProcessOfApp` when an app changes scheduling group. A new phantom + schedules `trimPhantomProcessesIfNecessary`. +4. **The kill.** When the device-wide total exceeds `max_phantom_processes` (32), phantoms are + sorted by their app's oom adj (most important first), then youngest first, and the surplus is + killed from the end of that list (`SIGKILL` and `killProcessGroup`): the least important app's + oldest processes go first. As the foreground app, other apps' phantoms go first, so the + practical budget is our own 32, and of ours the **oldest** die first: the session's PipeWire, + D-Bus and Steam itself, not the game that pushed the count over. +5. **The second killer.** `ActivityManagerService.updatePhantomProcessCpuTimeLPr`: when the app is + at `PROCESS_STATE_HOME` or below (backgrounded, no foreground service) and a phantom used + "excessive" CPU, `killPhantomProcessGroupLocked` kills every phantom of that app **and the app**. + +`settings_enable_monitor_phantom_procs=false` (the developer option) switches off both on Android +12L and later; Android 12 does not have the setting, and there only the `device_config` limit below +applies. Raising +`max_phantom_processes` through `device_config` (shell only) avoids only the first: the +excessive-CPU check still runs while monitoring is on. + +Today an idle Steam session is about 30 processes and a session with a game about 45 (#566, #575). + +## Gap 1: an isolated process's children are never counted + +Two independent reasons, either of which is enough: + +- **Wrong cgroup path.** The path is built from `app.info.uid`, the *package's* uid (10148 here), + but an isolated process runs as its own uid (99000+ for `android:isolatedProcess`, 90000+ from an + app zygote) and its cgroup is `uid_/pid_`. The lookup finds nothing + (`FileNotFoundException`, logged only with `DEBUG_PROCESSES`) and the process is skipped. +- **App zygote skip.** Processes forked from an app zygote (`android:useAppZygote="true"`) are + skipped outright by the `app.appZygote` check, by design ("doesn't have its own acct entry"). + This one survives even if Google fixes the path. + +Measured with `max_phantom_processes=4` and monitoring on, children killed by Android: + +| Where the children were forked | Children | Thor (Android 13) | Emulator (Android 15) | +|---|---|---|---| +| Main app process (control) | 10 | 6 ("Trimming phantom processes") | 6 | +| plain `isolatedProcess` service (uid 99000+) | 10 | 0 | 0 | +| `isolatedProcess` + `useAppZygote` service (uid 90000) | 40 | 0 | 0 | + +`cgroup.procs` of `/sys/fs/cgroup/uid_90000/pid_` held all 41 pids the whole time; the +phantom list (`dumpsys activity processes`, "All Active App Child Processes") only ever showed the +main process's children. With the limit at 4, the Thor also trimmed another app's `logcat` child, +as expected for the device-wide count. + +## Gap 2: a process that execs in place is an app process, not a phantom + +An `android:process` service process can `execve()` a Linux program in place. If it first clears +`FD_CLOEXEC` on its binder fd, the binder node stays alive, so AMS never sees the process die. The +pid stays in `mPidsSelfLocked` and is never counted. Its own children are counted as usual. + +Same results on the Thor and the emulator: + +| Worker `:wN` | Result | +|---|---| +| exec `/system/bin/sleep`, binder fd closed by exec (control) | "has died" at once; AMS restarts the service | +| exec `/system/bin/sleep`, binder fd kept | stays `fg`/`(service)` while bound; survives a density change, `am send-trim-memory`, Home/back cycles | +| exec `sh` forking 6 `sleep`s, binder fd kept | `sh` not counted; its 6 children counted (2 trimmed at limit 4) | +| guest exits (killed) | AMS logs "has died" and removes the cgroup, as for any app process | + +Calls AMS makes into the process after the exec fail cleanly: the kernel logs +`binder_alloc_buf, no vma` and AMS gets `DeadObjectException` ("Failed for dead process. +ClientTransactionItem=ConfigurationChangeItem", "Remote exception" for trim). Nothing kills the +process for it. It is frozen like any cached process when the app goes to the background without a +foreground service. + +## What else was tried + +| Idea | Result | +|---|---| +| Move a process to another cgroup (`cgroup.procs` of root, of `uid_N`) | `EACCES`: dirs are `system:system 0775` and SELinux denies `cgroup_v2` writes to apps | +| Make a sub-cgroup under our `pid_N` (children of a sub-cgroup are not in its `cgroup.procs`) | `EACCES` | +| `clone3(CLONE_INTO_CGROUP)` | apps cannot open `/sys/fs/cgroup` (SELinux `read` denied) | +| `unshare(CLONE_NEWUSER)` / `CLONE_NEWCGROUP` | `EINVAL` (no user namespaces in GKI) / `EPERM` | +| Empty `/proc//cmdline` | read as `""`, still counted; changing it needs `PR_SET_MM` (`CAP_SYS_RESOURCE`) | +| Run "processes" as threads (`CLONE_THREAD`) | only with a shared address space; Steam, Chromium and Wine rely on real processes | +| More `android:process` services hosting the tree | each process's children are still phantoms; only the process itself is free (Gap 2) | +| Rely on kill order | we are the foreground app, so our own newest processes die first | + +## What an isolated process can do + +Measured from both isolated variants (domain `isolated_app`) against the normal app +(`untrusted_app`), with fds created by the app and passed over binder: + +| | app | isolated | +|---|---|---| +| `fork` | ✅ | ✅ (children uncounted) | +| `execve` of an executable in the APK's lib dir (as `libddexec.so`) | ✅ | ✅ | +| `execve` of `/system/bin/*` | ✅ | ✅ | +| create `AF_INET` socket | ✅ | ❌ `EACCES` | +| `connect`/`send`/`recv` on a TCP or UDP socket the app created | ✅ | ✅ (policy: "network sockets received over IPC") | +| read/write a passed unix stream socket / pipe | ✅ | ✅ | +| `open()` an app data file by path | ✅ | ❌ `ENOENT` (not mounted) | +| read/write/`mmap` a passed app data file | ✅ | ✅ | +| `mmap(PROT_EXEC)` of a passed app data file | ✅ | ❌ `EACCES` | +| receive a passed directory fd | ✅ | ❌ (binder refuses the transaction) | +| `mmap(PROT_EXEC)` of a memfd, anonymous RWX (JIT) | ✅ | ✅ | +| GPU device (`/dev/kgsl-3d0`, `/dev/mali0`) | ✅ | ❌ (`neverallow`, also for passed fds) | +| signal or read `/proc` of the app's processes | ✅ | ❌ (`EPERM`, `EACCES`) | + +This table is the emulator (stock, enforcing policy). **The Thor's ROM runs `isolated_app` +permissive** (every isolated denial logs `permissive=1`; `untrusted_app` is enforcing): there an +isolated process could also create inet sockets and open `/dev/kgsl-3d0`. That is an AYN quirk and +must not be relied on; design for the enforcing column. + +Isolated processes can talk to each other through abstract unix sockets. Everything else in the +app's world (files, sockets to the app's servers, the GPU) has to be brokered through fds. + +## Routes + +### A. An isolated tier for everything that does not touch the GPU + +Run a session's GPU-free processes inside one app-zygote isolated service; their whole fork tree is +invisible. Needed: + +- **Loader:** `libddexec.so` already starts programs without the kernel loading them; it would take + its ELF from an inherited fd and copy segments into anonymous or memfd memory, since isolated + processes cannot map app files executable. A broker can hand out one sealed memfd per library so + pages stay shared. +- **File broker:** the native hook already funnels path calls through `rewrite_path`; in the + isolated tier those calls become requests to a broker in the app, which opens the file and returns + the fd. Directories cannot be passed, so `opendir`/`getdents` are served from listings. + Raw syscalls (Wine's preloader, FEX internals) need a seccomp `SIGSYS` trap, which the hook + already uses for Android's own filter. +- **Sockets:** `socket(AF_INET*)` → broker-created socket; then the process connects itself. + Unix sockets between isolated processes become abstract sockets; connections to servers in the + app (compositor, PipeWire, VkBridge) are connected by the broker. +- **No signals across the boundary:** a process and everything it signals or ptraces must be on the + same side. Wine's processes all depend on `wineserver` signalling them, so Wine stays with the game. +- **GPU:** only through a remoting layer such as VkBridge (already used on Mali), never directly. + +Candidates for the tier: the Steam client and its web helper's renderer/utility processes (with +the web helper's GPU work remoted or in software), the session scripts, D-Bus services, PipeWire +helpers, Python daemons. A cross-tier launch (Steam starting the game's `reaper`) runs through the +broker, with a small stand-in process left in the tier for Steam to wait on. Stand-ins are free +there. + +### B. Exec-in-place workers for long-lived processes + +Declare a pool of `android:process` services (`:g0`…`:g127`). Each long-lived program runs as the +main process of one worker (Gap 2): full app privileges, direct GPU, normal signals and `/proc` +(same uid and SELinux domain), and the app hears its exit through binder death. Costs and limits: + +- A worker is a zygote fork (~100 ms); a pre-started pool removes the wait. +- Only the worker's main process is free; its children count. So each long-lived program must be + started in its own worker, not forked by its parent. +- Programs the app or the session script start and do not wait on (Xwayland, D-Bus, PipeWire, + helpers, `wineserver -p`) can move with a `droiddeck-spawn` client and no other change. +- A program another guest forks and waits on (Wine's processes, Steam's children) needs the hook to + hand the exec to a worker and translate the pid for the parent: `wait4`, `kill`, `/proc/`, + `SIGCHLD`. All app processes share zygote's session (sid 0, pgid of zygote), so `setpgid` and + process-group signals across workers are possible. +- Relies on AMS never pinging a process; today it only sends oneway calls that fail harmlessly. + +### Measured on the Thor: a real session + +An idle Steam session (Big Picture at the library, Decky on, 0.7.11 / main `b08d8e8e1`) holds +**48 counted processes** in the app's cgroup, well past 32 before any game starts: +9 bash, 6 python3, 5 dbus-daemon (with the portals and at-spi under the session bus), 4 Decky +PluginLoader, 4 steamwebhelper, 2 Xwayland, gamescope and its reaper, PipeWire and WirePlumber, +Steam, the clipboard bridge, and the app's own logcat, PulseAudio and audio relay. + +Prototype of B on this branch (`runtime/GuestWorkers.kt`, `droiddeck-spawn`, `dd_spawn` in the +session script; `DD_SPAWN_DAEMONS=0` turns it off): 24 `:gN` worker services, a spawn socket in the +app, and the session script starting the clipboard bridge, the system bus, login1 and the session +bus through it. Result: + +- Each of the four runs as its own app process (`/sys/fs/cgroup/uid_/pid_` with one + process). login1's sleep handshake, NetworkManager (state 70, full connectivity) and the Steam + library all work. +- Counted processes: **45** instead of 48. The session bus took its 9 activated children with it, so + they are still counted, under its worker. + +So starting top-level daemons in workers is not enough. What is left is the processes other +programs start. Of the 47 counted processes in that session, **40 are exec'd programs** and only 7 +are forks without an exec (the session script's `( … ) &` subshells). A handoff inside the native +hook, at `execve()` in a forked child, could move all 40, leaving about 7 counted at idle. That needs +the pid translation described in B (the parent keeps the forked pid; `wait4`, `kill`, `SIGCHLD` and +`/proc/` go to the worker's process). + +### Handoff in the native hook (prototype, on this branch) + +`tools/nativeguest/hook/handoff.c`. At `execve()` in a forked child, a program named in +`DD_HANDOFF` is sent to the app's spawn socket instead of exec'd: the request carries argv, the +environment, the working directory and every inheritable fd with its number, and a worker execs +the program with those fds in place. The child records "my pid is now worker pid P" in a memfd +table its parent created, and exits. In the parent, `wait4`/`waitpid`/`wait`/`wait3`/`waitid` and +`kill` treat the forked pid as P until P exits. P's hook writes its exit status into the table; for +a program that ends without `exit()` (a signal) the app writes a report tagged with the child it is +for (from `ApplicationExitInfo`), which the parent's hook takes once P is gone, and sends the parent +`SIGCHLD`. Only the hook moves an entry to "exited", by compare-and-swap. A launch takes three +answers: the hook's "go" once it has P's pid, the worker's answer to the app's commit, and the +app's "ok" once the worker runs the program; without any of them the program runs locally instead, +never twice. The child's side is +vfork-safe (Python's subprocess execs under `vfork`). Details that mattered: + +- **Scripts:** the list also matches the `#!` interpreter (`python3` for `droiddeck-agent`). +- **Exec chains:** a forked child that first execs a wrapper (`env`, `taskset`, a shell script, + Wine re-executing itself through `wine-preloader`) keeps its parent's table fd across the exec, + so the wrapper's own exec can still be handed off. +- **Not handed off:** Steam and the web helper's browser process (gamescope finds a window's app by + walking its process's parents) and its utility processes (the client refuses its transport — + "no transport is available" — from processes that are not its children). The web helper's + renderers hand off fine. +- **Game windows outside the reaper:** gamescope finds a window's app by walking its process up to + Steam's `reaper`, which a handed-off Wine process is not under. Proton sets `STEAM_GAME` itself + from `SteamGameId`, but a store game's is a 64-bit id and is not set: Splinter Cell (Ubisoft) + ran without ever taking focus. The agent now tags such a window from its process's `SteamAppId` + also on the arm64 client. +- One-shot programs cost a worker start (~100 ms) each, so the list names long-lived programs only + (`xprop+-spy`: `name+prefix` matches only when an argument starts with prefix). +- **Near the limit, a shell's children too.** Once 20 of the app's processes are counted (the hook + counts them in `/proc`: this uid's processes in an app process's cgroup other than that process), + a child of `bash`, `sh`, `dash`, `zsh`, `ksh`, `fish`, `make` or `xargs` is handed off even when + it is not listed. Those parents wait with `wait()`, which the hook answers; Qt's `QProcess` and + other parents that watch a child by pidfd or `/proc` would see the forked child end at once, so + their children stay. A job in the foreground of its controlling terminal (`TIOCGPGRP` on + `/dev/tty`, whatever its standard fds are: `cmd | less`, `less < file`) stays too: a handed-off + program has no controlling terminal, so `/dev/tty`, ^C and job control would miss it. A job a + shell with job control runs (any process group other than the shell's, `cmd &` in an interactive + terminal, each member of its pipeline) stays as well: the shell waits for its stops and continues, + which happen to a handed-off program's worker and never reach that wait. A job started with `&` + from a shell without job control (a script, `bash -c`) runs in the shell's group reading + `/dev/null`, and goes. Steam's client and launch chain (`steam`, its + web helper, `droiddeck-steam-x64`, `reaper`, `steam-launch-wrapper`, `pw-audio-namespace`, + gamescope, anything under `Steam/`) never go this way. In the desktop + session (KDE Plasma, 17–19 counted at rest), a Konsole running 40 `sleep 600 &` jobs peaked at + 61 counted and lost 27 processes to Android's limit (Konsole, D-Bus, the portal) before this, and + at 20 with no kills after. Still counted, and not handed off: a terminal's foreground jobs (a + `make -j` and its compilers) and the D-Bus daemon's activation helpers (forks that never exec). +- **The desktop.** Plasma's own programs are listed (`startplasma-wayland`, `plasma_session`, + KWin, `kded6`, `ksmserver`, `plasmashell`, PowerDevil, KDE Connect, the KIO workers, the D-Bus + activated portal, dconf and activity manager) along with DroidDeck's desktop helpers. Discover's + update notifier, GeoClue's demo agent and the global-menu proxy are off in the user's Autostart. + A program a desktop launcher starts (`DD_HANDOFF_LAUNCHERS`: Plasma's shell, KRunner, Dolphin) + goes to a worker when it is a plain fork and exec: in the launcher's process group and session, + with no controlling terminal. Those launchers are Qt programs, which wait with `waitpid()` once + the hook has taken their pidfds away. A terminal's shell (its own session and terminal) stays. + Firefox runs with fission off, at most two web content processes and no crash helper. The + desktop and its apps use about 80 workers with Steam and a game running, hence 128. + + Counted children on the Thor (main: the session as #3338 and #3594 left it): + + | | main | this | + |---|---|---| + | desktop at rest | 30 | 0 | + | Dolphin, Konsole, Firefox, Kate and System Settings open | not measured (49 on a Pocket FIT without Firefox, the terminal running 40 jobs) | 7 | + | those, the desktop's Steam client and Bully running | not measured | 20 (30 with 64 workers: Wine's services were refused one) | + + With Bully running, six scans forced with the stock limit of 32 killed nothing. What stays + counted then: Steam's client and launch chain (10), Firefox's helpers (6), Konsole's shell, + Proton's script and `wineserver`. + +Default list: the portals, at-spi, `python3`, PipeWire, WirePlumber, Decky's PluginLoader, the log's +`gnudd`, `xprop -spy`, the web helper's renderers, `wine`, `wine-preloader`, `wineserver`. + +Measured on the Thor, same session and game as above: + +| | counted children, idle | counted, Bully (Proton) running | +|---|---|---| +| main, no handoff | 48 | 63 | +| handoff | **26** | **29** | + +With the handoff on, Bully reached its menu at 30 fps, kept focus, and Steam's library, Decky, the +portals, NetworkManager/login1 and the agent all worked. + +Then Android's own limit was switched back on (`settings_enable_monitor_phantom_procs=true`, +default limit 32) with the game running, and a scan was forced every 20 s for 3 minutes +(`dumpsys meminfo` refreshes the CPU stats the scan runs on; process starts and activity changes do +too, irregularly): + +| | Android listed | killed | session | +|---|---|---|---| +| no handoff (`DD_SPAWN_DAEMONS=0`, same build) | 63 | **33**, oldest first: the session's bash, Python daemons, D-Bus, Xwayland, Steam, PipeWire, gamescope's reaper | FAILED | +| handoff | 27–29 (device-wide) | **0** in 9 scans | game running throughout | + +### Taken further: the session itself in workers + +A second round moved most of what was still counted: + +- **The app's own processes:** `HostProcess.startUncounted` runs a host command in a worker with the + same contract as `HostProcess.start` (output lines, exit code, working directory). The session + root, the app log's logcat, PulseAudio and the DirectAudio relay use it. A worker cannot `chdir` + before its exec, so Android's `sh` does it from an environment of its own and exports the + program's (`env -i` cannot be used: the APK's library path contains `==`). +- **PulseAudio** closes every inherited fd at start, the worker's binder fd included, and Android + then killed the worker as dead (the SIGKILL came from system_server's `ActivityManager` thread, + seen with the `signal_generate` ftrace event, which shell can enable on the Thor). The daemon + spares the fd named in `PULSE_PASSED_FD`; the worker replaces `@DDH_WORKER_BINDER_FD@` in a + program's arguments and environment with its `/dev/binder` fd number, so PulseAudio is given it. + Started as a normal child the token reads as fd 0, which the daemon ignores. +- **The script's long-lived subshells:** `dd_job FUNCTION` runs a function in a new `bash` that first + loads the shell's variables, functions and options from a state file, so it is an exec'd program + the hook can hand off (`bash+dd-job`). `$!`, `kill` and `wait` keep working. The zRAM scanner, + the property watcher, Decky's supervisor and the request/timer loop use it. +- **The log pipeline** is `droiddeck-log-writer`, a script of its own instead of a `{ gnudd; cat; }` + subshell. +- **gamescope, its reaper and the inner `droiddeck-session steam`** are handed off. Steam, its web + helper's browser process and its utility processes still are not (see above). + +Things this needed, found the hard way: + +- **The binder fd is the worker's life.** It sits above every fd number the program gets; programs + that close all inherited fds (gamescope) are kept from closing it (the hook's kept fds, also + against `CLOSE_RANGE_CLOEXEC`); children never send it along with a handoff; and the hook closes + copies in every other process (`DDH_WORKER_PID`), so a worker's exit is seen when its program + exits. A worker that lost its binder fd was killed by Android within milliseconds. +- **A session of its own (`setsid`) for every worker.** All app processes are in zygote's process + group, so a program signalling its group reached the app itself (the hook also refuses + `kill(0)`/`kill(-pgid)` into zygote's group, and `kill(-1)`). `reap_orphans` in the session + script stands down when its parent is zygote. +- **Nested handoffs** (a program in a worker handing off its own child): inherited `DDH_*` + variables are dropped from each request. +- **Requests carry up to 240 fds,** in chunks of 60 (`LocalSocket` reads at most 64 per read), after + the request itself; the spawn server catches everything per connection (an uncaught exception there + took the whole app down once). +- **The table is made at a process's first fork,** not only when `DD_SPAWN` is in its environment at + start: a shell that exports it has no sign of it in its own environment. +- **Exit status:** the program's hook records it with `on_exit` or in `_exit()` into the parent's + table; the app's `ApplicationExitInfo` is only the fallback (signals). A program inherits its + forked parent's ignored signals, open-files limit and umask (`DDH_SIGIGN`, `DDH_NOFILE`, + `DDH_UMASK`). + +Measured on the Thor, Bully under Proton, Android's limit on (default 32), a scan forced every 20 s: + +| | counted, idle | counted, in game | killed in 3 min | +|---|---|---|---| +| main (no handoff) | 48 | 63 | 33, session failed | +| first round | 26 | 29 | 0 | +| second round | 9 | 14 | 0 | +| **third round** | **7–9** | **12** | **0** in 2 min, game kept focus | + +Still counted at idle: `run_gamescope`'s subshell, Steam, its web helper's browser and +two or three utility processes, the session bus's activation babysitter and Decky's +multiprocessing child (forks without an exec). In game, also Steam's launch chain (`sh`, +`pw-audio-namespace`, `reaper`) and the `wineserver` daemon (a fork of its first process, which +lingers in its worker; see below). + +### Third round + +- **PulseAudio in a worker** (above). +- **`posix_spawn()`:** Python 3.13+ (`subprocess`, even with `close_fds`) and GLib's `g_spawn` start + programs with `posix_spawn()`, whose child makes the exec system call itself, past the hook. A + listed program is now spawned with `fork()` and the hook's `execve()`; the hook replays glibc's + file actions and attributes in the child, and a close-on-exec pipe returns an exec error as + `posix_spawn()`'s result. Proton's Wine and at-spi's bus came out of the count this way. +- **The table fd survives a child that closes every inherited fd** (Python's `subprocess` before + exec): it sits at fd 800 or above and is one of the hook's kept fds. Reopening it from + `/proc//fd` does not work on Android (EACCES). A nonce in the table's header tells it from + a file a program put at that number (inode numbers are rewritten by the hardlink emulation). +- **The exit status comes from the program itself.** The worker first runs a `bash` that `cd`s and + execs the program; that `bash` closed the `DDH_TABLE` fd as someone else's table, so the + program after it could never report, and statuses came from `ApplicationExitInfo`, late or + unknown. The `DDH_TABLE` fd is now kept through that exec, and `_exit()` reports as `exit()` does. +- **Daemons:** Android kills every process in a worker's cgroup when the worker's own process ends + (`libprocessgroup: Successfully killed process cgroup`). `wineserver` forks the server and leaves + with `_exit(0)`, so the server died with it and Wine stopped with "the wine server failed to run". + A handed-off program's process now reports its status and then stays, with no fds but the + binder's and all signals blocked, until no other process is left in its cgroup (found through + `/proc//cgroup`, as `cgroup.procs` is not readable). It does so only when it is + single-threaded at exit, and never for the processes the app starts itself (the session root), + whose exit the app waits for. +- **`reap_orphans`** in the session script killed every process whose parent was zygote (all the + app's workers, the session root among them) when the inner `droiddeck-session` ended in a + worker: the guest cannot see zygote in `/proc`. It now stands down when `DDH_WORKER_PID` is + its own pid. +- **`DD_HANDOFF_DEBUG=/path`** appends the hook's trace to a file. On stderr it broke Steam's + login, and the trace from a game's processes went to a pipe nobody read. +- **Finding the sender of a SIGKILL:** shell can enable the `signal/signal_generate` ftrace event + on the Thor (`/sys/kernel/tracing`), which names the sending thread; Perfetto recorded nothing + there. +- **Ending a game from Steam** (`SteamClient.Apps.TerminateApp`, the overlay's Exit game) left Wine + running since the first round: Steam sends SIGINT to the launch's `reaper` and its parent, and the + reaper ends what is under it, which handed-off programs are not. Each handed-off program now + lists itself as `P` with the process that forked its child and, for when that process is + gone (Wine starts a process through a fork that exits at once), the worker's program it descended + from. A signal to `reaper SteamLaunch` from a hooked process also goes, as SIGTERM for SIGINT + (Wine takes SIGINT for a console's Ctrl+C), to the groups of every listed program under that + reaper, all found before any is signalled. +- **Process groups:** a handed-off program runs in a session of its own, outside the group its + forked parent's child was in. It lists itself as `GROUP.PID.START` for that group (`DDH_PGID`, + also for the processes it forks), and the hook's `kill(-GROUP)`, `kill(0)` and `killpg()` also + signal the groups those programs lead. +- **Tried and dropped:** handing off Steam's launch chain (`sh`, `steam-launch-wrapper`, `reaper`): + the client tracks the process it forked, which then exits at once, and called the game closed. + Showing a handed-off program's forking process as its parent in `/proc//stat` and `status` + left Steam's UI at "Loading library data": the client checks the parents of the processes on its + IPC connections with `lsof -F R`. Only the program's own `getppid()` answers with that process + (while it lives, then 1): the GOG launch leases the game folder for as long as the launcher, its + parent, runs, and took zygote, which the guest cannot see, for a launcher already gone. And + `posix_spawn()` emulation must make only + system calls in its child (no hook wrapper takes a lock there): one Steam fork hung on a lock + another thread held. + +Quitting the game (also from Steam), stopping the session (no worker is left) and starting +again all work. Started from the front end with the limit on, Setup shows "Child-process limit +handled by DroidDeck" and Steam starts. + +### The bionic runtime + +DroidDeck-Bionic runs Wine on Android's libc, outside the glibc root, so the native hook never sees +its processes: with the handoff on, a bionic game's Wine programs (the game, `services.exe`, +`winedevice.exe`, `plugplay.exe`, `svchost.exe`, `lsass.exe`, `explorer.exe`, `rpcss.exe`) all stayed +under the worker that runs the tool's `launch.sh` and were counted. The same handoff is built into +the runtime's exec shim (`tools/bionic-runtime/handoff.c`, part of `libexecshim.so`, which every Wine +process preloads): it includes `hook/handoff.c` and `hook/kept.c` (the descriptors `close()` and +`close_range()` leave open, moved out of `privileged.c` for this) and adds what the native hook's +other parts do around them (`fork()`, `close()`, `close_range()`, `dup2()`, `dup3()`, and `exit()` for +the `on_exit()` bionic lacks). What differs on bionic: + +- **bionic's `execv()`, `execvp()` and `execl*()`** make the execve system call inside libc, past an + interposed `execve()`. Wine starts its preloader with `execv()`, so the shim defines them on top + of its `execve()`. +- **A start through the system linker** (`/system/bin/linker64 PROGRAM ARGS`, which the shim makes + of a dynamic program in app data, and which Wine sometimes makes itself) is listed by PROGRAM + (`ddh_try_as()` matches one program and sends another). +- **The app starts a handed-off program from the glibc root's `bash`** (GuestWorkers), which cannot + load the runtime's `LD_PRELOAD` and `LD_LIBRARY_PATH` (bionic libraries: "libdl.so: cannot open + shared object file"). The request carries those two as arguments of `/system/bin/env` instead, + which `bash` execs and which puts them back for the program; the worker's main process is the + program all the same. +- `launch.sh` keeps `DD_SPAWN`, `DD_SPAWN_SESSION`, `DD_HANDOFF*`, `DDH_*` and `DDNATV_ROOT` (it drops + the glibc guest's environment otherwise). The "can't open /proc/N/environ: Permission denied" + lines its prefix checks printed came from idle workers (zygote forks, not dumpable), not from + handed-off programs, which are readable; the redirect is now quiet. + +Measured on an AYANEO Pocket FIT (Snapdragon G3 Gen 3, Adreno 750, Android 14), DroidDeck-Bionic 14.1-r67 with this shim and +launcher, handoff on, max counted in the app's cgroups: + +| | Brawlhalla | DiRT Showdown | whole run | other apps' processes trimmed (limit on) | +|---|---|---|---|---| +| bionic, before | 25 | 24–27 | 28 | yes (Discord, a logcat, BatteryLog's `su`) | +| bionic, with the shim | 17 | 16 | 19–20 | none | +| DroidDeck-Proton 11-14.2 | 12–13 | 12–15 | 15–17 | none | + +DiRT's benchmark held 75 fps average either way; quit through Steam, stop and restart worked with +Android's limit on, with no DroidDeck process killed. Still counted on bionic: what `launch.sh` +itself starts (the game's first Wine process, `gstag`, the wait loop's `sleep`), since Android's +`sh` has no hook, and `wineserver`'s daemon fork. + +### Cost + +Measured on the Thor, Bully under Proton, the handoff on (`childProcessHandoff`) against off, two +sessions each: + +| | off | on, first | on, now | +|---|---|---|---| +| one program started, `fork`+`exec` of `/usr/bin/true` | 37–39 ms | 197 ms | 80 ms | +| `start steam` to READY | 14.0–14.2 s | 20.0–20.2 s | 18.2–18.5 s | +| `launch` to the game's focus | 10.1 s | 14.7–14.8 s | 11.6–11.7 s | +| in game: frames, CPU of the app's uid, `system_server` | 29.9 fps, 1.02–1.05 s/s, 21 ms/s | 29.8 fps, 1.11 s/s, 21–27 ms/s | 29.8–29.9 fps, 1.10–1.11 s/s, 22 ms/s | +| memory of the app's processes (RSS) | 3.57–3.62 GB | 3.42–3.50 GB | 3.49–3.66 GB | + +Running costs nothing measurable; starting things does. A handed-off program costs a worker: a +zygote fork, its runtime (40–50 ms of CPU) and the bind, and the worker waited 100 ms before its +exec so as not to cut off its reply. Now the app closes a pipe once it has the reply and the worker +execs then, and two workers are kept bound ahead of need while a session runs (12 MB of PSS each); +four did no better. Starting a session takes about 10 more CPU-seconds (51 s against 41 s for the +app's uid), and the last 4 s come from the session script's own steps running beside the +handed-off daemons. With only the hook's handoffs off (`DD_SPAWN_DAEMONS=0`), READY came at +14.1 s: the app's own workers (the session root, PulseAudio, logcat) cost nothing there. + +**In the app:** `PhantomProcessStatus.UNCOUNTED` is reported when the limit is on but the session +runs in workers (`GuestWorkers.enabled`: the native userland, Android 11+, and the +`childProcessHandoff` session preference, on by default). It does not block Steam. Turning the +preference off (`droiddeckctl prefs set session childProcessHandoff false --type bool`, with +Setup > Developer > Debugging tools on; see `docs/agent-control.md`) brings back +the old behavior and the old requirement. + +### C. Plan + +1. ~~Verify both gaps on the Thor~~ done; still to do on a stock Android 14+ phone (enforcing + SELinux, unlike the Thor) and on a Mali device. +2. ~~B for the processes DroidDeck and the session script start themselves~~ done. +3. ~~B inside the hook, with pid translation~~ done. +4. ~~The session root, its jobs, the log pipeline, the gamescope chain~~ done: 9 idle, 14 in game. + Third round (PulseAudio, `posix_spawn`, daemons): 7–9 idle, 12 in game. +5. ~~Setup no longer requires the developer option while the session runs in workers~~ done. +6. Open: + - ~~PulseAudio in a worker~~ done; + - ~~`posix_spawn()` and daemons in workers~~ done; + - `/proc//stat` showing the virtual parent, so that Steam and its web helper can be handed + off too; + - ~~pre-started workers, so that a handoff costs no zygote fork~~ done: two are kept bound; + - ~~more games and configurations~~ done on the Thor with the stock limit on, no kills in any: + Bully on GE-Proton, Proton Experimental ARM64 and DroidDeck-Proton 11 (11–14 counted), Bomb + Rush Cyberfunk (14), MGSV Ground Zeroes (13), Sekiro (13), zero-copy off (11), the x86-64 + Steam client under FEX (14, against 55 without the handoff), Splinter Cell through Ubisoft + Connect (14, against 65), Star Wars: Galaxy of Heroes (EA, 14), 9 Years of Shadows (GOG, 14), + run mode with 40 background jobs (1), the desktop at rest (17–20) and + with a terminal's 40 background jobs (20). PRoot sessions keep the old behavior and still need + the developer option: with the limit on, Android killed 30 of their processes and the session + failed; + - Wine-heavy launchers and anti-cheat; + - a settings switch for `childProcessHandoff`. +7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket + broker and keeps the GPU outside. + +## Zombies + +Every session process is a child subreaper (`tools/linuxfs/preload/subreaper.c`, so that a +double-forked Xwayland is not left to init, which some vendor kernels kill), and most programs +never wait for a child they did not fork. What they adopted stayed a zombie: the grandchildren of +Qt's `startDetached()` under Plasma's shell, KWin and kaccess, Wine's double-forked processes, +wlroots' Xwayland under gamescope. A parent that never waits at all (Plasma's shell, for what it +launches) also kept the forked child of each program it handed off. On the Thor, main had 4 +zombies in Steam mode at rest and 19 in Bully, and the desktop gained one per app closed. + +The hook now reaps them from SIGCHLD (`ddh_reap_unclaimed()`): + +- **Adopted:** each process records, at its pid, the parent that started it and its own start + time, in one file for the session (`DD_PARENTS`). A fork's child does it at the fork, any other + program at its start. A zombie child whose record names another parent was adopted. An own child + (recorded with this parent, or with no record, such as a static program a `vfork()` started) is + left for its program's wait. +- **A handed-off program's forked child,** as a wait's look reaps it: the program's exit stays in + the table for the parent's wait. + +The program's SIGCHLD action runs first, and `sigaction()` shows it as the program set it. +`SIG_IGN` and `SA_NOCLDWAIT` stay the kernel's. A program that leaves SIGCHLD alone gets the +handler only when `DD_REAP_ADOPTED` names it (Plasma's programs, D-Bus, gamescope, Wine's +launchers, Decky's loader): with a handler, `poll()`, `sleep()` and the like return `EINTR` when a +child exits. With these changes there are no zombies left in either mode, Bully included. + +qemu-user has no `PR_SET_CHILD_SUBREAPER`, so the adoption tests skip under it (CI) and were run on +the Thor's kernel. + +## Robustness + +- Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app + zygote isolated services so either one is enough. +- Gap 2 depends on AMS not probing liveness. A future check (a ping, or watching a pidfd for the + binder) would end it; the session would then fall back to counted processes, which is today's + behavior. +- OEM ROMs with their own process managers (MIUI/HyperOS, ColorOS) are outside this. +- A listed program's stops and continues (`kill -STOP`, `SIGCONT`) reach its worker, not a wait in + its parent: `waitpid(…, WUNTRACED)` and `WCONTINUED` report none for it. Listed programs are the + session's own (Steam, Wine, game helpers), whose parents start them without job control; one a + shell runs as a job-control job (`wine game.exe &` in an interactive terminal) stays counted, as + any such job does, so its shell gets its stops. Reading + the worker's state from `/proc` instead was tried and dropped: a stop and a continue can both + fall between two reads. + +## phantomlab + +`tools/phantomlab` is a standalone test app (package `com.droiddeck.phantomlab`, no Gradle). It +forks sleepers from the main process, a plain isolated service, an app-zygote isolated service and +eight `:wN` workers, execs in place, and probes what a process may do. + +The limit of 4 below is device-wide: a trim while it is set can kill other apps' child processes, +which restoring the setting does not bring back. Use a test device or an emulator with nothing else +running, and note the current values first, to put them back afterwards: + +``` +adb shell settings get global settings_enable_monitor_phantom_procs +adb shell device_config get activity_manager max_phantom_processes +adb shell device_config get_sync_disabled_for_tests +``` + +Android 12 and some Android 13 builds have no `get_sync_disabled_for_tests`; there `adb shell +device_config is_sync_disabled_for_tests` answers only true or false, so it cannot tell `persistent` +from `until_reboot`. Note `none` when it says false. When it says true, sync is already off: skip +the `set_sync_disabled_for_tests persistent` step below, which keeps whichever mode it was, and +leave the mode alone when you restore the rest. + +``` +tools/phantomlab/build.sh # build/phantomlab.apk, debug-signed +adb install -r tools/phantomlab/build/phantomlab.apk +adb shell device_config set_sync_disabled_for_tests persistent +adb shell device_config put activity_manager max_phantom_processes 4 +adb shell settings put global settings_enable_monitor_phantom_procs true +adb shell am start -n com.droiddeck.phantomlab/.Main --es cmd spawn --es target iso:a --ei n 40 +adb shell "am start -n com.droiddeck.phantomlab/.Main --es cmd exec --es target w0 --ei keep 1 --es argv '/system/bin/sleep|100000'" +adb shell am start -n com.droiddeck.phantomlab/.Main --es cmd probe --es target iso:a --es what self,memfd_exec,exec,fds,escape,libexec --es fds tcp,udp,unix,file:probe.txt +adb logcat -s PLAB ActivityManager | grep -i 'PLAB\|Trimming' +``` + +Targets: `main`, `proc` (`:proc`), `isoplain`, `iso:` (one app-zygote instance per name), +`w0`…`w7`. Android scans only on CPU-stat refreshes, so switch apps a few times (5 s apart) before +reading the phantom list. Restore the noted values afterwards: `adb shell device_config put +activity_manager max_phantom_processes ` (or `adb shell device_config delete activity_manager +max_phantom_processes` if it was null), `adb shell device_config set_sync_disabled_for_tests ` +and `adb shell settings put global settings_enable_monitor_phantom_procs `, and end the lab's +sleepers with `adb shell am force-stop com.droiddeck.phantomlab`. diff --git a/docs/settings-map.md b/docs/settings-map.md index 122ab30945..aface4f407 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -32,9 +32,11 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot | | Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor | | Host name | Settings › Performance (`droiddeck://settings/performance`) | name | +| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot | | Controller | Settings › Controller (`droiddeck://settings/controller`) | gamepad, buttons, mapping, profile, remap | | Smart glasses | Settings › Smart glasses (`droiddeck://settings/glasses`) | xreal, viture, vr, ar | | Theme | Settings › Launcher (`droiddeck://settings/launcher`) | color, dark | +| Frosted | Settings › Launcher (`droiddeck://settings/launcher`) | blur, wallpaper, background, cards, transparent, transparency, opacity, glass | | App scale | Settings › Launcher (`droiddeck://settings/launcher`) | size, zoom | | App icon | Settings › Launcher (`droiddeck://settings/launcher`) | | | Animations | Settings › Launcher (`droiddeck://settings/launcher`) | | diff --git a/docs/testing/chinese-input.md b/docs/testing/chinese-input.md new file mode 100644 index 0000000000..ef2546efce --- /dev/null +++ b/docs/testing/chinese-input.md @@ -0,0 +1,23 @@ +# Chinese input + +The app ships a pinyin input method payload with the session files; it needs no network at run time. + +## Android keyboard + +1. Select your Android input method (for example Sogou or Gboard) in the system settings, then start a DroidDeck session and open its Android keyboard. +2. Type pinyin, pick a candidate, and commit it; confirm mixed Chinese/Latin and emoji text such as `中文` and `😀` arrives in the focused field, and that a backspace or Enter sent after a commit stays after it. + +## Steam on-screen keyboard + +Steam pinyin requires a Linux runtime built with IBus. The APK installs the pinyin engine and its data, but does not replace an installed Linux runtime. A runtime without IBus can still start Steam and cannot offer pinyin until it is updated. + +Start a Steam session, open Steam's on-screen keyboard on a text field, switch it to Simplified Chinese (pinyin), and confirm committing a candidate puts the characters in the field. Physical keys, shortcuts, and Latin input keep working as before. + +## X11 text-input fallback + +For clients without native Wayland text input, committed Android IME text is delivered to the focused X11 display. + +- **One focused display.** Text goes only to the focused X11 display. +- **Mappings stay stable.** Each keysym keeps its keycode and mapping until the helper exits, because clients may decode key events after they arrive. +- **Capacity is finite.** Only originally empty, non-modifier, unheld keycodes 8..255 can be reserved (at most 248 per display, in practice fewer); a frame that needs more distinct symbols than remain is refused before anything is injected, so restart the session to reclaim the slots. +- **Scope of the limitation.** Steam's own built-in IBus pinyin keyboard and native Wayland text input do not use this fallback and are not subject to it. diff --git a/settings.gradle b/settings.gradle index 6abc4f6609..21bd4f6605 100644 --- a/settings.gradle +++ b/settings.gradle @@ -8,6 +8,18 @@ pluginManagement { dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { + def robolectricMirror = providers.gradleProperty('robolectricMavenMirror').orNull + if (robolectricMirror) { + exclusiveContent { + forRepository { + maven { + name = 'robolectricMirror' + url = uri(robolectricMirror) + } + } + filter { includeGroup 'org.robolectric' } + } + } google() mavenCentral() maven { url 'https://jitpack.io' } diff --git a/tools/agent/AGENTS.md b/tools/agent/AGENTS.md index 20b1736bd7..d9b7deb09e 100644 --- a/tools/agent/AGENTS.md +++ b/tools/agent/AGENTS.md @@ -59,7 +59,9 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools process, and the conversation continues on the new build. - Python tests run from the repository root: `python3 -m unittest tools.tests.test_x`. Some fail on the device on `origin/main` too; run them on a worktree of `origin/main` before blaming a change. -- Gradle unit tests rarely run on the device. Leave them to CI and say so rather than retrying. +- Gradle runs on the device once the build tools are set up, but slowly: run the test classes that cover + your change, and leave full suites and native builds to CI. `PreviewRenderTest` cannot run here + (Robolectric's native graphics has no aarch64 Linux build). - If `git push` asks for credentials, run `gh auth setup-git` once. - Commits and pull requests you make are the user's own: no co-author line, AI credit or generated-by note. diff --git a/tools/agent/dd-gh-login b/tools/agent/dd-gh-login index f9b0b7734a..e02054ffc1 100755 --- a/tools/agent/dd-gh-login +++ b/tools/agent/dd-gh-login @@ -28,6 +28,19 @@ float_code() { [ "$result" = ok ] } +# git pushes through gh's sign-in and commits as the signed-in account, with its no-reply address. +configure_git() { + gh auth setup-git || return 1 + [ -n "$(git config --global user.name)" ] && [ -n "$(git config --global user.email)" ] && return 0 + local user id login name + user=$(gh api user -q '"\(.id) \(.login) \(.name // .login)"') || return 1 + read -r id login name <<<"$user" + [ -n "$id" ] && [ -n "$login" ] || return 1 + [ -n "$(git config --global user.name)" ] || git config --global user.name "${name:-$login}" + [ -n "$(git config --global user.email)" ] || git config --global user.email "$id+$login@users.noreply.github.com" +} +if [ "${1:-}" = --git ]; then configure_git; exit; fi + coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; } gh_pid=$GH_PID exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}" @@ -48,5 +61,9 @@ while IFS= read -r line <&"$ghout"; do done wait "$gh_pid" status=$? +if [ $status = 0 ] && ! configure_git; then + echo "Signed in, but git could not be set up: run dd-gh-login --git" + status=1 +fi [ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code" exit $status diff --git a/tools/agent/setup b/tools/agent/setup index e3b649db5e..45ad8144f7 100755 --- a/tools/agent/setup +++ b/tools/agent/setup @@ -16,6 +16,9 @@ command -v claude >/dev/null || [ -x "$HOME/.local/bin/claude" ] || mkdir -p "$HOME/.local/bin" for tool in dd-agent dd-lab-build dd-gh-login android-open; do install -m755 "$here/$tool" "$HOME/.local/bin/$tool"; done +if gh auth status >/dev/null 2>&1 && ! "$here/dd-gh-login" --git; then + echo "setup: git could not use the GitHub sign-in; run dd-gh-login --git" >&2 +fi # DroidDeck passes the live loopback adb port; a fixed one here would go stale whenever wireless debugging is toggled. sed -i 's|ADB_SERIAL=127.0.0.1:5555 |ADB_SERIAL="${ADB_SERIAL:-127.0.0.1:5555}" |' "$HOME/.bashrc" 2>/dev/null || true grep -q 'droiddeck-agent-path' "$HOME/.bashrc" 2>/dev/null || @@ -63,6 +66,29 @@ if [ ! -x "$sdk/cmdline-tools/latest/bin/sdkmanager" ]; then mv "$sdk/cmdline-tools/cmdline-tools" "$sdk/cmdline-tools/latest" fi export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-arm64 +# Ubuntu's default JDK can be newer than the Gradle wrapper supports, so every shell and Gradle run +# here uses 17, the SDK above and the qemu-wrapped aapt2, not only dd-lab-build's. +sed -i '/^# droiddeck-agent-gradle$/,+1d' "$HOME/.bashrc" 2>/dev/null || true +printf '# droiddeck-agent-gradle\nexport JAVA_HOME=%s ANDROID_HOME="$HOME/android-sdk"\n' "$JAVA_HOME" >> "$HOME/.bashrc" +mkdir -p "$HOME/.gradle" +touch "$HOME/.gradle/gradle.properties" +# Gradle's own settings carry the SDK too, for shells that do not read ~/.bashrc. +for setting in "org.gradle.java.home=$JAVA_HOME" "android.aapt2FromMavenOverride=$HOME/aapt2/aapt2" "systemProp.android.home=$sdk"; do + sed -i "/^${setting%%=*}=/d" "$HOME/.gradle/gradle.properties" + echo "$setting" >> "$HOME/.gradle/gradle.properties" +done +# The NDK's compilers are x86-64 only, so DroidDeck's native code is left to CI, as dd-lab-build does, +# and Conscrypt ships no aarch64 Linux library for Robolectric to load. +mkdir -p "$HOME/.gradle/init.d" +cat > "$HOME/.gradle/init.d/droiddeck-device.gradle" <<'GRADLE' +settingsEvaluated { settings -> + if (settings.rootProject.name != 'DroidDeck') return + gradle.startParameter.excludedTaskNames += ':app:buildVkBridgeServer' + gradle.allprojects { + tasks.withType(org.gradle.api.tasks.testing.Test).configureEach { systemProperty 'robolectric.conscryptMode', 'OFF' } + } +} +GRADLE (set +o pipefail; yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null) "$sdk/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null diff --git a/tools/bionic-runtime/build.sh b/tools/bionic-runtime/build.sh index 9837fbfd3f..11f496d62e 100755 --- a/tools/bionic-runtime/build.sh +++ b/tools/bionic-runtime/build.sh @@ -36,9 +36,11 @@ GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-im VULKAN_HEADERS_TAG=v1.4.341 # The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed. # Layer v18: DroidDeck-Proton 11-14.1 (Valve Wine a47c73f52fd7, as GE-Proton11-14), the build Bannerlator ships; it -# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40). -LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261124-v18/DroidDeck-proton-11.0-14.1-arm64ec.wcp -LAYER_SHA256=bf94176180e96584185835f9e80b168666f9fa752aa9583cfedb8fe493134ff6 # proton-wine 1a5735e7 (run 45926928349) +# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40). This build adds the +# original Xbox fixes on top of v18 (special APC delivery, boot video aperture, 0 timer resolution: each off unless +# droiddeck-game-env sets its variable; FileAllocationInfo, MFCreateWaveFormatEx NULL size). +LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261203-ogxbox/DroidDeck-proton-11.0-14.1-arm64ec.wcp +LAYER_SHA256=a779747c880c64bacc0171cf26822f3398eaf32f0b214bca3448a95bf4127a90 # proton-wine ee646200 (run 47122517177) LAYER_VERSION=14.1 # Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default # DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later). @@ -184,7 +186,7 @@ echo "== DroidDeck fake input (app/src/main/cpp/fakeinput_steam.cpp), heap-taggi "$CXX" -shared -fPIC -O2 -Wall -Wno-attributes -pthread -std=c++17 "$ROOT/app/src/main/cpp/fakeinput_steam.cpp" \ -ldl -static-libstdc++ -o "$PACK/preload/libfakeinput.so" "$CC" -shared -fPIC -O2 -Wall "$HERE/notag.c" -ldl -o "$PACK/preload/libnotag.so" -"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" -ldl -o "$PACK/preload/libexecshim.so" +"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" "$HERE/handoff.c" -ldl -o "$PACK/preload/libexecshim.so" "$CC" -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden "$HERE/steamshm.c" -ldl -o "$PACK/preload/libsteamshm.so" "$CC" -O2 -Wall "$HERE/gstag.c" -o "$PACK/bin/gstag" "$STRIP" --strip-unneeded "$PACK/layer/"*.so "$PACK/preload/"*.so "$PACK/bin/gstag" diff --git a/tools/bionic-runtime/execshim.c b/tools/bionic-runtime/execshim.c index 166b9cb6fd..8b449e8b74 100644 --- a/tools/bionic-runtime/execshim.c +++ b/tools/bionic-runtime/execshim.c @@ -25,6 +25,9 @@ typedef struct __posix_spawn_file_actions *posix_spawn_file_actions_t; #define LINKER "/system/bin/linker64" +// handoff.c: returns unless the exec was handed to one of the app's worker processes +void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]); + enum kind { PASS, VIA_LINKER, VIA_INTERP }; // What starting `path` needs; for scripts, the interpreter and its optional argument. @@ -205,6 +208,8 @@ int execve(const char *path, char *const argv[], char *const envp[]) { char storage[6 * PATH_MAX]; // stack only: this may run in posix_spawn's vfork-like child (where it passes) const char *file = path; char **args = rewrite(path, argv, &file, storage); + // the app may run it in a worker instead (handoff.c): matched by the program, sent as the start below + ddh_bionic_exec(file, args ? args : argv, envp, path, argv); int ret = real(file, args ? args : argv, envp); int saved = errno; free(args); diff --git a/tools/bionic-runtime/handoff.c b/tools/bionic-runtime/handoff.c new file mode 100644 index 0000000000..a20f16fa42 --- /dev/null +++ b/tools/bionic-runtime/handoff.c @@ -0,0 +1,422 @@ +// handoff: part of libexecshim.so, preloaded into the bionic Wine processes. The native hook's exec +// handoff (tools/nativeguest/hook/handoff.c, docs/phantom-processes.md) built for bionic: a program a +// Wine process forks and execs runs as the main process of one of the app's worker processes instead of +// as a child Android counts against its limit. The glibc session's hook cannot reach these processes +// (they run on Android's libc), so without this every Wine process of a bionic game was counted. +// +// What the native hook does around the handoff and this file does too: fork() records the child for +// its parent's table, close(), close_range(), dup2() and dup3() leave the table and the worker's binder +// fds alone (hook/kept.c), and execve() offers the exec to the app before it runs (execshim.c calls +// ddh_bionic_exec() with the start it is about to make: "/system/bin/linker64 PROGRAM ARGS" for a +// program in the app's data, matched against DD_HANDOFF by PROGRAM). wait*(), kill() and _exit() are +// the handoff's own (hook/handoff.c). Nothing here acts without DD_SPAWN and DD_HANDOFF in the +// environment (tools/bionic-runtime/tool/launch.sh keeps them). +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// bionic has no thread cancellation: nothing can cancel the table's setup +#ifndef PTHREAD_CANCEL_ENABLE +#define PTHREAD_CANCEL_ENABLE 0 +#define PTHREAD_CANCEL_DISABLE 1 +static int pthread_setcancelstate(int state, int *old) { + (void)state; + if (old) *old = PTHREAD_CANCEL_ENABLE; + return 0; +} +#endif +#ifndef CLOSE_RANGE_UNSHARE +#define CLOSE_RANGE_UNSHARE (1U << 1) +#endif +#ifndef CLOSE_RANGE_CLOEXEC +#define CLOSE_RANGE_CLOEXEC (1U << 2) +#endif +#ifndef __NR_close_range +#define __NR_close_range 436 +#endif + +#include +static void pthread_testcancel(void) {} +int close_range(unsigned int first, unsigned int last, int flags); + +// bionic has no on_exit(): the handoff reports a program's exit status from it (exit() runs it). +// atexit() handlers get no status, so exit() below notes it first; a return from main() reaches +// exit() inside libc and reports 0. +static void (*g_on_exit_fn)(int, void *); +static void *g_on_exit_arg; +static int g_exit_status; +static void run_on_exit(void) { + if (g_on_exit_fn) g_on_exit_fn(g_exit_status, g_on_exit_arg); +} +static int on_exit(void (*fn)(int, void *), void *arg) { + g_on_exit_fn = fn; + g_on_exit_arg = arg; + return atexit(run_on_exit); +} + +// The native hook's names for the plain system call and for a guest path: here there is no guest root. +static long call_orig_syscall(long nr, unsigned long a, unsigned long b, unsigned long c, unsigned long d, + unsigned long e, unsigned long f) { + return syscall(nr, a, b, c, d, e, f); +} +static const char *rewrite_path(const char *path, char *out, size_t size) { + (void)out; + (void)size; + return path; +} + +// The native hook's SIGCHLD handling (hook/signals.c) is not part of this shim: its programs record their +// first parent for the session's subreapers, and reap nothing themselves. +static void ddnatv_manage_sigchld(void) {} +static void ddh_reap_unclaimed(void) __attribute__((unused)); + +#include "../nativeguest/hook/kept.c" +#include "../nativeguest/hook/handoff.c" + +void exit(int status) { + g_exit_status = status; + void (*real)(int) = (void (*)(int))dlsym(RTLD_NEXT, "exit"); + if (real) real(status); + syscall(SYS_exit_group, status); + __builtin_unreachable(); +} + +static int ddh_is_linker(const char *path) { + const char *base = path ? strrchr(path, '/') : NULL; + return base && strcmp(base + 1, "linker64") == 0; +} + +static int ddh_regular(const char *path, int mode) { + struct stat st; + return path && stat(path, &st) == 0 && S_ISREG(st.st_mode) && access(path, mode) == 0; +} + +// Android refuses execve() of a file in the app's data unless SELinux is permissive (execshim.c makes the +// dynamic ones linker64 starts). An unreadable setting counts as enforcing. +static int ddh_selinux_permissive(void) { + char c = 0; + int fd = (int)syscall(SYS_openat, AT_FDCWD, "/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC, 0); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, &c, 1); + syscall(SYS_close, fd); + return n == 1 && c == '0'; +} + +// A handed-off start that fails fails in the worker, where the caller cannot see it and try its next +// candidate (Wine tries its preloader, then its loader), so only a start that would succeed here goes. +static int ddh_bionic_startable(const char *file, char *const args[]) { + char real[PATH_MAX]; + // env takes an argument with '=' for a variable, and looks a name without '/' up in PATH + if (!file || strchr(file, '=') || !strchr(file, '/')) return 0; + if (!ddh_regular(file, X_OK) || !realpath(file, real)) return 0; + if (ddh_is_linker(real)) + return args && args[0] && args[1] && args[1][0] != '-' && ddh_regular(args[1], R_OK) && ddh_startable(args[1]); + if (strncmp(real, "/data/", 6) == 0 && !ddh_selinux_permissive()) return 0; + // env starts FILE with FILE as argv[0] + return args && args[0] && strcmp(args[0], file) == 0 && ddh_startable(file); +} + +void ddh_bionic_exec(const char *file, char *const args[], char *const envp[], const char *path, char *const argv[]) { + if (ddh_env(envp, "DD_HANDOFF_DEBUG")) { + char why[200]; + struct ddh_table *own = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + snprintf(why, sizeof(why), "bionic exec (spawn %d list %d table %d owner %d up %d ppid %d) of", ddh_env(envp, "DD_SPAWN") != NULL, + ddh_env(envp, "DD_HANDOFF") != NULL, own != NULL, own ? (int)g_ddh_owner : 0, g_ddh_up != NULL, (int)getppid()); + ddh_debug(envp, why, path ? path : "(null)"); + } + if (!ddh_env(envp, "DD_SPAWN") || !ddh_env(envp, "DD_HANDOFF")) return; + if (!ddh_bionic_startable(file, args)) { + ddh_debug(envp, "bionic exec stays here (not startable as a handoff):", path ? path : "(null)"); + return; + } + // Wine's own starts through the system linker ("/system/bin/linker64 PROGRAM ARGS") are listed by PROGRAM + const char *match = path; + char *const *match_argv = argv; + if (ddh_is_linker(path) && argv && argv[0] && argv[1]) { + match = argv[1]; + match_argv = argv + 1; + } + // The app starts a handed-off program from the glibc root's shell (GuestWorkers), which cannot load this + // runtime's LD_PRELOAD and LD_LIBRARY_PATH (bionic libraries). The request carries them as arguments of + // Android's env instead, which the shell execs and which puts them back for the program: the worker's main + // process ends up as the program all the same. Stack only (this may run in a vfork child). + int nargs = 0, nenv = 0; + while (args[nargs]) nargs++; + while (envp && envp[nenv]) nenv++; + // env, up to two loader variables, FILE, args[1..], NULL (nargs >= 1: ddh_bionic_startable) + char *wrapped[nargs + 4]; + char *trimmed[nenv + 1]; + int w = 0, t = 0; + wrapped[w++] = (char *)"/system/bin/env"; + for (int i = 0; i < nenv; i++) { + if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0 || strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) { + if (w < 3) wrapped[w++] = envp[i]; + } else { + trimmed[t++] = envp[i]; + } + } + trimmed[t] = NULL; + // env runs the program by the path its first argument gives: the start's file, then the rest of its argv + wrapped[w++] = (char *)file; + for (int i = 1; i < nargs; i++) wrapped[w++] = args[i]; + wrapped[w] = NULL; + ddh_try_as("/system/bin/env", wrapped, trimmed, match, match_argv); + ddh_debug(envp, "bionic exec stays here:", path ? path : "(null)"); +} + +// bionic's exec functions call the execve system call stub inside libc, past execshim.c's execve(): Wine +// starts its programs with execv() (its preloader) and execvp(), so these go through execve() here. +extern char **environ; + +int execv(const char *path, char *const argv[]) { return execve(path, argv, environ); } + +// bionic's execvpe(), through execve() here: an unset PATH is libc's default (Android 14's; an empty one, and an empty +// entry, are the current directory), and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh. +#define DDH_DEFPATH "/product/bin:/apex/com.android.runtime/bin:/apex/com.android.art/bin:/system_ext/bin:/system/bin:/system/xbin:/odm/bin:/vendor/bin:/vendor/xbin" + +static int exec_as_script(const char *file, char *const argv[], char *const envp[]) { + int n = 0; + while (argv && argv[n]) n++; + char *script[(n > 0 ? n : 1) + 2]; + int s = 0; + script[s++] = (char *)"sh"; + script[s++] = (char *)file; + for (int i = 1; i < n; i++) script[s++] = argv[i]; + script[s] = NULL; + return execve("/system/bin/sh", script, envp); +} + +int execvpe(const char *file, char *const argv[], char *const envp[]) { + if (!file || !*file) { + errno = ENOENT; + return -1; + } + if (strchr(file, '/')) { + execve(file, argv, envp); + return errno == ENOEXEC ? exec_as_script(file, argv, envp) : -1; + } + const char *dirs = getenv("PATH"); + if (!dirs) dirs = DDH_DEFPATH; + int saw_eacces = 0; + size_t flen = strlen(file); + for (const char *p = dirs;;) { + const char *end = strchr(p, ':'); + size_t len = end ? (size_t)(end - p) : strlen(p); + const char *dir = len ? p : "."; + if (!len) len = 1; + char full[PATH_MAX]; + if (len + flen + 2 > sizeof(full)) { + errno = ENAMETOOLONG; + } else { + memcpy(full, dir, len); + full[len] = '/'; + memcpy(full + len + 1, file, flen + 1); + execve(full, argv, envp); + } + switch (errno) { + case EISDIR: + case ELOOP: + case ENAMETOOLONG: + case ENOENT: + case ENOTDIR: + break; + case ENOEXEC: + return exec_as_script(full, argv, envp); + case EACCES: + saw_eacces = 1; + break; + default: + return -1; + } + if (!end) break; + p = end + 1; + } + if (saw_eacces) errno = EACCES; + return -1; +} + +int execvp(const char *file, char *const argv[]) { return execvpe(file, argv, environ); } + +// execl(), execlp(), execle(): the list as an argv on the stack +#define EXECL_ARGV(first, ap, n) \ + do { \ + va_list count_ap; \ + va_copy(count_ap, ap); \ + n = first ? 1 : 0; \ + if (first) \ + while (va_arg(count_ap, const char *)) n++; \ + va_end(count_ap); \ + } while (0) + +int execl(const char *path, const char *arg0, ...) { + va_list ap; + va_start(ap, arg0); + int n; + EXECL_ARGV(arg0, ap, n); + char *argv[n + 1]; + argv[0] = (char *)arg0; + for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *); + argv[n] = NULL; + va_end(ap); + return execve(path, argv, environ); +} + +int execlp(const char *file, const char *arg0, ...) { + va_list ap; + va_start(ap, arg0); + int n; + EXECL_ARGV(arg0, ap, n); + char *argv[n + 1]; + argv[0] = (char *)arg0; + for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *); + argv[n] = NULL; + va_end(ap); + return execvp(file, argv); +} + +int execle(const char *path, const char *arg0, ...) { + va_list ap; + va_start(ap, arg0); + int n; + EXECL_ARGV(arg0, ap, n); + char *argv[n + 1]; + argv[0] = (char *)arg0; + for (int i = 1; i < n; i++) argv[i] = va_arg(ap, char *); + argv[n] = NULL; + if (arg0) (void)va_arg(ap, char *); // the list's NULL + char *const *envp = va_arg(ap, char *const *); + va_end(ap); + return execve(path, argv, envp); +} + +pid_t fork(void) { + static pid_t (*orig_fork)(void) = NULL; + if (!orig_fork) orig_fork = (pid_t (*)(void))dlsym(RTLD_NEXT, "fork"); + if (!orig_fork) { + errno = ENOSYS; + return -1; + } + ddh_prepare(); + pid_t forker = (pid_t)syscall(SYS_gettid); + pid_t forking = (pid_t)syscall(SYS_getpid); + pid_t pid = orig_fork(); + if (pid == 0) { + kept_forked(); + kept_close_forked(); + ddh_drop_worker_binder(); + ddh_forked(forker); + ddh_record_parent((pid_t)syscall(SYS_getpid), forking); + } else if (pid > 0) { + ddh_child_created(pid, 1); + } + return pid; +} + +int close(int fd) { + static int (*orig_close)(int) = NULL; + if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close"); + uint64_t ticket = kept_close_begin(); + if (kept_any() > 0 && is_kept_fd(fd)) { + kept_close_end(ticket); + return 0; + } + int r = orig_close ? orig_close(fd) : (errno = ENOSYS, -1); + int saved = errno; + kept_close_end(ticket); + errno = saved; + return r; +} + +static int dup_moved(int (*dup_fn)(int, int, int), int oldfd, int newfd, int flags) { + int pidfd_from = -1, locked = 0; + if (oldfd != newfd) { + locked = ddh_parent_pidfd_lock(newfd); + pidfd_from = ddh_parent_pidfd_moves(newfd); + } + int ret = dup_fn(oldfd, newfd, flags); + ddh_parent_pidfd_settle(pidfd_from, ret >= 0); + int saved = errno; + ddh_parent_pidfd_unlock(locked); + errno = saved; + return ret; +} + +static int (*g_orig_dup2)(int, int); +static int (*g_orig_dup3)(int, int, int); +static int call_dup2(int oldfd, int newfd, int flags) { + (void)flags; + return g_orig_dup2 ? g_orig_dup2(oldfd, newfd) : (errno = ENOSYS, -1); +} +static int call_dup3(int oldfd, int newfd, int flags) { + return g_orig_dup3 ? g_orig_dup3(oldfd, newfd, flags) : (errno = ENOSYS, -1); +} + +int dup2(int oldfd, int newfd) { + if (!g_orig_dup2) g_orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2"); + return dup_moved(call_dup2, oldfd, newfd, 0); +} + +int dup3(int oldfd, int newfd, int flags) { + if (!g_orig_dup3) g_orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3"); + return dup_moved(call_dup3, oldfd, newfd, flags); +} + +static int close_range_part(unsigned int first, unsigned int last, void *flags) { + return (int)syscall(__NR_close_range, first, last, *(int *)flags); +} + +static int close_range_unshare(void) { + return (int)syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE); +} + +int close_range(unsigned int first, unsigned int last, int flags) { + // what the kernel refuses, refused before the range is split or the table unshared + if (first > last || (flags & ~(int)(CLOSE_RANGE_UNSHARE | CLOSE_RANGE_CLOEXEC))) { + errno = EINVAL; + return -1; + } + uint64_t ticket = kept_close_begin(); + int r = 0; + // The table is unshared first, once, and this thread goes on with its own copy of the kept list + // (kept_split()) + if (flags & CLOSE_RANGE_UNSHARE) { + r = kept_split(close_range_unshare); + flags &= ~(int)CLOSE_RANGE_UNSHARE; + } + if (r == 0) { + int snapshot[DDNATV_MAX_KEPT_FDS]; + const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot; + int count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot); + r = count == 0 ? close_range_part(first, last, &flags) + : for_each_range_without(first, last, kept, count, close_range_part, &flags); + } + int saved = errno; + kept_close_end(ticket); + errno = saved; + return r; +} + +// The native hook's own uses of these (exec.c) have no counterpart here +__attribute__((unused)) static void *const glibc_only[] = {(void *)ddh_try, (void *)ddh_spawn_wanted}; diff --git a/tools/bionic-runtime/tool/launch.sh b/tools/bionic-runtime/tool/launch.sh index 0a9c298f0b..82f11b1fd0 100644 --- a/tools/bionic-runtime/tool/launch.sh +++ b/tools/bionic-runtime/tool/launch.sh @@ -53,6 +53,13 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do DROIDDECK_GUEST_ROOT) ;; DROIDDECK_UPSCALE|DROIDDECK_UPSCALE_*|WINEDLLPATH|ADSP_LIBRARY_PATH|PROTON_ENABLE_NVAPI|DXVK_ENABLE_NVAPI|WINE_HIDE_NVIDIA_GPU) ;; VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;; + # droiddeck-game-env's original Xbox switches for this layer's Wine and the Xbox VKD3D-Proton build + WINE_SPECIAL_APC_INTERRUPT|WINE_MF_DISPLAY_APERTURE|WINE_PRECISE_SLEEP) ;; + VKD3D_INTEROP_PRESENT|VKD3D_PACKED_422|VKD3D_PACKED_422_SWIZZLE) ;; + # The exec handoff (../handoff.c): the app's spawn socket and list (the app starts a handed-off program from the + # glibc root's shell, so its path too), and what a worker hands the program it runs (this script, when it runs + # in one): the first Wine process's hook knows the worker's binder fds are not its own. + DD_SPAWN|DD_SPAWN_SESSION|DD_HANDOFF|DD_HANDOFF_DEBUG|DD_HANDOFF_PRESSURE|DDH_*|DDNATV_ROOT) ;; *) unset "$v" 2>/dev/null ;; esac done @@ -90,7 +97,8 @@ export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR") UPSCALE_LAYER="" [ -n "${DROIDDECK_UPSCALE:-}" ] && [ -n "${DROIDDECK_UPSCALE_LAYER:-}" ] && [ -d "$DROIDDECK_UPSCALE_LAYER" ] && UPSCALE_LAYER=":$DROIDDECK_UPSCALE_LAYER" export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer$UPSCALE_LAYER ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0} -export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=1 +export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=0 +echo "WSI forced XWayland bypass disabled (GAMESCOPE_WSI_FORCE_BYPASS=$GAMESCOPE_WSI_FORCE_BYPASS)" [ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter # Wine: DXVK/VKD3D over the builtins, X11 inside gamescope (winewayland would pick DroidDeck's compositor), @@ -262,7 +270,7 @@ prepare_prefix() { prefix_busy() { # a process of this prefix is running for p in /proc/[0-9]*; do [ "${p#/proc/}" = "$$" ] && continue - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 done return 1 } @@ -277,7 +285,7 @@ programs_left() { # a program of this prefix is still running, apart from Wine's ""|wineserver|services.exe|winedevice.exe|plugplay.exe|explorer.exe|svchost.exe|rpcss.exe|conhost.exe|start.exe|\ winemenubuilder|wineboot.exe|tabtip.exe) continue ;; esac - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0 done return 1 } @@ -286,7 +294,7 @@ stop_wine() { # wineserver -k, then whatever of this prefix is left (e.g. a game wineserver_ -k 2>/dev/null sleep 1 for p in /proc/[0-9]*; do - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue [ "${p#/proc/}" = "$$" ] && continue echo "$(date +%H:%M:%S) left over: ${p#/proc/} $(cat "$p/comm" 2>/dev/null)" kill -9 "${p#/proc/}" 2>/dev/null @@ -430,7 +438,7 @@ comm=$(echo "$name" | cut -c1-15) game_pids() { # processes of this prefix with the game's name (two prefixes can run programs with the same name) for p in $(grep -lFx "$comm" /proc/[0-9]*/comm 2>/dev/null); do p=${p%/comm} - tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}" + tr '\0' '\n' 2>/dev/null < "$p/environ" | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}" done } # The game's windows go straight to gamescope's X server, as with DroidDeck-Proton (no Wine desktop): the game diff --git a/tools/build_local.sh b/tools/build_local.sh index b5d15acea6..3c4feff55f 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -50,7 +50,7 @@ if ! command -v docker >/dev/null 2>&1; then echo "Docker is required to cross-compile the glibc ARM64 preload libraries." >&2 exit 1 fi -for tool in curl tar zstd shasum unzip python3 go; do +for tool in curl tar zstd shasum unzip python3 go rpm2cpio cpio; do if ! command -v "${tool}" >/dev/null 2>&1; then echo "${tool} is required to build the CI-equivalent APK." >&2 exit 1 @@ -540,6 +540,8 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then fi python3 tools/powervr/fetch.py bash tools/packs/build.sh app/build/packs +mkdir -p "${cache_dir}/ime" +python3 "${repo_root}/tools/ime/prepare.py" --packages "${cache_dir}/ime" --download --output "${linuxfs_dir}" python3 tools/release/runtime_inputs.py record ./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg} python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk" diff --git a/tools/ci/build-label.sh b/tools/ci/build-label.sh new file mode 100755 index 0000000000..806e0366fc --- /dev/null +++ b/tools/ci/build-label.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Exports the build metadata Gradle bakes into BuildConfig and prints the label for DROIDDECK_BUILD_LABEL. +set -euo pipefail +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 "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV" +echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV" +echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV" +echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/tools/components/README.md b/tools/components/README.md index 782d8b9f14..d1d5276311 100644 --- a/tools/components/README.md +++ b/tools/components/README.md @@ -10,13 +10,18 @@ flowchart LR Source[Pin source tree] --> Components[Prepare verified components] Source --> Xbox[Xbox ARM64 backend] Source --> Tests[Python and native tests] - Components --> APK[Compile APK and Android tests] + Components --> APK[Compile APK] Xbox --> APK APK --> Gate[Compile and test APK gate] Tests --> Gate Gate --> Publish[Main only: signing and publishing] ``` +Kotlin unit tests run in the separate `Unit tests` workflow (`unit-tests.yml`), so a +PR test build is published as soon as the APK compiles. Build validation folds both +workflows into the `Build APK` commit status, and Release APKs requires both for the +released commit. + All workers verify the same source tree. The component artifact records that tree, recipe identities and every output hash; the APK worker verifies the inventory before building. This handoff verifies consistency within the same CI run. It is diff --git a/tools/components/recipes.json b/tools/components/recipes.json index 1eff34a6bd..863cbb2633 100644 --- a/tools/components/recipes.json +++ b/tools/components/recipes.json @@ -15,6 +15,7 @@ "tools/msitools", "tools/pipewire", "tools/vr", + "tools/ime", "tools/gpuload", "tools/upscale/layer", "app/src/main/cpp/waylandcomp/generated", @@ -25,6 +26,10 @@ "outputs": [ "app/src/main/assets/linuxfs/usr/local/bin/gamescope", "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so", + "app/src/main/assets/linuxfs/usr/local/share/droiddeck/ime-files.json", + "app/src/main/assets/linuxfs/usr/local/share/droiddeck/ibus.profile", + "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ime/ibus-engine-pinyin", + "app/src/main/assets/linuxfs/usr/share/pyzy/db/android.db", "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so", "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/libVkLayer_droiddeck_upscale.so", "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-upscale-layer/VK_LAYER_DROIDDECK_upscale.json" @@ -35,7 +40,9 @@ "libc6-dev-arm64-cross", "g++-aarch64-linux-gnu", "libvulkan1", - "mesa-vulkan-drivers" + "mesa-vulkan-drivers", + "rpm2cpio", + "cpio" ] }, "esync": { diff --git a/tools/components/recipes/runtime.sh b/tools/components/recipes/runtime.sh index f395d5c862..81754b0e29 100644 --- a/tools/components/recipes/runtime.sh +++ b/tools/components/recipes/runtime.sh @@ -14,6 +14,8 @@ done 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 +mkdir -p app/build/ime-packages +python3 tools/ime/prepare.py --packages app/build/ime-packages --download --output "$D" if [ -f tools/gamescope/release.env ]; then . tools/gamescope/release.env curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst" diff --git a/tools/desktop-kde/README.md b/tools/desktop-kde/README.md index 53c6c5531b..ad72261024 100644 --- a/tools/desktop-kde/README.md +++ b/tools/desktop-kde/README.md @@ -71,7 +71,7 @@ both build jobs verify the Arch Linux ARM signature and pinned SHA-256 as for ev The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch, executable, library and build package hashes. Corresponding source is -https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz plus the patch in this repository. +https://download.kde.org/stable/plasma/6.8.3/kwin-6.8.3.tar.xz plus the patch in this repository. The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes. diff --git a/tools/desktop-kde/build-kwin.sh b/tools/desktop-kde/build-kwin.sh index d3620257c9..4775bcd689 100644 --- a/tools/desktop-kde/build-kwin.sh +++ b/tools/desktop-kde/build-kwin.sh @@ -6,7 +6,7 @@ here=$(cd "$(dirname "$0")" && pwd) source "$here/kwin.env" source "$here/mesa.env" version=$DESKTOP_KWIN_VERSION -source_sha=ea5e68d957c7d70abed97222a592d4445fda29129e20942658badd224ee138b4 +source_sha=fd5cb783f220ea4526a9afee2f72b582c3e87ef7f91b19bc5c7a6662ffe7fbdc mirror=https://fl.us.mirror.archlinuxarm.org/aarch64 builder=68B3537F39A313B3E574D06777193F152BDBE6A6 work=$(mktemp -d) diff --git a/tools/desktop-kde/kwin.env b/tools/desktop-kde/kwin.env index 6ad1968d5a..63b235e28f 100644 --- a/tools/desktop-kde/kwin.env +++ b/tools/desktop-kde/kwin.env @@ -1 +1 @@ -DESKTOP_KWIN_VERSION=6.8.2 +DESKTOP_KWIN_VERSION=6.8.3 diff --git a/tools/desktop-kde/overlay/usr/share/applications/droiddeck-return-gaming.desktop b/tools/desktop-kde/overlay/usr/share/applications/droiddeck-return-gaming.desktop deleted file mode 100644 index 67f1d7f218..0000000000 --- a/tools/desktop-kde/overlay/usr/share/applications/droiddeck-return-gaming.desktop +++ /dev/null @@ -1,9 +0,0 @@ -[Desktop Entry] -Name=Return to Gaming Mode -Comment=Log out of the desktop and go back to Steam -Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout -Icon=steamdeck-gaming-return -Terminal=false -Type=Application -StartupNotify=false -NoDisplay=true diff --git a/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE b/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE index 12938c69a7..5d8b01f6e4 100644 --- a/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE +++ b/tools/desktop-kde/overlay/usr/share/licenses/droiddeck-desktop/NOTICE @@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay) - steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme), GPL-3.0. -- kwin_wayland: KWin 6.8.2, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch. - Corresponding source: https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz and +- kwin_wayland: KWin 6.8.3, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch. + Corresponding source: https://download.kde.org/stable/plasma/6.8.3/kwin-6.8.3.tar.xz and https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches (the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package). diff --git a/tools/docker_platform.sh b/tools/docker_platform.sh index 3360c81ec0..40e38e7d97 100644 --- a/tools/docker_platform.sh +++ b/tools/docker_platform.sh @@ -4,7 +4,7 @@ if [[ -z "${docker_platform}" ]]; then fi case "${docker_platform}" in linux/arm64|linux/arm64/*) docker_platform=linux/arm64 ;; esac if [[ -z "${DROIDDECK_BUILD_IMAGE:-}" ]]; then - DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v4 + DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v5 [[ "${docker_platform}" == linux/arm64 ]] && DROIDDECK_BUILD_IMAGE+=-arm64 fi export DROIDDECK_DOCKER_PLATFORM=${docker_platform} DROIDDECK_BUILD_IMAGE diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 2a4341c514..831f5fbf89 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -750,13 +750,16 @@ def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict return {"code": code, "info": {"value": 0, "minimum": low, "maximum": high, "fuzz": 0, "flat": 0, "resolution": 0}} commands = [ - {"id": 1, "command": "register", "name": "DroidDeck agent pen", "bus": "virtual", "configuration": [ + # The bus comes after the codes: a `uinput` without the virtual bus fails on it with no "Error reading in + # object", while symbolic codes read first produce that message and send the script round again as numbers. + {"id": 1, "command": "register", "name": "DroidDeck agent pen", "configuration": [ {"type": "UI_SET_EVBIT", "data": ["EV_KEY", "EV_ABS"]}, {"type": "UI_SET_KEYBIT", "data": ["BTN_TOOL_PEN", "BTN_TOOL_RUBBER", "BTN_TOUCH", "BTN_STYLUS", "BTN_STYLUS2"]}, {"type": "UI_SET_ABSBIT", "data": ["ABS_X", "ABS_Y", "ABS_PRESSURE", "ABS_DISTANCE", "ABS_TILT_X", "ABS_TILT_Y"]}, {"type": "UI_SET_PROPBIT", "data": ["INPUT_PROP_DIRECT"]}, ], "abs_info": [axis("ABS_X", 0, width - 1), axis("ABS_Y", 0, height - 1), axis("ABS_PRESSURE", 0, UINPUT_PRESSURE), - axis("ABS_DISTANCE", 0, UINPUT_DISTANCE), axis("ABS_TILT_X", -90, 90), axis("ABS_TILT_Y", -90, 90)]}, + axis("ABS_DISTANCE", 0, UINPUT_DISTANCE), axis("ABS_TILT_X", -90, 90), axis("ABS_TILT_Y", -90, 90)], + "bus": "virtual"}, {"id": 1, "command": "delay", "duration": UINPUT_REGISTER_MS}, ] sent = {tool_key: 0, "BTN_TOUCH": 0, "BTN_STYLUS": 0, "BTN_STYLUS2": 0} @@ -792,27 +795,91 @@ def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict {"id": 1, "command": "sync", "syncToken": UINPUT_SYNC}] -def uinput_check(adb: str, serial: str) -> None: +def uinput_check(adb: str, serial: str) -> int: + """Checks the device can inject through `uinput` and returns its SDK level.""" probe = run_adb(adb, serial, "shell", - "command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput") + "command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput; " + "echo sdk=$(getprop ro.build.version.sdk)") if probe.returncode != 0: raise ControlError((probe.stdout + probe.stderr).decode(errors="replace").strip() or "adb shell failed", "ADB_FAILED") - missing = probe.stdout.decode(errors="replace").split() - if "no-uinput" in missing: + words = probe.stdout.decode(errors="replace").split() + if "no-uinput" in words: raise ControlError("This device's shell has no `uinput` command", "UINPUT_UNAVAILABLE") - if "no-dev-uinput" in missing: + if "no-dev-uinput" in words: raise ControlError("The ADB shell cannot write /dev/uinput on this device", "UINPUT_UNAVAILABLE") + sdk = next((w[4:] for w in words if w.startswith("sdk=")), "") + return int(sdk) if sdk.isdigit() else UINPUT_NAMED_SDK + + +# Android 14 QPR2 taught `uinput` symbolic event names, the `sync` command and the virtual bus. Earlier versions stop at +# the register line with "Error reading in object" before any device exists, so their scripts carry Linux's numeric +# codes, register on the USB bus and end without `sync`. SDK 34 covers both sides of QPR2, so it is tried named first. +UINPUT_NAMED_SDK = 34 +UINPUT_REJECTED = "Error reading in object" +UINPUT_CODES = { + "EV_SYN": 0, "EV_KEY": 1, "EV_ABS": 3, "SYN_REPORT": 0, "INPUT_PROP_DIRECT": 1, + "BTN_SOUTH": 304, "BTN_EAST": 305, "BTN_NORTH": 307, "BTN_WEST": 308, "BTN_TL": 310, "BTN_TR": 311, + "BTN_SELECT": 314, "BTN_START": 315, "BTN_MODE": 316, "BTN_THUMBL": 317, "BTN_THUMBR": 318, + "BTN_TOOL_PEN": 320, "BTN_TOOL_RUBBER": 321, "BTN_TOUCH": 330, "BTN_STYLUS": 331, "BTN_STYLUS2": 332, + "ABS_X": 0, "ABS_Y": 1, "ABS_RX": 3, "ABS_RY": 4, "ABS_HAT0X": 16, "ABS_HAT0Y": 17, + "ABS_PRESSURE": 24, "ABS_DISTANCE": 25, "ABS_TILT_X": 26, "ABS_TILT_Y": 27, +} +UINPUT_CONFIG_CODES = {"UI_SET_EVBIT": 100, "UI_SET_KEYBIT": 101, "UI_SET_ABSBIT": 103, "UI_SET_PROPBIT": 110} + + +def uinput_script(commands: list[dict], legacy: bool) -> str: + """The `uinput -` input: as written, or for [legacy] `uinput` numeric, on the USB bus and without `sync`.""" + if legacy: + def code(value): + return UINPUT_CODES[value] if isinstance(value, str) else value + + numeric = [] + for command in commands: + if command["command"] == "sync": + continue + command = dict(command) + if command["command"] == "register": + if command.get("bus") == "virtual": + command["bus"] = "usb" + command["configuration"] = [{"type": UINPUT_CONFIG_CODES[c["type"]], "data": [code(d) for d in c["data"]]} + for c in command["configuration"]] + command["abs_info"] = [dict(a, code=code(a["code"])) for a in command.get("abs_info", [])] + elif command["command"] == "inject": + command["events"] = [code(e) for e in command["events"]] + numeric.append(command) + commands = numeric + return "".join(json.dumps(command) + "\n" for command in commands) + + +def uinput_finished(result: subprocess.CompletedProcess, token: str, legacy: bool) -> bool: + """Whether `uinput` ran the whole script: by its sync token, or for [legacy] `uinput` by a clean exit.""" + out = result.stdout.decode(errors="replace") + if not legacy: + return token in out + text = out + (result.stderr or b"").decode(errors="replace") + return result.returncode == 0 and "Error" not in text and "Exception" not in text + + +def uinput_run(adb: str, serial: str, sdk: int, commands: list[dict], token: str, + timeout: float) -> tuple[subprocess.CompletedProcess, bool]: + """Runs [commands] through `uinput -` in the form the device reads; returns the result and whether it finished.""" + legacy = sdk < UINPUT_NAMED_SDK + result = run_adb(adb, serial, "shell", "uinput", "-", stdin=uinput_script(commands, legacy).encode(), timeout=timeout) + out = result.stdout.decode(errors="replace") + if not legacy and UINPUT_REJECTED in out and token not in out: + legacy = True + result = run_adb(adb, serial, "shell", "uinput", "-", stdin=uinput_script(commands, legacy).encode(), timeout=timeout) + return result, uinput_finished(result, token, legacy) def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: - uinput_check(adb, serial) + sdk = uinput_check(adb, serial) viewport = input_viewport(run_adb(adb, serial, "shell", "dumpsys", "input").stdout.decode(errors="replace")) - script = "".join(json.dumps(command) + "\n" for command in uinput_commands(samples, tool, viewport)) started = time.monotonic() - result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(), - timeout=(UINPUT_REGISTER_MS + samples[-1]["t"] + UINPUT_TAIL_MS) / 1000 + 30) + result, finished = uinput_run(adb, serial, sdk, uinput_commands(samples, tool, viewport), UINPUT_SYNC, + (UINPUT_REGISTER_MS + samples[-1]["t"] + UINPUT_TAIL_MS) / 1000 + 30) elapsed = round((time.monotonic() - started) * 1000) - if UINPUT_SYNC not in result.stdout.decode(errors="replace"): + if not finished: detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:] raise ControlError(f"uinput stopped before the end of the gesture (exit {result.returncode})" + (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why", @@ -869,13 +936,12 @@ def gamepad_commands(buttons: list[str], hold: int, gap: int) -> list[dict]: def gamepad_uinput(adb: str, serial: str, buttons: list[str], hold: int, gap: int) -> dict: commands = gamepad_commands(buttons, hold, gap) - uinput_check(adb, serial) - script = "".join(json.dumps(command) + "\n" for command in commands) + sdk = uinput_check(adb, serial) started = time.monotonic() - result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(), - timeout=(UINPUT_REGISTER_MS + len(buttons) * (hold + gap) + UINPUT_TAIL_MS) / 1000 + 30) + result, finished = uinput_run(adb, serial, sdk, commands, GAMEPAD_SYNC, + (UINPUT_REGISTER_MS + len(buttons) * (hold + gap) + UINPUT_TAIL_MS) / 1000 + 30) elapsed = round((time.monotonic() - started) * 1000) - if GAMEPAD_SYNC not in result.stdout.decode(errors="replace"): + if not finished: detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:] raise ControlError(f"uinput stopped before the last button (exit {result.returncode})" + (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why", diff --git a/tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch b/tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch new file mode 100644 index 0000000000..31b8f2a557 --- /dev/null +++ b/tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch @@ -0,0 +1,45 @@ +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +index cebf1f5..b1a72d2 100644 +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -32,6 +32,7 @@ + #include + #include + #include ++#include + + #define PAGE_START(x) ((x) & ~(uintptr_t)(4095)) + #define PAGE_OFFSET(x) ((x) & 4095) +@@ -505,7 +506,12 @@ public: + auto PageSize = sysconf(_SC_PAGESIZE); + PageSize = PageSize > 0 ? PageSize : FEXCore::Utils::FEX_PAGE_SIZE; + ++ const auto [HostStackLow, HostStackHigh] = HostStackReservation(PageSize); ++ + do { ++ if (StackHint < HostStackHigh && StackHint + FULL_STACK_SIZE > HostStackLow && HostStackLow > FULL_STACK_SIZE) { ++ StackHint = (HostStackLow - FULL_STACK_SIZE) & ~static_cast(PageSize - 1); ++ } + // Allocate the base of the full 128MB stack range. + StackPointerBase = Handler->GuestMmap(Thread, reinterpret_cast(StackHint), FULL_STACK_SIZE, PROT_NONE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_GROWSDOWN | MAP_NORESERVE | MAP_FIXED_NOREPLACE, -1, 0); +@@ -793,6 +799,19 @@ public: + *AuxTabSize = sizeof(AuxType) * AuxVariables.size(); + } + ++ static std::pair HostStackReservation(uint64_t PageSize) { ++ struct prctl_mm_map map {}; ++ uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast(__builtin_frame_address(0)); ++ Top = (Top + PageSize - 1) & ~(PageSize - 1); ++ ++ constexpr uint64_t MinGap = 128ULL * 1024 * 1024; ++ const uint64_t MaxGap = std::max(Top / 6 * 5, MinGap); ++ struct rlimit Limit {}; ++ uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast(Limit.rlim_cur) : MinGap; ++ Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize; ++ return {Top > Gap ? Top - Gap : 0, Top}; ++ } ++ + // Get the current memory map from /proc/self/stat + static bool GetCurrentMap(struct prctl_mm_map& map) { + diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 974ba58ab6..045208fc51 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -21,9 +21,10 @@ library list, before anything is published. trip to Xwayland on the paint thread; with no image, wlserver's position is used as upstream does. - `0101-nested-wayland-cursor-routing.patch` - this app: `gamescope_cursor_composite=2` lets the nested Wayland session paint its cursor in the output using the real X pointer position; client - cursor surfaces are cleared to prevent a duplicate at the host pointer, while Gamescope's original - default host-cursor fallback is preserved when its no-keyboard-focus policy selects it. Empty - client cursor images and Gamescope's hidden flag still suppress the painted cursor. + cursor surfaces are cleared to prevent a duplicate at the host pointer, and so is Gamescope's + default host-cursor fallback, which would otherwise show a second arrow until Gamescope gets + keyboard focus. Empty client cursor images and Gamescope's hidden flag still suppress the + painted cursor. - `0110-wayland-backend-touch.patch` - this app: the nested Wayland backend bound only the host's pointer and keyboard, so a finger on the phone's screen never reached Steam. It now binds `wl_touch` too and hands each finger to wlserver's touch path (`wlserver_touchdown` / `motion` / @@ -484,3 +485,36 @@ not wait on fences attached to a dma-buf, so the composite now checks each outpu It picks the next image that is neither held by the host nor still being scanned out. Only when every free image is still on the display does it wait for one, up to 100 ms. On kernels that cannot attach the fence, the host keeps waiting itself and nothing changes. `tools/gamescope/tests/nested-swapchain.cpp` covers the choice and the busy check. + +## 0147 Wayland backend: a forwarded client buffer goes back to its client only after scanout + +When no composite is needed, gamescope hands a client's own buffer to the host compositor as a plane. The host now +releases a buffer as soon as the display latches the next one and leaves its release fence on the buffer's dma-buf. +gamescope returned the buffer to the client on that release, and a client whose Vulkan driver does not wait on +fences attached to a dma-buf then drew into it while the display was still scanning it out, which showed as black +tiles in compressed buffers. A forwarded client buffer now stays held until `poll(POLLOUT)` on its dma-buf reports +that the display has finished with it, on a waiter thread so nothing else blocks. A release that arrives after the +buffer was shown again is dropped, so the later release decides. A pending wait holds its own reference on the +buffer, since that later release can drop the host's reference before the wait ends. Composite output images keep the 0146 path, and a +host that waits for the fence itself releases buffers that are already idle, so nothing changes there. + +## 0148 Wayland backend: composite every frame when the host releases buffers before scanout + +With 0147 a forwarded client buffer stays held until the display has finished scanning it out, about one refresh after +the host releases it. Steam's web helper cycles three buffers of its own, so forwarding them held the Steam UI at 80 fps +on a 120 Hz screen (frames alternately one and two refreshes apart). The first time a forwarded buffer comes back while +it is still being scanned out, the backend now composites every frame into its own output images. Those are reused at +latch under 0146, and the client's buffers return as soon as the composite has read them: the Steam UI then runs at +the full 120 fps. Hosts that release a buffer only after scanout never take this path and keep forwarding. + +## 0998 Wayland backend: verified producer acquire fences for forwarded frames + +When the app opts in and the parent Wayland registry actually advertises +`droiddeck_frame_acquire_v1`, Gamescope offers a separate v1 acquire global +to nested clients. A validated native sync_file stays with one matching +surface attachment and commit generation. Pending fences go through the +existing readiness waiter; a failed fence never marks a frame ready. +Only a forwarded, unchanged source buffer can carry its completed fence to +the parent. Composited output, unsupported clients, older hosts, and X11 +continue through their existing paths. The host and producer do not need +to upgrade simultaneously to retain the existing copy fallback. diff --git a/tools/gamescope/build-in-arch.sh b/tools/gamescope/build-in-arch.sh index cf56408bff..a021265d39 100755 --- a/tools/gamescope/build-in-arch.sh +++ b/tools/gamescope/build-in-arch.sh @@ -46,6 +46,9 @@ cd "$WORK" g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \ tools/gamescope/tests/nested-swapchain.cpp -o pkg/test-nested-swapchain pkg/test-nested-swapchain +g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \ + tools/gamescope/tests/producer-acquire.cpp -o pkg/test-producer-acquire +env -u GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE pkg/test-producer-acquire rm -rf out && mkdir -p out/usr/local/bin PKG=$(ls pkg/arch/gamescope-*.pkg.tar.* | grep -v -- '-debug-' | head -1) tar -xf "$PKG" -C out --strip-components=2 usr/bin/gamescope @@ -60,6 +63,11 @@ echo "NEEDED: $NEEDED" MISSING="" for lib in $NEEDED; do grep -qx "$lib" tools/gamescope/runtime-sonames.txt || MISSING="$MISSING $lib"; done if [ -n "$MISSING" ]; then echo "ERROR: not in the runtime:$MISSING"; exit 3; fi +# The signed APK can distinguish the negotiated release from earlier Gamescope +# assets; leave the feature unavailable rather than relying on a filename. +LC_ALL=C grep -aFq 'GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE' out/usr/local/bin/gamescope +mkdir -p out/usr/local/share/droiddeck +printf 'droiddeck-producer-acquire-v1\n' > out/usr/local/share/droiddeck/gamescope-producer-acquire-v1 (cd out && tar --use-compress-program='zstd -19' -cf ../gamescope.tzst usr) sha256sum gamescope.tzst | tee gamescope.tzst.sha256 ls -l gamescope.tzst out/usr/local/bin/gamescope diff --git a/tools/gamescope/patches/0101-nested-wayland-cursor-routing.patch b/tools/gamescope/patches/0101-nested-wayland-cursor-routing.patch index f59201e672..0a4805a839 100644 --- a/tools/gamescope/patches/0101-nested-wayland-cursor-routing.patch +++ b/tools/gamescope/patches/0101-nested-wayland-cursor-routing.patch @@ -74,7 +74,7 @@ index 0000000..d7c21da + + constexpr bool CursorShouldBeForwardedToHost( int cursorCompositeMode, bool useHostCursorFallback ) + { -+ return cursorCompositeMode != 2 || useHostCursorFallback; ++ return cursorCompositeMode != 2; + } + + constexpr bool CursorImageShouldBePainted( bool imageEmpty, bool cursorHidden ) @@ -176,10 +176,10 @@ index 0000000..9c622db + REQUIRE( CursorShouldBeComposited( 2, false, false, true, false ) ); +} + -+TEST_CASE("manual composition retains only the no-focus default cursor fallback", "[cursor_routing]") ++TEST_CASE("manual composition never forwards a cursor to the host", "[cursor_routing]") +{ + REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, false ) ); -+ REQUIRE( CursorShouldBeForwardedToHost( 2, true ) ); ++ REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, true ) ); + REQUIRE( CursorShouldBeForwardedToHost( 1, false ) ); + REQUIRE( CursorShouldBeForwardedToHost( 0, false ) ); +} diff --git a/tools/gamescope/patches/0147-forwarded-buffers-wait-for-scanout.patch b/tools/gamescope/patches/0147-forwarded-buffers-wait-for-scanout.patch new file mode 100644 index 0000000000..61e3af5b09 --- /dev/null +++ b/tools/gamescope/patches/0147-forwarded-buffers-wait-for-scanout.patch @@ -0,0 +1,355 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 12f0f50..d9db2e6 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -3,24 +3,28 @@ + #include "wlserver.hpp" + #include "vblankmanager.hpp" + #include "steamcompmgr.hpp" + #include "edid.h" + #include "Utils/Defer.h" + #include "Utils/Algorithm.h" + #include "convar.h" + #include "refresh_rate.h" + #include "waitable.h" + #include "Utils/TempFiles.h" + #include "Utils/CursorRouting.h" + #include "Utils/WaylandScaling.h" ++#include "output_image_pick.hpp" ++ ++#include ++#include + + #include + #include + #include + #include + #include + #include + #include + #include + #include + + #include "wlr_begin.hpp" +@@ -485,44 +489,86 @@ namespace gamescope + + // One backing plane plus every layer steamcompmgr can hand us. + CWaylandPlane m_Planes[k_nMaxLayers + 1]; + bool m_bVisible = true; + std::atomic m_bDesiredFullscreenState = { false }; + + bool m_bHostCompositorIsCurrentlyVRR = false; + }; + + class CWaylandFb final : public CBaseBackendFb + { + public: +- CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer ); ++ CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer, int nDmabufFd = -1 ); + ~CWaylandFb(); + + void OnCompositorAcquire(); + void OnCompositorRelease(); ++ void OnScanoutDone( uint64_t ulAcquireSerial ); + + wl_buffer *GetHostBuffer() const { return m_pHostBuffer; } + wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; } + + bool HeldByHost() const override { return m_bCompositorAcquired; } + + void Wayland_Buffer_Release( wl_buffer *pBuffer ); + static const wl_buffer_listener s_BufferListener; + + private: + CWaylandBackend *m_pBackend = nullptr; + wl_buffer *m_pHostBuffer = nullptr; + wlr_buffer *m_pClientBuffer = nullptr; ++ int m_nDmabufFd = -1; ++ std::mutex m_AcquireMutex; ++ uint64_t m_ulAcquireSerial = 0; + bool m_bCompositorAcquired = false; + }; ++ ++ class CWaylandScanoutRelease final : public IWaitable ++ { ++ public: ++ CWaylandScanoutRelease( CWaylandFb *pFb, int nFd, uint64_t ulAcquireSerial ) ++ : m_pFb{ pFb } ++ , m_nFd{ nFd } ++ , m_ulAcquireSerial{ ulAcquireSerial } ++ { ++ // A later acquire and release can drop the compositor's reference before this wait ends. ++ m_pFb->IncRef(); ++ } ++ ++ ~CWaylandScanoutRelease() { m_pFb->DecRef(); } ++ ++ int GetFD() override { return m_nFd; } ++ void OnPollOut() override { Finish(); } ++ void OnPollHangUp() override { Finish(); } ++ ++ static CAsyncWaiter<> &Waiter() ++ { ++ static CAsyncWaiter<> s_Waiter{ "gamescope-scanout" }; ++ return s_Waiter; ++ } ++ ++ private: ++ void Finish() ++ { ++ Waiter().RemoveWaitable( this ); ++ m_pFb->OnScanoutDone( m_ulAcquireSerial ); ++ close( m_nFd ); ++ delete this; ++ } ++ ++ CWaylandFb *m_pFb; ++ int m_nFd; ++ uint64_t m_ulAcquireSerial; ++ }; + const wl_buffer_listener CWaylandFb::s_BufferListener = + { + .release = WAYLAND_USERDATA_TO_THIS( CWaylandFb, Wayland_Buffer_Release ), + }; + + class CWaylandInputThread + { + public: + CWaylandInputThread(); + ~CWaylandInputThread(); + + bool Init( CWaylandBackend *pBackend ); +@@ -969,73 +1015,108 @@ namespace gamescope + .action = WAYLAND_NULL(), + }; + const zwp_primary_selection_source_v1_listener CWaylandBackend::s_PrimarySelectionSourceListener = + { + .send = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_PrimarySelectionSource_Send ), + .cancelled = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_PrimarySelectionSource_Cancelled ), + }; + + ////////////////// + // CWaylandFb + ////////////////// + +- CWaylandFb::CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer ) ++ CWaylandFb::CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer, int nDmabufFd ) + : CBaseBackendFb() + , m_pBackend { pBackend } + , m_pHostBuffer { pHostBuffer } ++ , m_nDmabufFd { nDmabufFd } + { + wl_buffer_add_listener( pHostBuffer, &s_BufferListener, this ); + } + + CWaylandFb::~CWaylandFb() + { + // I own the pHostBuffer. + wl_buffer_destroy( m_pHostBuffer ); + m_pHostBuffer = nullptr; ++ if ( m_nDmabufFd >= 0 ) ++ close( m_nDmabufFd ); + } + + void CWaylandFb::OnCompositorAcquire() + { +- // If the compositor has acquired us, track that +- // and increment the ref count. +- if ( !m_bCompositorAcquired ) ++ bool bTakeRef = false; + { ++ std::scoped_lock lock( m_AcquireMutex ); ++ m_ulAcquireSerial++; ++ bTakeRef = !m_bCompositorAcquired; + m_bCompositorAcquired = true; +- IncRef(); + } ++ ++ if ( bTakeRef ) ++ IncRef(); + } + + void CWaylandFb::OnCompositorRelease() + { +- // Compositor has released us, decrement rc. +- //assert( m_bCompositorAcquired ); ++ uint64_t ulSerial; ++ { ++ std::scoped_lock lock( m_AcquireMutex ); ++ ulSerial = m_ulAcquireSerial; ++ } ++ OnScanoutDone( ulSerial ); ++ } + +- if ( m_bCompositorAcquired ) ++ void CWaylandFb::OnScanoutDone( uint64_t ulAcquireSerial ) ++ { ++ bool bDropRef = false; + { ++ std::scoped_lock lock( m_AcquireMutex ); ++ if ( ulAcquireSerial != m_ulAcquireSerial ) ++ return; ++ bDropRef = m_bCompositorAcquired; + m_bCompositorAcquired = false; +- DecRef(); + } ++ ++ if ( bDropRef ) ++ DecRef(); + else +- { + xdg_log.errorf( "Compositor released us but we were not acquired. Oh no." ); +- } + } + + void CWaylandFb::Wayland_Buffer_Release( wl_buffer *pBuffer ) + { + assert( m_pHostBuffer ); + assert( m_pHostBuffer == pBuffer ); + + xdg_log.debugf( "buffer_release: %p", pBuffer ); + ++ if ( ShowsClientBuffer() && gamescope::DmabufScanoutPending( m_nDmabufFd ) ) ++ { ++ int nFd = fcntl( m_nDmabufFd, F_DUPFD_CLOEXEC, 0 ); ++ if ( nFd >= 0 ) ++ { ++ uint64_t ulSerial; ++ { ++ std::scoped_lock lock( m_AcquireMutex ); ++ ulSerial = m_ulAcquireSerial; ++ } ++ auto *pWait = new CWaylandScanoutRelease( this, nFd, ulSerial ); ++ if ( CWaylandScanoutRelease::Waiter().AddWaitable( pWait, EPOLLOUT | EPOLLHUP | EPOLLONESHOT ) ) ++ return; ++ delete pWait; ++ close( nFd ); ++ } ++ } ++ + OnCompositorRelease(); + } + + ////////////////// + // CWaylandConnector + ////////////////// + + CWaylandConnector::CWaylandConnector( CWaylandBackend *pBackend, uint64_t ulVirtualConnectorKey ) + : CBaseBackendConnector{ ulVirtualConnectorKey } + , m_pBackend( pBackend ) + , m_Planes{ this, this, this, this, this, this, this, this, this } + { +@@ -2349,25 +2430,26 @@ namespace gamescope + pDmaBuf->format, + 0u ); + + if ( !pImportedBuffer ) + { + xdg_log.errorf( "Failed to import dmabuf" ); + zwp_linux_buffer_params_v1_destroy( pBufferParams ); + return nullptr; + } + + zwp_linux_buffer_params_v1_destroy( pBufferParams ); + +- return new CWaylandFb{ this, pImportedBuffer }; ++ int nDmabufFd = pDmaBuf->n_planes > 0 ? fcntl( pDmaBuf->fd[0], F_DUPFD_CLOEXEC, 0 ) : -1; ++ return new CWaylandFb{ this, pImportedBuffer, nDmabufFd }; + } + + bool CWaylandBackend::UsesModifiers() const + { + if ( !cv_wayland_use_modifiers ) + return false; + + return m_bCanUseModifiers; + } + std::span CWaylandBackend::GetSupportedModifiers( uint32_t uDrmFormat ) const + { + auto iter = m_FormatModifiers.find( uDrmFormat ); +diff --git a/src/backend.cpp b/src/backend.cpp +index cc91853..ec59c8b 100644 +--- a/src/backend.cpp ++++ b/src/backend.cpp +@@ -109,41 +109,47 @@ namespace gamescope + wlserver_unlock(); + } + + // Potentially release now! + DecRefPrivate(); + } + + return uRefCount; + } + + void CBaseBackendFb::SetBuffer( wlr_buffer *pClientBuffer ) + { ++ if ( pClientBuffer ) ++ m_bShowsClientBuffer = true; ++ + if ( m_pClientBuffer == pClientBuffer ) + return; + + assert( m_pClientBuffer == nullptr ); + m_pClientBuffer = pClientBuffer; + if ( GetRefCount() ) + { + wlserver_lock(); + wlr_buffer_lock( m_pClientBuffer ); + wlserver_unlock( false ); + } + + m_pReleasePoint = nullptr; + } + + void CBaseBackendFb::SetReleasePoint( std::shared_ptr pReleasePoint ) + { ++ if ( pReleasePoint ) ++ m_bShowsClientBuffer = true; ++ + if ( m_pReleasePoint == pReleasePoint ) + return; + + m_pReleasePoint = pReleasePoint; + + if ( m_pClientBuffer && GetRefCount() ) + { + wlserver_lock(); + wlr_buffer_unlock( m_pClientBuffer ); + wlserver_unlock(); + m_pClientBuffer = nullptr; + } +diff --git a/src/backend.h b/src/backend.h +index 30b42ca..9a27711 100644 +--- a/src/backend.h ++++ b/src/backend.h +@@ -303,26 +303,29 @@ namespace gamescope + public: + CBaseBackendFb(); + virtual ~CBaseBackendFb(); + + uint32_t IncRef() override; + uint32_t DecRef() override; + + void SetBuffer( wlr_buffer *pClientBuffer ) override; + void SetReleasePoint( std::shared_ptr pReleasePoint ) override; + + virtual IBackendFb *EnsureImported() override { return this; }; + ++ bool ShowsClientBuffer() const { return m_bShowsClientBuffer; } ++ + private: + wlr_buffer *m_pClientBuffer = nullptr; ++ std::atomic m_bShowsClientBuffer = { false }; + std::shared_ptr m_pReleasePoint; + }; + + class IBackend + { + public: + virtual ~IBackend() {} + + virtual bool Init() = 0; + virtual bool PostInit() = 0; + virtual std::span GetInstanceExtensions() const = 0; + virtual std::span GetDeviceExtensions( VkPhysicalDevice pVkPhysicalDevice ) const = 0; diff --git a/tools/gamescope/patches/0148-composite-when-host-releases-before-scanout.patch b/tools/gamescope/patches/0148-composite-when-host-releases-before-scanout.patch new file mode 100644 index 0000000000..e7f872ac0e --- /dev/null +++ b/tools/gamescope/patches/0148-composite-when-host-releases-before-scanout.patch @@ -0,0 +1,116 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index d9db2e6..5c4cd86 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -804,24 +804,31 @@ namespace gamescope + { + auto iter = m_pOutputs.find( pOutput ); + if ( iter == m_pOutputs.end() ) + return nullptr; + + return &iter->second; + } + + wl_region *GetEmptyRegion() const { return m_pEmptyRegion; } + wl_region *GetFullRegion() const { return m_pFullRegion; } + CWaylandFb *GetBlackFb() const { return m_BlackFb.get(); } + ++ bool HostReleasesBeforeScanout() const { return m_bHostReleasesBeforeScanout; } ++ void OnHostReleasedBeforeScanout() ++ { ++ if ( !m_bHostReleasesBeforeScanout.exchange( true ) ) ++ xdg_log.infof( "Host releases buffers before scanout ends: compositing every frame into our own images" ); ++ } ++ + void OnConnectorDestroyed( CWaylandConnector *pConnector ) + { + m_pFocusConnector.compare_exchange_strong( pConnector, nullptr ); + } + + private: + + void Wayland_Registry_Global( wl_registry *pRegistry, uint32_t uName, const char *pInterface, uint32_t uVersion ); + static const wl_registry_listener s_RegistryListener; + + void Wayland_Modifier( zwp_linux_dmabuf_v1 *pDmabuf, uint32_t uFormat, uint32_t uModifierHi, uint32_t uModifierLo ); + +@@ -871,24 +878,25 @@ namespace gamescope + + wl_display *m_pDisplay = nullptr; + wl_shm *m_pShm = nullptr; + wl_compositor *m_pCompositor = nullptr; + wp_single_pixel_buffer_manager_v1 *m_pSinglePixelBufferManager = nullptr; + wl_subcompositor *m_pSubcompositor = nullptr; + zwp_linux_dmabuf_v1 *m_pLinuxDmabuf = nullptr; + xdg_wm_base *m_pXdgWmBase = nullptr; + wp_viewporter *m_pViewporter = nullptr; + wl_region *m_pEmptyRegion = nullptr; + wl_region *m_pFullRegion = nullptr; + Rc m_BlackFb; ++ std::atomic m_bHostReleasesBeforeScanout = { false }; + OwningRc m_pOwnedBlackFb; + OwningRc m_pBlackTexture; + wp_presentation *m_pPresentation = nullptr; + droiddeck_refresh_v1 *m_pHostRefresh = nullptr; + std::array m_HostRefreshRates{}; + std::atomic m_uHostRefreshRateCount = { 0 }; + std::vector m_PendingHostRefreshRates; + int m_nSentHostRefresh = 0; + int m_nSentHostFrameRate = 0; + frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr; + wp_color_manager_v1 *m_pWPColorManager = nullptr; + wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{}; +@@ -1083,24 +1091,25 @@ namespace gamescope + xdg_log.errorf( "Compositor released us but we were not acquired. Oh no." ); + } + + void CWaylandFb::Wayland_Buffer_Release( wl_buffer *pBuffer ) + { + assert( m_pHostBuffer ); + assert( m_pHostBuffer == pBuffer ); + + xdg_log.debugf( "buffer_release: %p", pBuffer ); + + if ( ShowsClientBuffer() && gamescope::DmabufScanoutPending( m_nDmabufFd ) ) + { ++ m_pBackend->OnHostReleasedBeforeScanout(); + int nFd = fcntl( m_nDmabufFd, F_DUPFD_CLOEXEC, 0 ); + if ( nFd >= 0 ) + { + uint64_t ulSerial; + { + std::scoped_lock lock( m_AcquireMutex ); + ulSerial = m_ulAcquireSerial; + } + auto *pWait = new CWaylandScanoutRelease( this, nFd, ulSerial ); + if ( CWaylandScanoutRelease::Waiter().AddWaitable( pWait, EPOLLOUT | EPOLLHUP | EPOLLONESHOT ) ) + return; + delete pWait; +@@ -1194,24 +1203,27 @@ namespace gamescope + plane.Present( nullptr ); + } + else + { + // TODO: Dedupe some of this composite check code between us and drm.cpp + bool bLayer0ScreenSize = close_enough(pFrameInfo->layers.get( 0 ).scale.x, 1.0f) && close_enough(pFrameInfo->layers.get( 0 ).scale.y, 1.0f); + + GamescopeUpscaleFilter eLayer0Filter = pFrameInfo->layers.get( 0 ).filter; + bool bNeedsCompositeFromFilter = ( eLayer0Filter == GamescopeUpscaleFilter::NEAREST || + eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize; + + bNeedsFullComposite |= cv_composite_force; ++ // A forwarded buffer would stay out of its client's hands until scanout ends, which caps a ++ // three-image client at two thirds of the refresh rate. Our own output images are reused at latch. ++ bNeedsFullComposite |= m_pBackend->HostReleasesBeforeScanout(); + bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes; + bNeedsFullComposite |= pFrameInfo->useFSRLayer0; + bNeedsFullComposite |= pFrameInfo->useNISLayer0; + bNeedsFullComposite |= pFrameInfo->useSGSRLayer0; + bNeedsFullComposite |= pFrameInfo->blurLayer0; + bNeedsFullComposite |= bNeedsCompositeFromFilter; + bNeedsFullComposite |= g_bColorSliderInUse; + bNeedsFullComposite |= pFrameInfo->bFadingOut; + bNeedsFullComposite |= !g_reshade_effect.empty(); + + if ( g_bOutputHDREnabled ) + bNeedsFullComposite |= g_bHDRItmEnable; diff --git a/tools/gamescope/patches/0998-forward-verified-producer-acquire-fences.patch b/tools/gamescope/patches/0998-forward-verified-producer-acquire-fences.patch new file mode 100644 index 0000000000..d7826b51f1 --- /dev/null +++ b/tools/gamescope/patches/0998-forward-verified-producer-acquire-fences.patch @@ -0,0 +1,693 @@ +diff --git a/protocol/droiddeck-frame-acquire-v1.xml b/protocol/droiddeck-frame-acquire-v1.xml +new file mode 100644 +index 0000000..f056b6e +--- /dev/null ++++ b/protocol/droiddeck-frame-acquire-v1.xml +@@ -0,0 +1,43 @@ ++ ++ ++ ++ ++ Optional explicit acquire sideband independent of DRM syncobj and buffer ++ allocation. Binding does not opt the client out of ordinary wl_buffer ++ release or existing synchronization protocols. The server advertises it ++ only when it implements all semantics for the selected display path. ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ After wl_surface.attach of a non-null buffer, and before its next ++ wl_surface.commit, send the producer's final writer fence for that ++ exact attachment. This outer probe requires that fence to have already ++ successfully signaled. The fence must be a real Linux sync_file, not a ++ dma-buf, eventfd, or Vulkan OPAQUE_FD. The server consumes its received ++ descriptor once for that attachment; the caller closes its local FD ++ after marshalling. ++ ++ The receiver validates the matching pending surface and buffer and ++ validates the descriptor. A duplicate, invalid, pending or mismatched ++ request is a protocol error; it is never downgraded to implicit sync. Another attach (even the same ++ wl_buffer), detach, surface/resource loss or supersession makes the ++ old proof inapplicable. Metadata-only commits may amend receiver-side ++ still-pending state but cannot introduce or re-use a fence themselves. ++ If no request was made, the receiver keeps its established safe path. ++ If a valid fence has been accepted and later the layer is ineligible, ++ the buffer must not be copied/read before that fence is satisfied or ++ imported as the source dependency. Transport never implies readiness ++ on missed deadlines and never changes release/retirement requirements. ++ ++ ++ ++ ++ ++ ++ +diff --git a/protocol/droiddeck-game-frame-acquire-v1.xml b/protocol/droiddeck-game-frame-acquire-v1.xml +new file mode 100644 +index 0000000..1b8c2a5 +--- /dev/null ++++ b/protocol/droiddeck-game-frame-acquire-v1.xml +@@ -0,0 +1,17 @@ ++ ++ ++ ++ ++ Immediately after wl_surface.attach and before the associated nonempty ++ commit, submit the successful or pending Linux sync_file representing the ++ final writer of that exact attachment. The caller closes its descriptor ++ after marshalling. This does not change wl_buffer release semantics. ++ Without a genuine positive descriptor, omit the sideband. ++ ++ ++ ++ ++ ++ ++ ++ +diff --git a/protocol/meson.build b/protocol/meson.build +index 71fe31b..1e56fbf 100644 +--- a/protocol/meson.build ++++ b/protocol/meson.build +@@ -44,6 +44,8 @@ protocols = [ + 'gamescope-action-binding.xml', + + 'droiddeck-refresh-v1.xml', ++ 'droiddeck-game-frame-acquire-v1.xml', ++ 'droiddeck-frame-acquire-v1.xml', + + # wlroots protocols + 'wlr-layer-shell-unstable-v1.xml', +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 45e32f3..e5cb845 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -43,6 +43,7 @@ + #include + #include + #include ++#include + #include "wlr_end.hpp" + + #include "drm_include.h" +@@ -143,6 +144,7 @@ namespace gamescope + struct WaylandPlaneState + { + wl_buffer *pBuffer; ++ std::shared_ptr pProducerFence; + int32_t nDestX; + int32_t nDestY; + double flSrcX; +@@ -755,6 +757,8 @@ namespace gamescope + virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override; + + std::span GetHostRefreshRates() const; ++ droiddeck_frame_acquire_v1 *GetHostAcquire() const { return m_pHostAcquire; } ++ bool SupportsDroidDeckProducerAcquire() const override { return m_pHostAcquire != nullptr; } + void SyncHostRefreshTarget(); + virtual bool SupportsExplicitSync() const override; + +@@ -893,6 +897,7 @@ namespace gamescope + OwningRc m_pBlackTexture; + wp_presentation *m_pPresentation = nullptr; + droiddeck_refresh_v1 *m_pHostRefresh = nullptr; ++ droiddeck_frame_acquire_v1 *m_pHostAcquire = nullptr; + std::array m_HostRefreshRates{}; + std::atomic m_uHostRefreshRateCount = { 0 }; + std::vector m_PendingHostRefreshRates; +@@ -1613,6 +1618,8 @@ namespace gamescope + { + std::unique_lock lock( m_PlaneStateLock ); + m_oCurrentPlaneState = oState; ++ if (m_oCurrentPlaneState) ++ m_oCurrentPlaneState->pProducerFence.reset(); + } + + if ( oState ) +@@ -1760,6 +1767,12 @@ namespace gamescope + // The x/y here does nothing? Why? What is it for... + // Use the subsurface set_position thing instead. + wl_surface_attach( m_pSurface, oState->pBuffer, 0, 0 ); ++ if ( auto *manager = m_pBackend->GetHostAcquire(); manager && oState->pProducerFence ) ++ { ++ const int fd = oState->pProducerFence->SignaledFd(); ++ if (fd >= 0) ++ droiddeck_frame_acquire_v1_set_acquire_fence(manager, m_pSurface, oState->pBuffer, fd); ++ } + wl_surface_damage( m_pSurface, 0, 0, INT32_MAX, INT32_MAX ); + wl_surface_set_opaque_region( m_pSurface, oState->bOpaque ? m_pBackend->GetFullRegion() : nullptr ); + wl_surface_set_buffer_scale( m_pSurface, 1 ); +@@ -1815,6 +1828,7 @@ namespace gamescope + ClipPlane( WaylandPlaneState + { + .pBuffer = pBuffer, ++ .pProducerFence = pLayer->pProducerFence, + .nDestX = int32_t( -pLayer->offset.x ), + .nDestY = int32_t( -pLayer->offset.y ), + .flSrcX = 0.0, +@@ -2812,6 +2826,12 @@ namespace gamescope + wl_output_add_listener( pOutput , &s_OutputListener, this ); + m_pOutputs.emplace( std::make_pair( std::move( pOutput ), WaylandOutputInfo{} ) ); + } ++ else if ( droiddeck::ProducerAcquireEnabled() && ++ uVersion >= 1 && !strcmp( pInterface, droiddeck_frame_acquire_v1_interface.name ) && !m_pHostAcquire ) ++ { ++ m_pHostAcquire = static_cast( ++ wl_registry_bind( pRegistry, uName, &droiddeck_frame_acquire_v1_interface, 1u ) ); ++ } + else if ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) ) + { + m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u ); +diff --git a/src/WaylandServer/WaylandServerLegacy.h b/src/WaylandServer/WaylandServerLegacy.h +index 63ee2ca..0164853 100644 +--- a/src/WaylandServer/WaylandServerLegacy.h ++++ b/src/WaylandServer/WaylandServerLegacy.h +@@ -3,9 +3,11 @@ + #include + #include "WaylandDecls.h" + #include ++#include + #include + #include + #include "vulkan_include.h" ++#include "droiddeck_producer_fence.hpp" + + + #include "wlr_begin.hpp" +@@ -57,6 +59,10 @@ struct wlserver_wl_surface_info + uint64_t desired_present_time = 0; + + uint64_t last_refresh_cycle = 0; ++ const void *producerPendingAttachment = nullptr; ++ droiddeck::PendingProducerFence producerFence; ++ std::unordered_map committedProducerFences; ++ struct wl_listener producerFenceClientCommit; + }; + + wlserver_wl_surface_info *get_wl_surface_info(struct wlr_surface *wlr_surf); +diff --git a/src/backend.h b/src/backend.h +index 9a27711..9fe0c15 100644 +--- a/src/backend.h ++++ b/src/backend.h +@@ -377,6 +377,7 @@ namespace gamescope + virtual bool IsSessionBased() const = 0; + + virtual bool SupportsExplicitSync() const = 0; ++ virtual bool SupportsDroidDeckProducerAcquire() const { return false; } + + // Dumb helper we should remove to support multi display someday. + gamescope::GamescopeScreenType GetScreenType() +diff --git a/src/commit.cpp b/src/commit.cpp +index fbfb550..cd35202 100644 +--- a/src/commit.cpp ++++ b/src/commit.cpp +@@ -55,7 +55,9 @@ void commit_t::OnPollIn() + + { + std::unique_lock lock( m_WaitableCommitStateMutex ); +- if ( !CloseFenceInternal() ) ++ const bool bFailedProducerFence = m_bProducerFence && ++ droiddeck::ProducerFenceStatus(m_nCommitFence) != 1; ++ if ( !CloseFenceInternal() || bFailedProducerFence ) + return; + } + +@@ -115,12 +117,13 @@ bool commit_t::CloseFenceInternal() + return true; + } + +-void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame ) ++void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame, bool bProducerFence ) + { + std::unique_lock lock( m_WaitableCommitStateMutex ); + CloseFenceInternal(); + + m_nCommitFence = nFence; ++ m_bProducerFence = bProducerFence; + m_bMangoNudge = bMangoNudge; + m_uMangoMsgType = uMangoMsgType; + m_bDroidDeckHudFrame = bDroidDeckHudFrame; +diff --git a/src/commit.h b/src/commit.h +index ae767b6..99b32ae 100644 +--- a/src/commit.h ++++ b/src/commit.h +@@ -35,13 +35,14 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + + // Returns true if we had a fence that was closed. + bool CloseFenceInternal(); +- void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame = false ); ++ void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame = false, bool bProducerFence = false ); + + bool ShouldPreemptivelyUpscale( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler ); + + struct wlr_buffer *buf = nullptr; + gamescope::Rc vulkanTex; + std::optional upscaledTexture; ++ std::shared_ptr pProducerFence; + + gamescope::Rc GetTexture( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler, GamescopeAppTextureColorspace &colorspace ) + { +@@ -79,6 +80,7 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + + std::mutex m_WaitableCommitStateMutex; + int m_nCommitFence = -1; ++ bool m_bProducerFence = false; + bool m_bMangoNudge = false; + // Typed mangoapp stream to nudge, 0 for none, never the legacy type. + uint32_t m_uMangoMsgType = 0; +diff --git a/src/droiddeck_producer_fence.hpp b/src/droiddeck_producer_fence.hpp +new file mode 100644 +index 0000000..5e7dd9d +--- /dev/null ++++ b/src/droiddeck_producer_fence.hpp +@@ -0,0 +1,67 @@ ++#pragma once ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace droiddeck ++{ ++ inline bool ProducerAcquireEnabled() ++ { ++ static const bool enabled = [] { ++ const char *value = std::getenv("GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE"); ++ return value && std::strcmp(value, "1") == 0; ++ }(); ++ return enabled; ++ } ++ ++ // Status 1 is success, 0 is pending, everything else is unsafe. ++ inline int ProducerFenceStatus(int fd) ++ { ++ sync_file_info info{}; ++ if (fd < 0 || ioctl(fd, SYNC_IOC_FILE_INFO, &info) < 0 || !info.num_fences) ++ return -1; ++ return info.status; ++ } ++ ++ class ProducerFence ++ { ++ public: ++ explicit ProducerFence(int fd) : m_fd(fd) {} ++ ProducerFence(ProducerFence &&other) noexcept : m_fd(other.TakeFd()) {} ++ ProducerFence(const ProducerFence &) = delete; ++ ProducerFence &operator=(const ProducerFence &) = delete; ++ ~ProducerFence() { if (m_fd >= 0) close(m_fd); } ++ ++ int SyncStatus() const { return ProducerFenceStatus(m_fd); } ++ int Dup() const { return m_fd < 0 ? -1 : fcntl(m_fd, F_DUPFD_CLOEXEC, 0); } ++ int SignaledFd() const { return SyncStatus() == 1 ? m_fd : -1; } ++ int Fd() const { return m_fd; } ++ int TakeFd() { return std::exchange(m_fd, -1); } ++ ++ private: ++ int m_fd; ++ }; ++ ++ // This slot belongs to one nested surface and is cleared by *every* ++ // attach request, even if the client reuses the same wl_buffer object. ++ struct PendingProducerFence ++ { ++ std::shared_ptr fence; ++ uint32_t sequence = 0; ++ const void *buffer = nullptr; ++ ++ std::shared_ptr Consume(bool attached, uint32_t seq, const void *current) ++ { ++ auto owned = std::exchange(fence, {}); ++ const bool same = attached && seq == sequence && current && current == buffer; ++ return same ? owned : nullptr; ++ } ++ }; ++} +diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp +index 8ae3b71..235cfc0 100644 +--- a/src/rendervulkan.hpp ++++ b/src/rendervulkan.hpp +@@ -281,6 +281,8 @@ enum AlphaBlendingMode_t + //#define DRM_MODE_BLEND_COVERAGE 1 + //#define DRM_MODE_BLEND_PIXEL_NONE 2 + ++namespace droiddeck { class ProducerFence; } ++ + struct FrameInfo_t + { + bool useFSRLayer0; +@@ -309,6 +311,7 @@ struct FrameInfo_t + struct Layer_t + { + gamescope::Rc tex; ++ std::shared_ptr pProducerFence; + int zpos; + + vec2_t offset; +@@ -378,6 +381,7 @@ struct FrameInfo_t + if ( m_nCount >= k_nMaxLayers ) + return nullptr; + ++ m_Layers[m_nCount].pProducerFence.reset(); + return &m_Layers[ m_nCount++ ]; + } + +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index c2e04ab..f5b744b 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -2559,6 +2559,7 @@ paint_cached_base_layer(const gamescope::Rc& commit, const BaseLayerIn + + layer->tex = commit->GetTexture( base.eUpscaleFilter, base.eUpscaleScaler, layer->colorspace ); + layer->filter = base.filter; ++ layer->pProducerFence = layer->tex == commit->vulkanTex ? commit->pProducerFence : nullptr; + if ( layer->tex == commit->vulkanTex ) + { + if ( base.uOutputWidth == currentOutputWidth && base.uOutputHeight == currentOutputHeight ) +@@ -2670,6 +2671,7 @@ paint_window_commit( const gamescope::Rc &lastCommit, steamcompmgr_win + layer->filter = ( flags & PaintWindowFlag::NoFilter ) ? GamescopeUpscaleFilter::LINEAR : frameInfo->eUpscaleFilter; + + layer->tex = lastCommit->GetTexture( layer->filter, frameInfo->eUpscaleScaler, layer->colorspace ); ++ layer->pProducerFence = layer->tex == lastCommit->vulkanTex ? lastCommit->pProducerFence : nullptr; + + if ( flags & PaintWindowFlag::NoScale ) + { +@@ -8915,7 +8917,7 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + already_exists = true; + } + +- if ( already_exists && !reslistentry.feedback && reslistentry.presentation_feedbacks.empty() ) ++ if ( already_exists && !reslistentry.pProducerFence && !reslistentry.feedback && reslistentry.presentation_feedbacks.empty() ) + { + wlserver_lock(); + wlr_buffer_unlock( buf ); +@@ -8957,6 +8959,8 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + droiddeck::frame_trace::Event::ImportSucceededOther, + bTraceCurrent ); + ++ newCommit->pProducerFence = std::move(reslistentry.pProducerFence); ++ const bool bProducerFence = bool(newCommit->pProducerFence); + int fence = -1; + global_focus_t *pCurrentFocus = GetCurrentFocus(); + +@@ -9104,7 +9108,24 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + pBackendFb->SetBuffer( buf ); + } + +- if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent ) ++ if ( bProducerFence ) ++ { ++ const int status = newCommit->pProducerFence->SyncStatus(); ++ if ( status != 0 && status != 1 ) ++ return; // A failed producer write may not be marked ready. ++ bKnownReady = status == 1; ++ if ( !bKnownReady ) ++ { ++ fence = newCommit->pProducerFence->Dup(); ++ if ( fence < 0 ) ++ { ++ // Still wait on original; this commit cannot forward proof. ++ fence = newCommit->pProducerFence->TakeFd(); ++ newCommit->pProducerFence.reset(); ++ } ++ } ++ } ++ else if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent ) + { + fence = eventFd.first; + bKnownReady = eventFd.second; +@@ -9127,13 +9148,13 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + + if ( cv_commit_ready_check ) + { +- if ( !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) ) ++ if ( !bProducerFence && !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) ) + bKnownReady = true; + note_commit_fence( bKnownReady ); + } + gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 ); + { +- newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted() ); ++ newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted(), bProducerFence ); + if ( bKnownReady ) + { + newCommit->Signal(); +diff --git a/src/wlserver.cpp b/src/wlserver.cpp +index 84602c0..6a4f4da 100644 +--- a/src/wlserver.cpp ++++ b/src/wlserver.cpp +@@ -57,6 +57,7 @@ + #include "gamescope-private-protocol.h" + #include "gamescope-swapchain-protocol.h" + #include "presentation-time-protocol.h" ++#include "droiddeck-game-frame-acquire-v1-protocol.h" + + #include "wlserver.hpp" + #include "hdmi.h" +@@ -136,7 +137,8 @@ std::vector& gamescope_xwayland_server_t::retrieve_commits() + + gamescope::ConVar cv_drm_debug_syncobj_force_wait_on_commit( "drm_debug_syncobj_force_wait_on_commit", false, "Force a wait on DRM sync objects before committing buffers" ); + +-ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf ) ++ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf, ++ std::shared_ptr pProducerFence ) + { + auto wl_surf = get_wl_surface_info( surf ); + +@@ -168,7 +170,8 @@ ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf ) + wl_surf->present_id, + wl_surf->desired_present_time, + std::move( pAcquirePoint ), +- std::move( pReleasePoint ) ++ std::move( pReleasePoint ), ++ bExplicitSync ? nullptr : std::move( pProducerFence ) + }; + wl_surf->present_id = std::nullopt; + wl_surf->desired_present_time = 0; +@@ -216,6 +219,12 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) { + ? droiddeck::frame_trace::Event::SurfaceCommitBuffer + : droiddeck::frame_trace::Event::SurfaceCommitNoBuffer ); + ++ // Capture state before the existing damage/attach flags are reset. ++ const bool bAttached = wlr_surface->current.committed & WLR_SURFACE_STATE_BUFFER; ++ auto &proofs = get_wl_surface_info(wlr_surface)->committedProducerFences; ++ auto proof = proofs.extract(wlr_surface->current.seq); ++ auto pProducerFence = proof.empty() ? nullptr : proof.mapped().Consume( ++ bAttached, wlr_surface->current.seq, wlr_surface->current.buffer ); + wlr_surface->current.committed = 0; + + wlserver_x11_surface_info *wlserver_x11_surface_info = get_wl_surface_info(wlr_surface)->x11_surface; +@@ -249,7 +258,14 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) { + + gpuvis_trace_printf( "xwayland_surface_commit wlr_surface %p", wlr_surface ); + +- ResListEntry_t entry = PrepareCommit( wlr_surface, buf ); ++ // A texture may still designate older storage after a rejected/no-op import. ++ if ( pProducerFence ) ++ { ++ struct wlr_dmabuf_attributes dmabuf{}; ++ if ( wlr_surface->current.buffer != buf || !wlr_buffer_get_dmabuf(buf, &dmabuf) ) ++ pProducerFence.reset(); ++ } ++ ResListEntry_t entry = PrepareCommit( wlr_surface, buf, std::move(pProducerFence) ); + + if (wlserver_x11_surface_info) + { +@@ -612,6 +628,31 @@ wlserver_wl_surface_info *get_wl_surface_info(struct wlr_surface *wlr_surf) + return reinterpret_cast(wlr_surf->data); + } + ++// This wlroots signal runs with its own pending.buffer lock, after the ++// pending object has been resolved and before the commit is applied or cached. ++static bool producer_fence_protocol_active(); ++ ++static void handle_producer_fence_client_commit(wl_listener *listener, void *) ++{ ++ wlserver_wl_surface_info *info = wl_container_of(listener, info, producerFenceClientCommit); ++ wlr_surface *surface = info->wlr; ++ info->producerPendingAttachment = nullptr; ++ auto proof = std::exchange(info->producerFence, {}); ++ if (!proof.fence || !surface->pending.buffer || proof.sequence != surface->pending.seq || ++ !(surface->pending.committed & WLR_SURFACE_STATE_BUFFER)) ++ return; ++ struct wlr_dmabuf_attributes dmabuf{}; ++ if (!wlr_buffer_get_dmabuf(surface->pending.buffer, &dmabuf) || ++ info->committedProducerFences.size() >= 64 || ++ info->committedProducerFences.contains(proof.sequence)) ++ { ++ wlr_surface_reject_pending(surface, surface->resource, 0, "invalid or excessive producer fence commits"); ++ return; ++ } ++ proof.buffer = surface->pending.buffer; // Borrowed from the state lock, no extra release path. ++ info->committedProducerFences.emplace(proof.sequence, std::move(proof)); ++} ++ + static void handle_wl_surface_commit( struct wl_listener *l, void *data ) + { + wlserver_wl_surface_info *surf = wl_container_of( l, surf, commit ); +@@ -707,6 +748,7 @@ static void handle_wl_surface_destroy( struct wl_listener *l, void *data ) + } + + wl_list_remove( &surf->commit.link ); ++ wl_list_remove(&surf->producerFenceClientCommit.link); + wl_list_remove( &surf->destroy.link ); + + delete surf; +@@ -725,6 +767,12 @@ static void wlserver_new_surface(struct wl_listener *l, void *data) + + wl_surface_info->commit.notify = handle_wl_surface_commit; + wl_signal_add( &wlr_surf->events.commit, &wl_surface_info->commit ); ++ wl_list_init(&wl_surface_info->producerFenceClientCommit.link); ++ if (producer_fence_protocol_active()) ++ { ++ wl_surface_info->producerFenceClientCommit.notify = handle_producer_fence_client_commit; ++ wl_signal_add(&wlr_surf->events.client_commit, &wl_surface_info->producerFenceClientCommit); ++ } + + wlr_surf->data = wl_surface_info; + +@@ -1811,6 +1859,79 @@ static bool filter_global(const struct wl_client *client, const struct wl_global + return server && server->get_output() == output; + } + ++static wl_protocol_logger *s_pProducerFenceLogger; ++static wl_global *s_pProducerFenceGlobal; ++ ++static bool producer_fence_protocol_active() ++{ ++ return s_pProducerFenceGlobal != nullptr; ++} ++ ++static void producer_fence_protocol_log( void *, wl_protocol_logger_type direction, ++ const wl_protocol_logger_message *message ) ++{ ++ if ( direction != WL_PROTOCOL_LOGGER_REQUEST || std::strcmp(message->message->name, "attach") || ++ std::strcmp(wl_resource_get_class(message->resource), wl_surface_interface.name) || ++ message->arguments_count != 3 ) ++ return; ++ auto *surf = wlr_surface_from_resource(message->resource); ++ if ( auto *info = get_wl_surface_info(surf) ) ++ { ++ info->producerFence = {}; ++ // Wayland's server demarshaller gives the wl_object at the start ++ // of the wl_resource. Compare identity only, never dereference it. ++ info->producerPendingAttachment = message->arguments[0].o; ++ } ++} ++ ++static void set_producer_fence( wl_client *client, wl_resource *manager, wl_resource *surface, ++ wl_resource *buffer, int32_t fd ) ++{ ++ droiddeck::ProducerFence fence(fd); ++ wlr_surface *surf = surface && wl_resource_get_client(surface) == client ++ ? wlr_surface_from_resource(surface) : nullptr; ++ auto *info = get_wl_surface_info(surf); ++ if (!info || !buffer || wl_resource_get_client(buffer) != client || ++ !(surf->pending.committed & WLR_SURFACE_STATE_BUFFER) || ++ info->producerPendingAttachment != buffer || info->producerFence.fence) ++ { ++ wl_resource_post_error(manager, 0, "invalid or duplicate producer fence attachment"); ++ return; ++ } ++ ++ const int status = fence.SyncStatus(); ++ if (status != 0 && status != 1) ++ { ++ wl_resource_post_error(manager, 0, "producer fence requires a real sync_file"); ++ return; ++ } ++ info->producerFence = { std::make_shared(std::move(fence)), ++ surf->pending.seq }; ++} ++ ++static const struct droiddeck_game_frame_acquire_v1_interface producer_fence_impl = { ++ .set_acquire_fence = set_producer_fence, ++}; ++ ++static void bind_producer_fence(wl_client *client, void *, uint32_t, uint32_t id) ++{ ++ auto *resource = wl_resource_create(client, &droiddeck_game_frame_acquire_v1_interface, 1, id); ++ if (!resource) ++ { ++ wl_client_post_no_memory(client); ++ return; ++ } ++ wl_resource_set_implementation(resource, &producer_fence_impl, nullptr, nullptr); ++} ++ ++static void stop_producer_fence_protocol() ++{ ++ if (s_pProducerFenceGlobal) ++ wl_global_destroy(std::exchange(s_pProducerFenceGlobal, nullptr)); ++ if (s_pProducerFenceLogger) ++ wl_protocol_logger_destroy(std::exchange(s_pProducerFenceLogger, nullptr)); ++} ++ + bool wlsession_init( void ) { + static bool s_bInitted = false; + if ( s_bInitted ) +@@ -1824,6 +1945,7 @@ bool wlsession_init( void ) { + + wl_display_set_global_filter(wlserver.display, filter_global, nullptr); + ++ + const struct wlserver_output_info output_info = { + .description = "Virtual gamescope output", + }; +@@ -2200,6 +2322,18 @@ void wlserver_set_keyboard_layout( const char *pszLayout ) + bool wlserver_init( void ) { + assert( wlserver.display != nullptr ); + ++ // The backend has round-tripped its parent registry before wlserver_init. ++ // Older hosts, non-Wayland backends or an unarmed host keep the original ++ // producer conventions: do not advertise this inner protocol at all. ++ if (droiddeck::ProducerAcquireEnabled() && GetBackend()->SupportsDroidDeckProducerAcquire()) ++ { ++ s_pProducerFenceLogger = wl_display_add_protocol_logger(wlserver.display, producer_fence_protocol_log, nullptr); ++ if (s_pProducerFenceLogger) ++ s_pProducerFenceGlobal = wl_global_create(wlserver.display, &droiddeck_game_frame_acquire_v1_interface, 1, nullptr, bind_producer_fence); ++ if (!s_pProducerFenceGlobal) ++ stop_producer_fence_protocol(); ++ } ++ + wl_list_init(&pending_surfaces); + + wlserver.wlr.multi_backend = wlr_multi_backend_create( wlserver.event_loop ); +@@ -2345,6 +2479,7 @@ bool wlserver_init( void ) { + { + wl_log.errorf("Failed to start backend"); + wlr_backend_destroy( wlserver.wlr.multi_backend ); ++ stop_producer_fence_protocol(); + wl_display_destroy(wlserver.display); + return false; + } +@@ -2527,6 +2662,7 @@ void wlserver_run(void) + wl_list_remove( &wlserver.session_active.link ); + #endif + ++ stop_producer_fence_protocol(); + wl_display_destroy_clients(wlserver.display); + wl_display_destroy(wlserver.display); + wlserver.display = NULL; +diff --git a/src/wlserver.hpp b/src/wlserver.hpp +index 63542ef..12141b6 100644 +--- a/src/wlserver.hpp ++++ b/src/wlserver.hpp +@@ -50,6 +50,7 @@ struct ResListEntry_t { + uint64_t desired_present_time; + std::shared_ptr pAcquirePoint; + std::shared_ptr pReleasePoint; ++ std::shared_ptr pProducerFence; + }; + + struct wlserver_content_override; diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index d6d9b277a0..fbced83679 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-f3a45b31 -GAMESCOPE_SHA256=3908af87b2ee8a328e9780fc805c6a7bddd11d7405b9992d717b94e16c019313 +GAMESCOPE_TAG=gamescope-3.16.29-verified-acquire-v1 +GAMESCOPE_SHA256=0861b5f6f694842eead87e4fd68f7b3cf93c35f10e1dccffd5ea3fc75081b97d diff --git a/tools/gamescope/tests/producer-acquire.cpp b/tools/gamescope/tests/producer-acquire.cpp new file mode 100644 index 0000000000..f99974a5e5 --- /dev/null +++ b/tools/gamescope/tests/producer-acquire.cpp @@ -0,0 +1,36 @@ +#include "droiddeck_producer_fence.hpp" +#include +#include +#include + +int main() +{ + using namespace droiddeck; + assert(!ProducerAcquireEnabled()); // normal startup, no opt-in + assert(ProducerFenceStatus(-1) < 0); + + int ends[2]; + assert(pipe(ends) == 0); + const int readEnd = ends[0]; + auto fd = std::make_shared(readEnd); + assert(fd->SyncStatus() < 0); // ordinary pipe must never become a ready writer fence + assert(fd->SignaledFd() < 0); + int a, b; + PendingProducerFence old{fd, 21, &a}; + assert(!old.Consume(true, 22, &a)); + assert(!old.fence); + PendingProducerFence different{fd, 21, &a}; + assert(!different.Consume(true, 21, &b)); + PendingProducerFence empty{fd, 21, &a}; + assert(!empty.Consume(false, 21, &a)); + PendingProducerFence matching{std::move(fd), 21, &a}; + auto consumed = matching.Consume(true, 21, &a); + assert(consumed && !matching.Consume(true, 21, &a)); // never clonable across commits + int dup = consumed->Dup(); + assert(dup >= 0 && fcntl(dup, F_GETFD) == FD_CLOEXEC); + consumed.reset(); + assert(fcntl(readEnd, F_GETFD) == -1 && errno == EBADF); + assert(fcntl(dup, F_GETFD) == FD_CLOEXEC); + close(dup); + close(ends[1]); +} diff --git a/tools/ime/packages.json b/tools/ime/packages.json new file mode 100644 index 0000000000..846dfebcea --- /dev/null +++ b/tools/ime/packages.json @@ -0,0 +1,27 @@ +{ + "version": 1, + "release": "Fedora 44 Everything aarch64", + "mirror": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/", + "packages": { + "ibus-pinyin": { + "filename": "ibus-pinyin-1.5.1-7.fc44.aarch64.rpm", + "url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/i/ibus-pinyin-1.5.1-7.fc44.aarch64.rpm", + "sha256": "fcae3a5f4263c005efa0751737bd653d4dca8ca53777362ad519f6bcbd99587c" + }, + "pyzy": { + "filename": "pyzy-0.1.0-37.fc44.aarch64.rpm", + "url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/p/pyzy-0.1.0-37.fc44.aarch64.rpm", + "sha256": "aa41dfdaa052ac5432e2fd4c64ea706a7153b6e7b72f18bf1633006f7190b76f" + }, + "pyzy-db-android": { + "filename": "pyzy-db-android-0.1.0-37.fc44.noarch.rpm", + "url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/p/pyzy-db-android-0.1.0-37.fc44.noarch.rpm", + "sha256": "bcaafe36fc93b892b1901607c887fd4efbc47eaa5b829bfe0347aa3137f41576" + }, + "lua-libs": { + "filename": "lua-libs-5.4.8-5.fc44.aarch64.rpm", + "url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/l/lua-libs-5.4.8-5.fc44.aarch64.rpm", + "sha256": "d719e35a8c2f771084f0b0d135a3ac68c51b032fc2199507685fe3ea32cee8fc" + } + } +} diff --git a/tools/ime/prepare.py b/tools/ime/prepare.py new file mode 100644 index 0000000000..be290f346f --- /dev/null +++ b/tools/ime/prepare.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Prepare the pinned pinyin engine and its runtime dependencies.""" + +import argparse +import hashlib +import json +from pathlib import Path, PurePosixPath +import shutil +import subprocess +import tempfile +import urllib.request +import xml.etree.ElementTree as ElementTree + +PACKAGES = Path(__file__).with_name('packages.json') +LIBRARY_DIR = 'usr/local/lib/droiddeck-ime' +ENGINE_NAME = 'ibus-engine-pinyin' +ENGINE_MEMBERS = ('usr/libexec/' + ENGINE_NAME, 'usr/bin/' + ENGINE_NAME) +COMPONENT = 'usr/share/ibus/component/pinyin.xml' +PROFILE = 'usr/local/share/droiddeck/ibus.profile' +MANIFEST = 'usr/local/share/droiddeck/ime-files.json' +LICENSES = 'usr/local/share/licenses/droiddeck-ime' +PROFILE_TEXT = 'user-db:user\nsystem-db:ibus\n' +# The engine links these by soname, so the dereferenced copies keep the RPM member names. +LIBRARIES = {'pyzy': ('usr/lib64/libpyzy-1.0.so.0',), + 'lua-libs': ('usr/lib64/liblua-5.4.so', 'usr/lib64/liblua-5.4.so.0')} +DATA = {'ibus-pinyin': ('usr/share/ibus-pinyin/base.lua', 'usr/share/ibus-pinyin/phrases.txt', + 'usr/share/ibus-pinyin/db/english.db'), + 'pyzy': ('usr/share/pyzy/phrases.txt',), + 'pyzy-db-android': ('usr/share/pyzy/db/android.db',)} +NOTICES = ('COPYING', 'LICENSE', 'COPYRIGHT', 'README', 'NOTICE') + + +def digest(path): + result = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + result.update(block) + return result.hexdigest() + + +def specifications(): + return json.loads(PACKAGES.read_text())['packages'] + + +def fetch(directory, spec): + directory.mkdir(parents=True, exist_ok=True) + path = directory / spec['filename'] + pending = path.with_name(path.name + '.pending') + with urllib.request.urlopen(spec['url'], timeout=60) as response, pending.open('wb') as stream: + shutil.copyfileobj(response, stream) + if digest(pending) != spec['sha256']: + pending.unlink() + raise ValueError('SHA256 mismatch for downloaded ' + spec['filename']) + pending.replace(path) + return path + + +def verified(directory, download=False): + sources = {} + for name, spec in specifications().items(): + path = directory / spec['filename'] + if download and not (path.is_file() and digest(path) == spec['sha256']): + path = fetch(directory, spec) + if not path.is_file(): + raise ValueError('missing RPM ' + spec['filename']) + if digest(path) != spec['sha256']: + raise ValueError('SHA256 mismatch for ' + spec['filename']) + sources[name] = path + return sources + + +def extract(name, rpm, destination): + for tool in ('rpm2cpio', 'cpio'): + if shutil.which(tool) is None: + raise ValueError(tool + ' is required to unpack the RPM payload') + destination.mkdir(parents=True) + with tempfile.TemporaryFile(dir=destination.parent) as payload: + subprocess.run(['rpm2cpio', str(rpm)], stdout=payload, check=True) + payload.seek(0) + listing = subprocess.run(['cpio', '-it', '--quiet'], stdin=payload, + stdout=subprocess.PIPE, check=True) + payload.seek(0) + for line in listing.stdout.splitlines(): + path = PurePosixPath(line.decode('utf-8', 'surrogateescape')) + if path.is_absolute() or '..' in path.parts: + raise ValueError(f'{name}: RPM payload contains unsafe path {path}') + subprocess.run(['cpio', '-idm', '--quiet'], stdin=payload, + cwd=destination, check=True) + + +def member(tree, name): + path = (tree / name).resolve() + if not path.is_relative_to(tree.resolve()) or not path.is_file(): + raise ValueError(f'{tree.name}: RPM payload is missing {name}') + return path + + +def install(source, target, output, files, executable=False): + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + target.chmod(0o755 if executable else 0o644) + files.add(target.relative_to(output).as_posix()) + + +def engine(tree): + for candidate in ENGINE_MEMBERS: + if (tree / candidate).is_file(): + return candidate + raise ValueError('ibus-pinyin RPM has no ' + ENGINE_NAME + ' executable') + + +def component(tree): + root = ElementTree.parse(member(tree, COMPONENT)).getroot() + for element in list(root.iter()): + for child in list(element): + if child.tag == 'setup': + element.remove(child) + executable = root.find('exec') + if executable is None: + raise ValueError('pinyin.xml has no engine exec element') + executable.text = f'/{LIBRARY_DIR}/{ENGINE_NAME} --ibus' + engines = {node.findtext('name', '').strip() for node in root.iter('engine')} + if not {'pinyin', 'bopomofo'} <= engines: + raise ValueError('pinyin.xml no longer defines the pinyin and bopomofo engines') + return root + + +def icons(root, tree, output, files): + names = set() + for node in root.iter('icon'): + text = (node.text or '').strip() + if text: + names.add(Path(text).stem if '/' in text else text) + found = sorted(path for path in (tree / 'usr/share').rglob('*') + if path.is_file() and path.suffix in ('.svg', '.png') and path.stem in names) + if names and not found: + raise ValueError('pinyin.xml icons are not in the ibus-pinyin RPM: ' + ', '.join(sorted(names))) + for path in found: + install(path, output / path.relative_to(tree), output, files) + + +def notices(name, tree, output, files): + copied = [] + for folder in ('usr/share/licenses/' + name, 'usr/share/doc/' + name): + base = tree / folder + if not base.is_dir(): + continue + for path in sorted(base.rglob('*')): + if path.is_file() and path.name.upper().startswith(NOTICES): + target = output / LICENSES / name / path.relative_to(base) + install(path, target, output, files) + copied.append(target.relative_to(output / LICENSES).as_posix()) + return copied + + +def prepare(directory, output, work=None, download=False): + specs = specifications() + sources = verified(directory, download) + output = output.resolve() + output.mkdir(parents=True, exist_ok=True) + created = work is None + work = Path(tempfile.mkdtemp(prefix='.droiddeck-ime-', dir=output.parent)) if created else Path(work) + work.mkdir(parents=True, exist_ok=True) + try: + trees = {} + for name, source in sources.items(): + trees[name] = work / name + shutil.rmtree(trees[name], ignore_errors=True) + extract(name, source, trees[name]) + files = set() + pinyin = trees['ibus-pinyin'] + install(member(pinyin, engine(pinyin)), output / LIBRARY_DIR / ENGINE_NAME, output, files, executable=True) + for name, candidates in LIBRARIES.items(): + installed = [candidate for candidate in candidates if (trees[name] / candidate).exists()] + if not installed: + raise ValueError(f'{name}: RPM has none of {list(candidates)}') + for candidate in installed: + install(member(trees[name], candidate), output / LIBRARY_DIR / Path(candidate).name, output, files) + for name, members in DATA.items(): + for relative in members: + install(member(trees[name], relative), output / relative, output, files) + root = component(pinyin) + icons(root, pinyin, output, files) + target = output / COMPONENT + target.parent.mkdir(parents=True, exist_ok=True) + ElementTree.ElementTree(root).write(target, encoding='utf-8', xml_declaration=True) + files.add(COMPONENT) + profile = output / PROFILE + profile.parent.mkdir(parents=True, exist_ok=True) + profile.write_text(PROFILE_TEXT, newline='\n') + files.add(PROFILE) + packages = {} + for name, spec in specs.items(): + license_files = notices(name, trees[name], output, files) + packages[name] = {'filename': spec['filename'], 'url': spec['url'], 'sha256': spec['sha256'], + 'license_files': license_files} + if not license_files: + packages[name]['license_note'] = ('RPM bundles no separate license file; ' + 'the payload is unmodified Fedora package content') + manifest = {'version': 1, 'engine': 'pinyin', 'packages': packages, + 'files': {path: {'sha256': digest(output / path), + 'mode': f'{(output / path).stat().st_mode & 0o777:04o}'} + for path in sorted(files)}} + destination = output / MANIFEST + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(manifest, sort_keys=True, indent=2) + '\n', newline='\n') + return destination, len(files) + finally: + if created: + shutil.rmtree(work, ignore_errors=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--packages', type=Path, required=True, help='Directory with the exact pinned RPMs') + parser.add_argument('--output', type=Path, required=True, + help='Prepared linuxfs root, for example app/build/prepared-assets/linuxfs') + parser.add_argument('--work', type=Path, help='Kept extraction cache instead of a temporary directory') + parser.add_argument('--download', action='store_true', + help='Fetch missing or mismatched RPMs into --packages and verify their SHA256') + args = parser.parse_args() + try: + destination, count = prepare(args.packages, args.output, args.work, args.download) + except (OSError, ValueError, subprocess.CalledProcessError, ElementTree.ParseError) as error: + parser.exit(1, f'error: {error}\n') + print(f'Wrote {count} IME payload files; manifest {destination}') + + +if __name__ == '__main__': + main() diff --git a/tools/ime/smoke.py b/tools/ime/smoke.py new file mode 100644 index 0000000000..4a9f17bfc5 --- /dev/null +++ b/tools/ime/smoke.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Check pinyin configuration and text commits over IBus.""" + +import os +import time + +try: + import gi + + gi.require_version('IBus', '1.0') + from gi.repository import GLib, IBus +except (ImportError, ValueError) as error: + raise SystemExit(f'error: PyGObject with the IBus 1.0 typelib is required: {error}') + +CLIENT = 'droiddeck-ime-test' +ENGINE = 'pinyin' +SECTION = 'engine/Pinyin' +BOOLEAN_KEYS = ('DoublePinyin', 'InitPinyin', 'GBK') +KEYCODES = {'a': 38, 'h': 43, 'i': 31, 'n': 57, 'o': 32, 'space': 65, '1': 10} + + +def pump(seconds, condition): + deadline = time.monotonic() + seconds + while True: + GLib.MainContext.default().iteration(False) + if condition(): + return True + if time.monotonic() >= deadline: + return False + time.sleep(0.02) + + +def press(context, name): + keyval = IBus.keyval_from_name(name) + keycode = KEYCODES[name] + context.process_key_event(keyval, keycode, 0) + context.process_key_event(keyval, keycode, IBus.ModifierType.RELEASE_MASK) + + +def boolean(config, key): + value = config.get_value(SECTION, key) + if value is None or value.get_type_string() != 'b': + return None + return value.get_boolean() + + +def unchanged(value, original): + if original is None: + return value is None + return value is not None and value.print_(True) == original.print_(True) + + +def configured(bus): + config = bus.get_config() + if config is None: + raise SystemExit('error: the bus exposes no configuration service') + saved = {key: config.get_value(SECTION, key) for key in BOOLEAN_KEYS} + probed = 0 + try: + for key in BOOLEAN_KEYS: + original = saved[key] + current = original is not None and original.get_type_string() == 'b' \ + and original.get_boolean() + wanted = not current + # The PyGObject override returns None on success, so verify writes by readback. + config.set_value(SECTION, key, GLib.Variant.new_boolean(wanted)) + if not pump(3.0, lambda key=key, wanted=wanted: boolean(config, key) == wanted): + raise SystemExit(f'error: {SECTION}/{key} did not read back as written') + probed += 1 + finally: + restore_failed = [] + for key in BOOLEAN_KEYS: + original = saved[key] + try: + if original is None: + config.unset(SECTION, key) + else: + config.set_value(SECTION, key, original) + if not pump(3.0, lambda key=key, original=original: + unchanged(config.get_value(SECTION, key), original)): + restore_failed.append(key) + except GLib.Error: + restore_failed.append(key) + if restore_failed: + raise SystemExit('error: could not restore ' + SECTION + ' settings: ' + + ', '.join(restore_failed)) + return probed + + +def main(): + if not os.environ.get('IBUS_ADDRESS'): + raise SystemExit('error: IBUS_ADDRESS is not set; the smoke test needs the private ibus-daemon') + bus = IBus.Bus() + if not bus.is_connected(): + raise SystemExit('error: cannot connect to the IBus bus from IBUS_ADDRESS') + engines = {engine.get_name() for engine in bus.list_engines() or []} + if ENGINE not in engines: + raise SystemExit('error: pinyin is not registered: ' + ', '.join(sorted(engines))) + print('IBus bus connected; pinyin engine registered') + + keys = configured(bus) + print(f'engine/Pinyin config write/readback ok ({keys} boolean settings)') + + if not bus.set_global_engine(ENGINE): + raise SystemExit('error: the bus rejected the pinyin global engine') + context = bus.create_input_context(CLIENT) + state = {'candidates': 0, 'commit': ''} + + def lookup(_, table, visible): + if table is not None: + state['candidates'] = table.get_number_of_candidates() + + def commit(_, text): + state['commit'] = text.get_text() or state['commit'] + + context.connect('update-lookup-table', lookup) + context.connect('commit-text', commit) + context.set_capabilities(IBus.Capabilite.PREEDIT_TEXT | IBus.Capabilite.LOOKUP_TABLE + | IBus.Capabilite.FOCUS) + context.focus_in() + pump(1.0, lambda: False) + context.set_engine(ENGINE) + pump(1.0, lambda: False) + + for _ in range(3): + for name in 'nihao': + press(context, name) + if pump(3.0, lambda: state['candidates'] > 0): + break + else: + raise SystemExit('error: no pinyin candidates after typing the test syllable') + print('lookup table ok') + + def chinese(): + return any('\u4e00' <= character <= '\u9fff' for character in state['commit']) + + for name in ('space', '1'): + press(context, name) + if pump(3.0, chinese): + break + if not chinese(): + raise SystemExit('error: pinyin committed no Chinese text for the test syllable') + print('commit-text ok') + context.focus_out() + print('droiddeck IBus pinyin smoke test passed') + + +if __name__ == '__main__': + try: + main() + except GLib.Error as error: + raise SystemExit(f'error: IBus call failed: {error.message}') diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index 7be3ccab5d..d2463c5128 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -9,7 +9,7 @@ export MOZ_ENABLE_WAYLAND=1 MOZ_USE_XINPUT2=1 export SHELL=/bin/bash export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1 export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1 -export MOZ_SHM_NO_SEALS=1 +export MOZ_SHM_NO_SEALS=1 MOZ_CRASHREPORTER_DISABLE=1 export QTWEBENGINE_DISABLE_SANDBOX=1 export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe export KWIN_USE_OVERLAYS=0 @@ -142,11 +142,10 @@ Exec=konsole -e /usr/local/bin/droiddeck-steam-x64 Icon=steam Categories=System; ENTRY -python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /' -( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) & +python3 /usr/local/bin/droiddeck-pad-defaults --every 30 & python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /' /usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /' -( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) & +python3 /usr/local/bin/droiddeck-library-perms 2>&1 & mkdir -p /usr/local/share/applications cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY' [Desktop Entry] @@ -175,6 +174,15 @@ fi if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 & fi +# Android counts the desktop's programs against an app's limit of 32. Off unless the user turns them +# back on in Autostart: Discover's update notifier (the packages follow DroidDeck's releases, and it +# keeps PackageKit running as root), GeoClue's demo agent (nothing asks for a location) and the +# global-menu proxy (the panel has no global menu). +mkdir -p "$HOME/.config/autostart" +for entry in org.kde.discover.notifier geoclue-demo-agent gmenudbusmenuproxy; do + [ -e "$HOME/.config/autostart/$entry.desktop" ] || + printf '[Desktop Entry]\nType=Application\nName=%s\nHidden=true\n' "$entry" > "$HOME/.config/autostart/$entry.desktop" +done skel_done=$HOME/.local/share/droiddeck/skel-copied if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then cp -rn /etc/skel/. "$HOME/" 2>/dev/null @@ -229,12 +237,21 @@ fi if ! /usr/local/bin/droiddeck-pipewire start; then echo "== pipewire: not running; screen capture has no picture" fi +return_gaming=/run/droiddeck/return-gaming +mkdir -p /run/droiddeck +rm -f "$return_gaming" echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY" -dbus-run-session -- startplasma-wayland +as_user= +if [ "${DD_DESKTOP_USER:-}" = 1 ] && [ -n "${DDNATV_ROOT:-}" ]; then + as_user=/usr/local/bin/droiddeck-user + echo "== droiddeck-desktop: Plasma runs as an ordinary user" +fi +$as_user dbus-run-session -- startplasma-wayland rc=$? /usr/local/bin/droiddeck-pipewire stop echo "== droiddeck-desktop: Plasma ended ($rc)" -if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ]; then +if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ] && [ -e "$return_gaming" ]; then + rm -f "$return_gaming" /usr/local/bin/droiddeck-steam-launch bigpicture sleep 30 fi diff --git a/tools/linuxfs/desktop/droiddeck-return-gaming.desktop b/tools/linuxfs/desktop/droiddeck-return-gaming.desktop new file mode 100644 index 0000000000..a4dd347002 --- /dev/null +++ b/tools/linuxfs/desktop/droiddeck-return-gaming.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Name=Return to Gaming Mode +Comment=Log out of the desktop and go back to Steam +Exec=sh -c ": > /run/droiddeck/return-gaming; dbus-send --session --print-reply --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout >/dev/null || rm -f /run/droiddeck/return-gaming" +Icon=steamdeck-gaming-return +Terminal=false +Type=Application +StartupNotify=false +NoDisplay=true diff --git a/tools/linuxfs/desktop/firefox-droiddeck.js b/tools/linuxfs/desktop/firefox-droiddeck.js index 053d7d03a3..f729aba2e0 100644 --- a/tools/linuxfs/desktop/firefox-droiddeck.js +++ b/tools/linuxfs/desktop/firefox-droiddeck.js @@ -9,3 +9,11 @@ pref("datareporting.policy.dataSubmissionEnabled", false); pref("browser.aboutwelcome.enabled", false); pref("browser.startup.homepage", "about:blank"); pref("layout.css.devPixelsPerPx", "1.25"); +// Android counts each of Firefox's processes against the app's limit of 32: one web content process +// per two tabs' worth of sites rather than one per site, none started ahead, and extensions and +// about: pages in the processes that already exist. +pref("fission.autostart", false); +pref("dom.ipc.processCount", 2); +pref("dom.ipc.processPrelaunch.enabled", false); +pref("browser.tabs.remote.separatePrivilegedContentProcess", false); +pref("extensions.webextensions.remote", false); diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 449c90ac93..756466bff4 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -284,8 +284,10 @@ def sandboxed_apps(proc=Path("/proc")): def window_steam_app(win, flatpaks, proc=Path("/proc")): match = STEAM_APP_CLASS.match(win.get("class") or "") - if match: - return match.group(1) if os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64" else None + if match and os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64": + return match.group(1) + # Gamescope finds the app of a window whose process runs under Steam's reaper. A game the + # session runs in a worker process (GuestWorkers) is not under it, whatever its class. pid = win.get("pid") if pid: if under_reaper(pid, proc): diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 0f426d9029..150013822d 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -350,6 +350,17 @@ def keeps_open(root): return isinstance(client, dict) and LAUNCH_BEHAVIOR[0] in client and client[LAUNCH_BEHAVIOR[0]] != LAUNCH_BEHAVIOR[1] +def chosen_folder(root, current, library): + current = current.strip() + folder = windows_path(root, current) if current else None + if not folder or rootfs_drive(root, current) or not os.path.isdir(folder): + return False + try: + return volume_root(os.path.realpath(folder)) == volume_root(os.path.realpath(library)) + except OSError: + return False + + def write_config(root, library=None): path = os.path.join(drive_c(root), *CONFIG) key, value = LAUNCH_BEHAVIOR @@ -374,6 +385,7 @@ def write_config(root, library=None): client["HardwareAcceleration"] = "false" changes.append("acceleration") if library and isinstance(client.setdefault("Install", {}), dict) \ + and not chosen_folder(root, str(client["Install"].get("DefaultInstallPath", "")), library) \ and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(root, library).rstrip("\\"): client["Install"]["DefaultInstallPath"] = install_path(root, library) changes.append("library") diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard index 014f305350..9db81b7e1c 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard @@ -1,7 +1,15 @@ #!/bin/bash -[ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0 -/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" & -child=$! -trap 'kill "$child" 2>/dev/null' EXIT +[ -n "${DISPLAY:-}" ] || exit 0 +children=() +if [ -n "${DD_ANDROID_CLIPBOARD:-}" ]; then + /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" & + children+=("$!") +fi +if [ -n "${DD_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-text-input ]; then + /usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" & + children+=("$!") +fi +[ "${#children[@]}" -gt 0 ] || exit 0 +trap 'kill "${children[@]}" 2>/dev/null' EXIT trap 'exit 0' TERM INT -wait "$child" +wait "${children[@]}" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 8463c69018..c392a0061a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -13,9 +13,10 @@ import subprocess import sys import tempfile from pathlib import Path +import xml.etree.ElementTree as ElementTree GAME_PREFIX = "DROIDDECK_GAME_" -GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR") +GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR", "DROIDDECK_GAME_FRAME_ACQUIRE") CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"} SYNC_KEYS = ("DD_SYNC", "DD_SYNC_FALLBACK", "DD_FSYNC_FIRST", "DD_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC") SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists" @@ -67,6 +68,29 @@ DOTNET_FEX = { "FEX_X87REDUCEDPRECISION": "0", } STABILITY_FEX = dict(DOTNET_FEX, FEX_MULTIBLOCK="0") +# Microsoft's original Xbox releases for PC run its emulator (Emu.exe). The switches turn on fixes in the builds of +# DroidDeck-Bionic's Wine, FEX and VKD3D-Proton made for it, each off by default: Wine delivers the Windows 11 special +# APCs the emulator interrupts its CPU threads with; FEX keeps the x87 state across those interrupts, checks for one in +# a loop that branches back into its own block, and maps an image without a lock order that deadlocks; Wine gives the +# boot video's types a display aperture and reports a 0 timer resolution (DXVK's vblank wait otherwise spins a core); +# VKD3D-Proton presents frames DXVK drew through D3D11On12 and maps the packed 4:2:2 video formats. FEX keeps +# DOTNET_FEX (the emulator's menu is .NET) without vector and memcpy TSO and with reduced x87 precision: on an +# Adreno 750 the emulator's menus ran at ~58 fps instead of ~35. +XBOX_BACK_COMPAT_IDENTITY = "xbox360backwardcompatibil" +XBOX_BACK_COMPAT_ENV = dict( + DOTNET_FEX, + FEX_VECTORTSOENABLED="0", + FEX_MEMCPYSETTSOENABLED="0", + FEX_X87REDUCEDPRECISION="1", + WINE_SPECIAL_APC_INTERRUPT="1", + FEX_SYNCX87CONTEXT="1", + FEX_LOOPSUSPENDCHECK="1", + FEX_SAFEIMAGEMAP="1", + WINE_MF_DISPLAY_APERTURE="1", + WINE_PRECISE_SLEEP="1", + VKD3D_INTEROP_PRESENT="1", + VKD3D_PACKED_422="1", +) # Setup loader offset-table IDs, as innoextract's known_setup_loader_versions lists them. Loaders # from 5.1.5 keep the table in a resource; older ones also put "Inno" at file offset 0x30. INNO_LOADER_IDS = (b"rDlPtS", b"nS5W7dT\x83\xaa\x1b\x0fj") @@ -149,6 +173,31 @@ def game_files(exe): return names +def xbox_identity(exe): + """The identity name in the MicrosoftGame.config of the Xbox package the executable is in, or "".""" + folder = os.path.dirname(exe) + for _ in range(4): + # The Xbox store accepts the file name in any case (XboxManifest.read). + name = "MicrosoftGame.config" + if not os.path.isfile(os.path.join(folder, name)): + try: + name = next((entry for entry in sorted(os.listdir(folder)) if entry.lower() == "microsoftgame.config"), name) + except OSError: + pass + try: + with open(os.path.join(folder, name), "rb") as source: + root = ElementTree.fromstring(source.read(1 << 20)) + except (OSError, ElementTree.ParseError): + root = None + if root is not None: + return next((node.get("Name", "") for node in root.iter() if node.tag.rsplit("}", 1)[-1] == "Identity"), "") + parent = os.path.dirname(folder) + if parent == folder: + break + folder = parent + return "" + + class Game: def __init__(self, exe, args, app_id=""): @@ -158,6 +207,7 @@ class Game: self.app_id = app_id self.stem = os.path.splitext(os.path.basename(exe))[0].lower() self.files = game_files(exe) + self.xbox_back_compat = os.path.isabs(exe) and xbox_identity(exe).lower().startswith(XBOX_BACK_COMPAT_IDENTITY) def has_arg(self, name): return any(a == name or a.startswith(name + "=") for a in self.args) @@ -177,10 +227,16 @@ def is_godot(game): @fix def dotnet_memory_ordering(game): - if "coreclr.dll" in game.files: + if "coreclr.dll" in game.files and not game.xbox_back_compat: return DOTNET_FEX, [], ".NET runtime: FEX with full TSO" +@fix +def xbox_back_compat(game): + if game.xbox_back_compat: + return XBOX_BACK_COMPAT_ENV, [], "Original Xbox game: emulator fixes on, FEX with load/store TSO and reduced x87 precision" + + @fix def unity_memory_ordering(game): if {"unityplayer.so", "gameassembly.so", "unityplayer.dll"} & game.files: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-log-writer b/tools/linuxfs/overlay/usr/local/bin/droiddeck-log-writer new file mode 100755 index 0000000000..fd49f5daed --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-log-writer @@ -0,0 +1,8 @@ +#!/bin/bash +# Appends stdin to a session log up to a byte cap, then reads and drops the rest, so that the session +# writing into it never gets SIGPIPE. A program of its own, rather than a subshell of the session, so +# that the native hook can start it outside the app's counted child processes. +# usage: droiddeck-log-writer FILE CAP_BYTES +dd=$(command -v gnudd || echo dd) +"$dd" of="$1" oflag=append conv=notrunc iflag=count_bytes count="$2" bs=65536 status=none +exec cat >/dev/null diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults b/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults index 5ecdc61a36..ceec469d71 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults @@ -1,6 +1,8 @@ #!/usr/bin/python3 import glob import os +import sys +import time HOME = os.environ.get("HOME", "/root") CONFIG = os.environ.get("XDG_CONFIG_HOME", os.path.join(HOME, ".config")) @@ -1048,8 +1050,19 @@ def switch_emulators(): print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})") -for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators): - try: - step() - except Exception as e: - print(f"droiddeck-pad-defaults: {step.__name__}: {e}") +def run_all(): + for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators): + try: + step() + except Exception as e: + print(f"droiddeck-pad-defaults: {step.__name__}: {e}", flush=True) + + +# --every SECONDS: again at that interval, for emulators set up while the desktop runs. One process +# for the whole desktop session rather than a shell loop starting a new one each time. +sys.stdout.reconfigure(line_buffering=True) +run_all() +if len(sys.argv) == 3 and sys.argv[1] == "--every": + while True: + time.sleep(float(sys.argv[2])) + run_all() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 79b0c149fe..cced83f6f6 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -13,7 +13,73 @@ fi export HOME=${HOME:-/root} mode=${1:-desktop} shift || true + +# Steam and its helpers share one session bus per session; an existing desktop bus is inherited. +if [ "$mode" = steam ] && [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then + exec dbus-run-session -- "$0" "$mode" "$@" +fi + step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; } +# Starts a long-lived program in its own Android process, which Android does not count against +# the session's child processes (docs/phantom-processes.md); a normal background job otherwise. +# Its pid is in $dd_spawned either way, and the ones not started as jobs in $dd_daemons, which +# the session stops as it ends. +dd_daemons= +dd_spawn() { + dd_spawned= + if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ] && [ -x /usr/local/bin/droiddeck-spawn ]; then + local f=${XDG_RUNTIME_DIR:-/tmp}/.dd-spawn.$$ rc=0 + /usr/local/bin/droiddeck-spawn --pid-file "$f" -- "$@" || rc=$? + dd_spawned=$(cat "$f" 2>/dev/null) + rm -f "$f" + if [ "$rc" = 0 ] && [ -n "$dd_spawned" ]; then + dd_daemons="$dd_daemons $dd_spawned" + return 0 + fi + # started, but its pid is unknown: not a second time + [ "$rc" = 3 ] && { dd_spawned=; return 0; } + fi + "$@" & + dd_spawned=$! +} +dd_stop_daemons() { + [ -n "$dd_daemons" ] && kill $dd_daemons 2>/dev/null + dd_daemons= +} +dd_session_pid=$$ +# Runs function $1 (with its arguments) in the background in a new bash that first loads this shell's +# variables, functions and options: a background subshell, but an exec'd program, which the native +# hook can hand to its own process (DD_HANDOFF "bash+dd-job"). $! is its pid, as for ( ... ) &. +dd_job() { + local state + if [ -n "${DD_HANDOFF:-}" ] && state=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/.dd-job.XXXXXX" 2>/dev/null); then + { + declare -p | grep -Ev '^declare -[a-zA-Z]*r|^declare -[-a-zA-Z]* (BASH[A-Z_]*|FUNCNAME|GROUPS|DIRSTACK|PIPESTATUS|COPROC|LINENO|_)=' + declare -f + shopt -p + set +o + } > "$state" 2>/dev/null + /bin/bash -c 'source "$1" 2>/dev/null; rm -f "$1"; shift; "$@"' dd-job "$state" "$@" & + else + "$@" & + fi +} +# Long-lived programs the session's guests start run in their own processes too +# (tools/nativeguest/hook/handoff.c). Not Steam, its web helper's browser process (gamescope finds a +# window's app by walking its process's parents) or its utility processes (the client only accepts +# its transport from its own children). +if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then + export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker} + # The programs these start for the user (an app from the panel, a file opened in Dolphin) + export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin} + # Each process's first parent, so that a process can reap the zombies it adopts as a subreaper, and + # the programs that reap them even while they leave SIGCHLD alone (hook/signals.c) + rm -f /run/droiddeck-parents.* 2>/dev/null + export DD_PARENTS=/run/droiddeck-parents.$$ + export DD_REAP_ADOPTED=${DD_REAP_ADOPTED-plasmashell:plasma_session:kwin_wayland:kwin_wayland_wrapper:kaccess:ksmserver:kded6:krunner:dolphin:dbus-daemon:startplasma-wayland:gamescope:wine:wine64:wine-preloader:wine64-preloader:wineserver:PluginLoader:PluginLoader.real} +else + unset DD_HANDOFF DD_HANDOFF_LAUNCHERS DD_PARENTS DD_REAP_ADOPTED +fi steam_setup_failed() { echo "== steam: the Steam client could not be set up (status $1)" [ -z "${DD_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$DD_STEAM_EXIT_FILE" @@ -24,8 +90,12 @@ if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then if [ "$(stat -c %s "$DD_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then mv -f "$DD_LOG" "$DD_LOG.1" fi - dd=$(command -v gnudd || echo dd) - exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1 + if [ -x /usr/local/bin/droiddeck-log-writer ]; then + exec > >(exec /usr/local/bin/droiddeck-log-writer "$DD_LOG" "${DD_LOG_CAP:-268435456}") 2>&1 + else + dd=$(command -v gnudd || echo dd) + exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1 + fi echo "== droiddeck-session $(date) mode=$mode $*" echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}" echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)" @@ -569,6 +639,10 @@ if [ -z "${DD_INSIDE:-}" ]; then fi [ "$mode" = steam ] && args+=(--default-touch-mode 4) [ "${DD_HDR:-0}" = 1 ] && args+=(--hdr-enabled) + # An SDR game reaches Android as its own SDR buffer, but whenever gamescope composites (a Steam + # toast, the volume slider) an HDR output encodes the frame in PQ, which the display tone-maps + # darker and shifted in colour. The output turns HDR only while a window presents HDR. + export gamescope_hdr_content_driven=1 [ -n "${DD_GAMESCOPE_ARGS:-}" ] && read -r -a _dd_extra <<<"$DD_GAMESCOPE_ARGS" && args+=("${_dd_extra[@]}") if [ "$mode" = steam ] && [ "${DD_MANGOAPP:-1}" = 1 ] \ && [ "${DD_STEAM_UI:-}" != desktop ] && command -v mangoapp >/dev/null 2>&1; then @@ -618,6 +692,11 @@ dd_stretch_game_screen() { export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11 reap_orphans() { local round p stat pid left + # Started by the app as an Android process of its own: its parent is zygote, whose other + # children are the app's processes. The guest may not see zygote in /proc; a worker's own + # program has DDH_WORKER_PID. + [ "${DDH_WORKER_PID:-}" = "$$" ] && return 0 + case "$(tr -d '\0' < "/proc/$PPID/cmdline" 2>/dev/null)" in ''|zygote*) return 0 ;; esac for round in 1 2 3 4 5; do left= for p in /proc/[0-9]*; do @@ -636,7 +715,14 @@ reap_orphans() { } if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then - /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" & + dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" +fi + +ime_text_pid= +if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DISPLAY:-}" ] && [ -n "${DD_LAUNCH_DIR:-}" ] \ + && [ -x /usr/local/bin/droiddeck-text-input ]; then + /usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" & + ime_text_pid=$! fi [ "${DD_DESKTOP:-}" = 1 ] || start_agent @@ -779,7 +865,7 @@ case $mode in fi if [ "${DD_ZRAM:-0}" = 1 ]; then step "zRAM compression: on" - ( + _dd_job_zram() { dd_zram_scan() { _dd_game=0 _dd_pids=() _dd_others=() _dd_apps= local _d _c _args _name _a _id _fex _lower _bnet=() _bnet_game=0 @@ -1124,7 +1210,7 @@ case $mode in _dd_sample_at= _dd_freed=0 _dd_client_out=0 _dd_note_client=0 _dd_note_session=0 _dd_trim_at=-30 _dd_back_at=-30 _dd_forced_at=-10 _dd_full_at=-60 _dd_noted_at=-5 _dd_rest=0 _dd_rest_until=0 _dd_rest_available=0 - while kill -0 $$ 2>/dev/null; do + while kill -0 "$dd_session_pid" 2>/dev/null; do dd_memory_tick if [ "$_dd_available" -ge 0 ] && { [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] || [ "$_dd_rate" -ge $((16 * 1024)) ]; }; then @@ -1133,7 +1219,8 @@ case $mode in nap 5 fi done - ) & + } + dd_job _dd_job_zram fi if [ "${DD_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${DD_LAUNCH_DIR:-}" ] && [ -z "${DD_DESKTOP:-}" ] \ && [ "${DD_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then @@ -1149,6 +1236,7 @@ case $mode in droiddeck-steam-library "$steam_root" || true step "setting up the ARM64 Proton compatibility tool" steam-compatibility "$steam_root" || true + steam-compatibility "$steam_root" --seed-arm64-tools || true if [ -z "${DD_DESKTOP:-}" ] && [ "${DD_STEAM_UI:-}" != desktop ]; then droiddeck-steam-ui-scale "$steam_root" "${DD_WIDTH:-1280}" "${DD_HEIGHT:-720}" || true fi @@ -1225,7 +1313,7 @@ case $mode in ) & fi fi - [ -z "${DD_DESKTOP:-}" ] && ( + _dd_job_properties() { stretch=0 restore=0 [ "${DD_STRETCHED:-0}" = 1 ] && stretch=1 [ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1 @@ -1304,8 +1392,9 @@ case $mode in && echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME" ;; esac - done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null) - ) & + done < <(exec xprop -spy -root "${atoms[@]}" 2>/dev/null) + } + [ -n "${DD_DESKTOP:-}" ] || dd_job _dd_job_properties steam_hold_launch() { local game=$1 shortcut= waited=0 status=0 _dd_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; } @@ -1392,8 +1481,8 @@ case $mode in fi if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then write_system_bus_config - dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile & - system_bus=$! + dd_spawn dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile + system_bus=$dd_spawned for _ in $(seq 1 50); do [ -S /run/dbus/system_bus_socket ] && break sleep 0.1 @@ -1401,8 +1490,8 @@ case $mode in if [ -S /run/dbus/system_bus_socket ]; then echo "== network: system bus up, NetworkManager stand-in running" rm -f "$DD_LAUNCH_DIR/steam-sleep-ready" - droiddeck-login1 --with-netmanager & - login_manager=$! + dd_spawn droiddeck-login1 --with-netmanager + login_manager=$dd_spawned for ((_i = 0; _i < 50; _i++)); do [ -f "$DD_LAUNCH_DIR/steam-sleep-ready" ] && break kill -0 "$login_manager" 2>/dev/null || break @@ -1426,7 +1515,7 @@ case $mode in if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then _dd_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus rm -f "$_dd_bus" - dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile & + dd_spawn dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile for _ in $(seq 1 50); do [ -S "$_dd_bus" ] && break nap 0.1 @@ -1464,7 +1553,7 @@ case $mode in if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown) if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && /usr/local/bin/droiddeck-fex prepare >/dev/null; }; then - ( + _dd_job_decky() { decky_child= decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; } trap decky_stop TERM INT HUP @@ -1488,7 +1577,8 @@ case $mode in echo "== Decky: loader exited with status $decky_status; restart $((decky_exits + 1))/5 in ${decky_delay}s" sleep "$decky_delay" done - ) & + } + dd_job _dd_job_decky decky_supervisor=$! echo "== Decky: session supervisor started ($decky_arch)" else @@ -1689,7 +1779,7 @@ case $mode in rm -f "$DD_LAUNCH_DIR/steam-stop" "$DD_LAUNCH_DIR/steam-game" "$DD_LAUNCH_DIR/steam-game.tmp" requests=1 fi - ( + _dd_job_requests() { tick=0 beat=0 library_job= @@ -1867,7 +1957,8 @@ case $mode in fi fi done - ) & + } + dd_job _dd_job_requests stop_watcher=$! if [ "${DD_VENUS:-0}" = 1 ] && [ -x /usr/local/bin/droiddeck-glprobe ] && [ "${GALLIUM_DRIVER:-}" = zink ]; then LIBGL_DEBUG=verbose MESA_LOG_LEVEL=debug timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -60 | sed 's/^/== glprobe: /' @@ -1900,6 +1991,46 @@ case $mode in fi fi rm -f "$HOME/.dd-restart-game" "$HOME/.dd-restarted-for" + unset IBUS_ADDRESS + ime_ibus_pid= + ime_ibus_socket= + stop_steam_ime() { + if [ -n "$ime_ibus_pid" ]; then + kill "$ime_ibus_pid" 2>/dev/null || true + wait "$ime_ibus_pid" 2>/dev/null || true + ime_ibus_pid= + fi + [ -S "$ime_ibus_socket" ] && rm -f "$ime_ibus_socket" + ime_ibus_socket= + unset IBUS_ADDRESS + } + if [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ] \ + && [ -x /usr/bin/ibus-daemon ] && [ -x /usr/bin/ibus ]; then + ime_ibus_socket="${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-ibus-$$.sock" + export IBUS_ADDRESS="unix:path=$ime_ibus_socket" + /usr/local/bin/droiddeck-steam-ime & + ime_ibus_pid=$! + ime_ready=0 + _ime_deadline=$((SECONDS + 5)) + while [ "$SECONDS" -lt "$_ime_deadline" ]; do + if env -u LD_LIBRARY_PATH -u LD_PRELOAD -u GSETTINGS_SCHEMA_DIR -u DCONF_PROFILE \ + timeout 1 /usr/bin/ibus list-engine --name-only 2>/dev/null | grep -qx 'pinyin'; then + ime_ready=1 + break + fi + kill -0 "$ime_ibus_pid" 2>/dev/null || break + nap 0.1 + done + unset _ime_deadline + if [ "$ime_ready" = 1 ]; then + echo "== ime: pinyin engine ready at $IBUS_ADDRESS" + else + echo "== ime: the pinyin engine did not start at $IBUS_ADDRESS; Steam starts without Chinese input" + stop_steam_ime + fi + elif [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ]; then + echo "== ime: the installed Linux runtime does not include IBus; Steam starts without pinyin" + fi while :; do rm -f "$HOME/.dd-restart-once" "$HOME/.dd-restart-lost" if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then @@ -2015,12 +2146,19 @@ case $mode in kill "$games_watcher" 2>/dev/null || true wait "$games_watcher" 2>/dev/null || true fi + stop_steam_ime + if [ -n "${ime_text_pid:-}" ]; then + kill "$ime_text_pid" 2>/dev/null || true + wait "$ime_text_pid" 2>/dev/null || true + ime_text_pid= + fi if [ -n "${DD_DESKTOP:-}" ]; then if [ -n "${decky_supervisor:-}" ]; then kill "$decky_supervisor" 2>/dev/null || true wait "$decky_supervisor" 2>/dev/null || true echo "== Decky: session supervisor stopped" fi + dd_stop_daemons _dd_jobs=$(jobs -p) [ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null echo "== steam: the client on the desktop has exited" @@ -2030,6 +2168,7 @@ case $mode in wait "$decky_supervisor" 2>/dev/null || true echo "== Decky: session supervisor stopped" fi + dd_stop_daemons _dd_jobs=$(jobs -p) [ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null reap_orphans diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn new file mode 100755 index 0000000000..c0ebafccac --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-spawn @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Starts a program as the main process of its own Android process, outside the session's cgroup. + +usage: droiddeck-spawn [--wait] [--pid-file FILE] [--] PROGRAM [ARGS...] + +Android counts the session's processes against its child-process limit; a program started this +way is not counted (its own children are). It gets this process's environment, working directory +and stdin/stdout/stderr, and is not a child of the caller: the pid printed on stdout (or written to +FILE) is the one to signal. Without --wait this returns once the program has started; with --wait +it waits for it and exits with its status. Where the app offers no spawner, the program is started as a normal child. +""" +import array +import json +import os +import re +import socket +import struct +import sys + + +# Exit status when the program started but its pid could not be reported: the caller must not +# start it again. +STARTED_UNREPORTED = 3 + + +def report(pid, pid_file): + try: + if pid_file: + with open(pid_file, "w") as f: + f.write("%s\n" % pid) + else: + print(pid, flush=True) + return True + except OSError as e: + print("droiddeck-spawn: started pid %s but could not report it: %s" % (pid, e), file=sys.stderr) + return False + + +def fallback(argv, wait, pid_file): + pid = os.fork() + if pid == 0: + try: + os.execvp(argv[0], argv) + except OSError as e: + print("droiddeck-spawn: %s: %s" % (argv[0], e.strerror), file=sys.stderr) + os._exit(127) + reported = report(pid, pid_file) + if wait: + return os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]) + return 0 if reported else STARTED_UNREPORTED + + +def main(): + args = sys.argv[1:] + wait = False + pid_file = None + while args and args[0].startswith("--"): + flag = args.pop(0) + if flag == "--": + break + if flag == "--wait": + wait = True + elif flag == "--pid-file" and args: + pid_file = args.pop(0) + else: + print(__doc__.strip(), file=sys.stderr) + return 2 + if not args: + print(__doc__.strip(), file=sys.stderr) + return 2 + name = os.environ.get("DD_SPAWN") + if not name: + return fallback(args, wait, pid_file) + s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + s.connect("\0" + name) + except OSError: + return fallback(args, wait, pid_file) + request = {"argv": args, "env": dict(os.environ), "cwd": os.getcwd(), "wait": wait} + # the session it belongs to, as SessionService writes it (a positive decimal); anything else is + # left out, and the app then runs nothing for it + session = os.environ.get("DD_SPAWN_SESSION", "") + if re.fullmatch(r"[1-9][0-9]{0,8}", session): + request["session"] = int(session) + payload = json.dumps(request).encode() + s.sendmsg([struct.pack(">I", len(payload)), payload], + [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", [0, 1, 2]))]) + reply = s.makefile("r") + first = reply.readline().split() + if len(first) != 2 or first[0] != "pid": + print("droiddeck-spawn: %s; starting %s as a child" % (" ".join(first[1:]) or "no answer", args[0]), + file=sys.stderr) + return fallback(args, wait, pid_file) + reported = report(first[1], pid_file) + if not wait: + return 0 if reported else STARTED_UNREPORTED + done = reply.readline().split() + status = int(done[1]) if len(done) == 2 and done[0] == "exit" else 1 + return status if 0 <= status < 256 else 128 + (status & 0x7f) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime new file mode 100755 index 0000000000..d7d683cbc5 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime @@ -0,0 +1,7 @@ +#!/bin/bash +[ -n "${IBUS_ADDRESS:-}" ] || exit 0 +unset LD_PRELOAD LD_LIBRARY_PATH GSETTINGS_SCHEMA_DIR +export LD_LIBRARY_PATH=/usr/local/lib/droiddeck-ime +export DCONF_PROFILE=/usr/local/share/droiddeck/ibus.profile +exec /usr/bin/ibus-daemon --address "$IBUS_ADDRESS" --panel disable --config default \ + --emoji-extension disable --cache none diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input b/tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input new file mode 100755 index 0000000000..0829dcb3d8 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input @@ -0,0 +1,510 @@ +#!/usr/bin/python3 +"""Deliver committed Android IME text to the focused X11 client.""" +import ctypes +import ctypes.util +import errno +import os +import select +import signal +import socket +import stat +import struct +import sys + +MAX_TEXT = 65536 +CANCELLABLE = 1 << 31 +CLIENT_TIMEOUT = 2.0 +PROBE_TIMEOUT = 0.5 +FOCUS_PROPERTY = b'GAMESCOPE_KEYBOARD_FOCUS_DISPLAY' +ANY_PROPERTY_TYPE = 0 +PROPERTY_WORDS = 1024 +PR_SET_PDEATHSIG = 1 +UNICODE_KEYSYM_FLAG = 0x01000000 +X11_SPECIAL_KEYSYMS = { + '\r': 0xff0d, # XK_Return + '\n': 0xff0d, # XK_Return + '\b': 0xff08, # XK_BackSpace + '\u007f': 0xffff, # XK_Delete + '\t': 0xff09, # XK_Tab +} + +_STOP = False + + +class XModifierKeymap(ctypes.Structure): + _fields_ = [('max_keypermod', ctypes.c_int), + ('modifiermap', ctypes.POINTER(ctypes.c_ubyte))] + + +class _DisplayState: + """Keep mappings stable until shutdown because clients may decode key events later.""" + + __slots__ = ('handle', 'codes', 'owned') + + def __init__(self, handle): + self.handle = handle + self.codes = {} # keysym -> keycode, stable for the session + self.owned = {} # keycode -> (width, original row) for shutdown restore + + +class XBridge: + def __init__(self): + self.lib = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6') + self.xtst = ctypes.CDLL(ctypes.util.find_library('Xtst') or 'libXtst.so.6') + self._open_displays = {} + self._declare() + + def _declare(self): + lib = self.lib + lib.XOpenDisplay.argtypes = [ctypes.c_char_p] + lib.XOpenDisplay.restype = ctypes.c_void_p + lib.XCloseDisplay.argtypes = [ctypes.c_void_p] + lib.XCloseDisplay.restype = ctypes.c_int + lib.XDefaultRootWindow.argtypes = [ctypes.c_void_p] + lib.XDefaultRootWindow.restype = ctypes.c_ulong + lib.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] + lib.XInternAtom.restype = ctypes.c_ulong + lib.XGetWindowProperty.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_long, ctypes.c_long, + ctypes.c_int, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_void_p)] + lib.XGetWindowProperty.restype = ctypes.c_int + lib.XFree.argtypes = [ctypes.c_void_p] + lib.XFree.restype = ctypes.c_int + lib.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), + ctypes.POINTER(ctypes.c_int)] + lib.XDisplayKeycodes.restype = ctypes.c_int + lib.XGetKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_int, + ctypes.POINTER(ctypes.c_int)] + lib.XGetKeyboardMapping.restype = ctypes.POINTER(ctypes.c_ulong) + lib.XChangeKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, + ctypes.POINTER(ctypes.c_ulong), ctypes.c_int] + lib.XChangeKeyboardMapping.restype = ctypes.c_int + lib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int] + lib.XSync.restype = ctypes.c_int + lib.XQueryKeymap.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + lib.XQueryKeymap.restype = ctypes.c_int + lib.XGetModifierMapping.argtypes = [ctypes.c_void_p] + lib.XGetModifierMapping.restype = ctypes.POINTER(XModifierKeymap) + lib.XFreeModifiermap.argtypes = [ctypes.POINTER(XModifierKeymap)] + lib.XFreeModifiermap.restype = ctypes.c_int + self.xtst.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, + ctypes.c_ulong] + self.xtst.XTestFakeKeyEvent.restype = ctypes.c_int + + def state(self, name): + existing = self._open_displays.get(name) + if existing is not None: + return existing + handle = self.lib.XOpenDisplay(name.encode()) + if not handle: + return None + state = _DisplayState(handle) + self._open_displays[name] = state + return state + + def display(self, name): + state = self.state(name) + return state.handle if state else None + + def close(self): + for state in self._open_displays.values(): + for keycode, (width, original) in state.owned.items(): + row = (ctypes.c_ulong * width)(*original) + self.lib.XChangeKeyboardMapping(state.handle, keycode, width, row, 1) + self.lib.XSync(state.handle, 0) + self.lib.XCloseDisplay(state.handle) + self._open_displays.clear() + + def target_display(self): + main = os.environ.get('DISPLAY', '').strip() + if not main: + return None + game = os.environ.get('STEAM_GAME_DISPLAY_0', '').strip() + if not game or game == main: + return main + main_display = self.display(main) + if not main_display: + return None + focused = self._focused_display(main_display) + if focused == game: + return game + if focused == main: + return main + return None + + def _focused_display(self, display): + root = self.lib.XDefaultRootWindow(display) + atom = self.lib.XInternAtom(display, FOCUS_PROPERTY, 0) + if not atom: + return None + actual_type = ctypes.c_ulong(0) + actual_format = ctypes.c_int(0) + items = ctypes.c_ulong(0) + remaining = ctypes.c_ulong(0) + data = ctypes.c_void_p() + status = self.lib.XGetWindowProperty( + display, root, atom, 0, PROPERTY_WORDS, 0, ANY_PROPERTY_TYPE, + ctypes.byref(actual_type), ctypes.byref(actual_format), ctypes.byref(items), + ctypes.byref(remaining), ctypes.byref(data)) + if status != 0 or not data or not items.value: + if data: + self.lib.XFree(data) + return None + try: + raw = _property_bytes(data, actual_format.value, items.value) + finally: + self.lib.XFree(data) + if raw is None: + return None + raw = raw.split(b'\0', 1)[0] + if not raw: + return None + try: + return raw.decode('ascii') + except UnicodeDecodeError: + return None + + def keymap(self, display): + lowest = ctypes.c_int(0) + highest = ctypes.c_int(0) + self.lib.XDisplayKeycodes(display, ctypes.byref(lowest), ctypes.byref(highest)) + if lowest.value < 0 or highest.value < lowest.value: + return None + count = highest.value - lowest.value + 1 + width = ctypes.c_int(0) + symbols = self.lib.XGetKeyboardMapping(display, lowest.value, count, ctypes.byref(width)) + if not symbols: + return None + if width.value <= 0: + self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p)) + return None + rows = [[symbols[index * width.value + level] for level in range(width.value)] + for index in range(count)] + self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p)) + return lowest.value, width.value, rows + + def held_keys(self, display): + state = ctypes.create_string_buffer(32) + if not self.lib.XQueryKeymap(display, ctypes.cast(state, ctypes.c_void_p)): + return set() + raw = state.raw + return {keycode for keycode in range(len(raw) * 8) + if raw[keycode >> 3] >> (keycode & 7) & 1} + + def modifier_keys(self, display): + mapping = self.lib.XGetModifierMapping(display) + if not mapping: + return set() + try: + width = mapping.contents.max_keypermod + keys = mapping.contents.modifiermap + return {keys[index] for index in range(8 * width) if keys[index]} + finally: + self.lib.XFreeModifiermap(mapping) + + def empty_rows(self, display, reserved): + keymap = self.keymap(display) + if keymap is None: + return [] + lowest, width, rows = keymap + held = self.held_keys(display) + modifiers = self.modifier_keys(display) + available = [] + for index in range(len(rows) - 1, -1, -1): + keycode = lowest + index + if keycode < 8 or keycode > 255 or keycode in held or keycode in modifiers: + continue + if keycode in reserved: + continue + row = rows[index] + if any(row): + continue + available.append((keycode, width, tuple(row))) + return available + + def type_text(self, state, text, cancelled=None): + """Reserve all required mappings before injecting any part of a frame.""" + handle = state.handle + needed = [] + seen = set() + for character in text: + keysym = _character_keysym(character) + if keysym not in seen: + seen.add(keysym) + needed.append(keysym) + missing = [keysym for keysym in needed if keysym not in state.codes] + if missing: + available = self.empty_rows(handle, set(state.codes.values())) + if len(available) < len(missing): + _log_capacity_exhausted() + return False + for keysym, (keycode, width, original) in zip(missing, available): + row = (ctypes.c_ulong * width)(*[keysym] * width) + # XChangeKeyboardMapping queues the request and returns 0. + self.lib.XChangeKeyboardMapping(handle, keycode, width, row, 1) + state.codes[keysym] = keycode + state.owned[keycode] = (width, original) + self.lib.XSync(handle, 0) + for character in text: + if _STOP: + return False + if cancelled is not None and cancelled(): + return False + keycode = state.codes[_character_keysym(character)] + if not self._tap(handle, keycode): + return False + return True + + def _tap(self, handle, keycode): + pressed = False + try: + if not self.xtst.XTestFakeKeyEvent(handle, keycode, 1, 0): + return False + pressed = True + self.lib.XSync(handle, 0) + if not self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0): + return False + pressed = False + self.lib.XSync(handle, 0) + finally: + if pressed: + self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0) + self.lib.XSync(handle, 0) + return True + + +def _character_keysym(character): + keysym = X11_SPECIAL_KEYSYMS.get(character) + if keysym is not None: + return keysym + codepoint = ord(character) + return codepoint if codepoint < 256 else UNICODE_KEYSYM_FLAG | codepoint + + +def _log_capacity_exhausted(): + try: + sys.stderr.write('droiddeck-text-input: not enough empty keycodes for this frame\n') + sys.stderr.flush() + except OSError: + pass + + +def _property_bytes(data, actual_format, items): + if actual_format == 8: + return ctypes.string_at(data, items) + if actual_format == 32: + # Xlib exposes format-32 property items as native longs, including on 64-bit systems. + words = ctypes.cast(data, ctypes.POINTER(ctypes.c_ulong)) + return b''.join(struct.pack(' 0: + try: + chunk = connection.recv(remaining) + except OSError: + return None + if not chunk: + return None + chunks.append(chunk) + remaining -= len(chunk) + return b''.join(chunks) + + +def read_request(connection): + header = _recv_exact(connection, 4) + if header is None: + return None + raw = struct.unpack('>I', header)[0] + cancellable = bool(raw & CANCELLABLE) + length = raw & ~CANCELLABLE + if length < 1 or length > MAX_TEXT: + return None + body = _recv_exact(connection, length) + if body is None: + return None + if b'\0' in body: + return None + try: + return body.decode('utf-8'), cancellable + except UnicodeDecodeError: + return None + + +def answer(connection, accepted): + try: + connection.sendall(b'\x01' if accepted else b'\x00') + connection.shutdown(socket.SHUT_WR) + except OSError: + return + # Drain unread bytes so close() does not reset the connection after the ACK. + try: + connection.settimeout(0.2) + while connection.recv(4096): + pass + except OSError: + pass + + +def _cancellation_probe(connection): + """Return a predicate that is true once the peer has cancelled a flagged frame. + + After the full frame has been read, any readable event (POLLIN/POLLHUP/POLLERR) + means extra data, half-close or reset - all of which are cancellation for a + cancellable client. + """ + poller = select.poll() + poller.register(connection, select.POLLIN) + return lambda: bool(poller.poll(0)) + + +def deliver(bridge, text, cancelled=None): + if cancelled is not None and cancelled(): + return False + target = bridge.target_display() + if target is None: + return False + state = bridge.state(target) + if state is None: + return False + return bridge.type_text(state, text, cancelled) + + +def serve_connection(connection, bridge): + connection.settimeout(CLIENT_TIMEOUT) + request = read_request(connection) + accepted = False + if request is not None: + text, cancellable = request + cancelled = _cancellation_probe(connection) if cancellable else None + try: + accepted = deliver(bridge, text, cancelled) + except Exception: + accepted = False + answer(connection, accepted) + + +def _identity(path): + try: + info = os.stat(path) + except OSError: + return None + return info.st_dev, info.st_ino + + +def _release(path, owned): + if owned is None: + return + try: + info = os.lstat(path) + except OSError: + return + if stat.S_ISSOCK(info.st_mode) and (info.st_dev, info.st_ino) == owned: + try: + os.unlink(path) + except OSError: + pass + + +def serve(path, bridge): + if not _remove_stale(path): + print("droiddeck-text-input: refusing to replace %s" % path, file=sys.stderr) + return 1 + server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + owned = None + try: + server.bind(path) + os.chmod(path, 0o600) + server.listen(8) + server.setblocking(False) + owned = _identity(path) + while not _STOP: + try: + ready, _, _ = select.select([server], [], [], 0.25) + except OSError: + break + if not ready: + continue + try: + connection, _ = server.accept() + except OSError: + if _STOP: + break + continue + try: + serve_connection(connection, bridge) + finally: + connection.close() + finally: + server.close() + _release(path, owned) + return 0 + + +def _remove_stale(path): + try: + info = os.lstat(path) + except FileNotFoundError: + return True + except OSError: + return False + if not stat.S_ISSOCK(info.st_mode): + return False + probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + probe.settimeout(PROBE_TIMEOUT) + probe.connect(path) + except OSError as error: + if error.errno == errno.ENOENT: + return True + if error.errno != errno.ECONNREFUSED: + return False + else: + return False + finally: + probe.close() + _release(path, (info.st_dev, info.st_ino)) + return True + + +def _stop(signum, frame): + global _STOP + _STOP = True + + +def _adopt_parent_death(): + parent = os.getppid() + try: + libc = ctypes.CDLL(None, use_errno=True) + libc.prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, + ctypes.c_ulong] + libc.prctl.restype = ctypes.c_int + libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) + except (OSError, AttributeError): + return True + return os.getppid() == parent and parent > 1 + + +def main(argv): + if len(argv) != 2 or not argv[1]: + return 2 + if not _adopt_parent_death(): + return 0 + os.umask(0o077) + for name in ('SIGTERM', 'SIGINT', 'SIGHUP'): + signal.signal(getattr(signal, name), _stop) + bridge = XBridge() + try: + return serve(argv[1], bridge) + finally: + bridge.close() + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-user b/tools/linuxfs/overlay/usr/local/bin/droiddeck-user new file mode 100755 index 0000000000..787c19caa5 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-user @@ -0,0 +1,15 @@ +#!/bin/sh +# Runs COMMAND, or a shell, as an ordinary user ("deck", the app's own Android user) instead of +# root, for programs that refuse root or check who owns their files. Everything started from it +# stays that user; sudo and su still give root, and exit goes back. +case ${1:-} in + -h|--help) echo "usage: droiddeck-user [COMMAND [ARG...]]"; exit 0 ;; +esac +if [ -z "${DDNATV_ROOT:-}" ]; then + echo "droiddeck-user: needs the native userland (Settings > Performance > Run without proot)" >&2 + exit 1 +fi +export DDNATV_BECOME=app USER=deck LOGNAME=deck +[ $# -gt 0 ] && exec "$@" +[ -t 2 ] && echo "Programs here run as an ordinary user (deck), not root. sudo still works; exit goes back." >&2 +exec "${SHELL:-/bin/bash}" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox index 143aa07c27..231dba2f0c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox @@ -28,6 +28,19 @@ CLASSES = { 'Windows.Storage.Streams.DataWriter'), } CLASS_KEY = 'Software\\Microsoft\\WindowsRuntime\\ActivatableClassId\\' +# Microsoft's original Xbox releases for PC install GameInputRedist.msi. The emulator needs the GameInput it installs +# (Wine's builtin one lacks the interface it asks for), but through the GameInputService class it registers that +# GameInput starts a service needing Windows notification calls Wine lacks, and the emulator then stops with "Gaming +# Services must be installed". Without the class it runs the redistributable's GameInput in process. +BACK_COMPAT_IDENTITY = 'xbox360backwardcompatibil' +# droiddeck-game-env gives these games the emulator's switches and faster FEX settings. Their install actions run +# without the switches and with FEX's full memory ordering and x87 precision: under the faster settings +# GameInputRedist.msi's 32-bit msiexec spun a core and never finished. +EMULATOR_SWITCHES = ('WINE_SPECIAL_APC_INTERRUPT', 'WINE_MF_DISPLAY_APERTURE', 'WINE_PRECISE_SLEEP', 'FEX_SYNCX87CONTEXT', + 'FEX_LOOPSUSPENDCHECK', 'FEX_SAFEIMAGEMAP', 'VKD3D_INTEROP_PRESENT', 'VKD3D_PACKED_422') +INSTALLER_FEX = {'FEX_TSOENABLED': '1', 'FEX_VECTORTSOENABLED': '1', 'FEX_MEMCPYSETTSOENABLED': '1', + 'FEX_HALFBARRIERTSOENABLED': '1', 'FEX_X87REDUCEDPRECISION': '0'} +GAMEINPUT_SERVICE = 'Software\\Classes\\CLSID\\{B773D0F8-01F8-41E7-9F23-6871DA0AACFF}' VIEW_DRIVES = 'xwvutsrqponmlkjihgfe' @@ -145,8 +158,21 @@ def game_config(exe): return None for folder in list(path.parents)[:4]: config = folder / 'MicrosoftGame.config' - if config.is_file(): - return config + if not config.is_file(): + # The Xbox store accepts the file name in any case (XboxManifest.read). + try: + config = next((entry for entry in sorted(folder.iterdir()) + if entry.name.lower() == 'microsoftgame.config' and entry.is_file()), None) + except OSError: + config = None + if config is None: + continue + # As in droiddeck-game-env, a manifest that does not parse gives way to one in a parent folder. + try: + ElementTree.fromstring(config.read_bytes()) + except (OSError, ElementTree.ParseError): + continue + return config return None @@ -186,6 +212,40 @@ def windows_arguments(text): return arguments +def back_compat(config): + try: + root = ElementTree.fromstring(config.read_bytes()) + except (OSError, ElementTree.ParseError): + return False + return any(node.tag.rsplit('}', 1)[-1] == 'Identity' and node.get('Name', '').lower().startswith(BACK_COMPAT_IDENTITY) + for node in root.iter()) + + +def remove_gameinput_service(proton, prefix, env, installed=False): + # Just after an install action Wine may not have written system.reg yet; reg.exe sees its registry either way. + if not installed: + try: + registry = (prefix / 'system.reg').read_text(encoding='utf-8', errors='replace') + except OSError: + return + if '[%s]' % GAMEINPUT_SERVICE.replace('\\', '\\\\').lower() not in registry.lower(): + return + try: + code = subprocess.run([proton, 'run', 'reg.exe', 'delete', 'HKLM\\' + GAMEINPUT_SERVICE, '/f'], + stdout=sys.stderr, env=env, timeout=90).returncode + except subprocess.TimeoutExpired: + print('droiddeck-xbox: GameInput service class could not be removed (reg.exe timed out); launching with it', + file=sys.stderr) + return + except OSError as e: + print('droiddeck-xbox: GameInput service class could not be removed (%s); launching with it' % (e.strerror or e), + file=sys.stderr) + return + # reg.exe fails when the key is absent, which after an install action only means the action registered no class. + if code != 0 and not installed: + print('droiddeck-xbox: GameInput service class could not be removed; launching with it', file=sys.stderr) + + def install_actions(config): try: root = ElementTree.fromstring(config.read_bytes()) @@ -218,6 +278,10 @@ def run_install_actions(proton, prefix, exe, env): if config is None: return done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions' + original_xbox = back_compat(config) + if original_xbox: + env = dict({k: v for k, v in env.items() if k not in EMULATOR_SWITCHES}, **INSTALLER_FEX) + installed = False for name, target, arguments in install_actions(config): try: content = hashlib.sha256() @@ -243,11 +307,14 @@ def run_install_actions(proton, prefix, exe, env): if code != 0: print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr) continue + installed = True try: done.mkdir(parents=True, exist_ok=True) marker.touch() except OSError as error: print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr) + if original_xbox: + remove_gameinput_service(proton, prefix, env, installed) def view_drive(prefix, exe): diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index a0a3280d12..4eb7ba26f7 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -5,6 +5,7 @@ import re import runpy import shutil import sys +import tempfile TOOL = "droiddeck-proton-arm64" TOOL_11 = "droiddeck-proton-11-arm64" @@ -26,6 +27,8 @@ SNIPER_APPID = "1628350" SLR4_APPID = "4183110" FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID) REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES +ARM64_TOOL_DEPENDENCIES = (("1826330", "Proton EasyAntiCheat Runtime"), + ("1070560", "Steam Linux Runtime 1.0 (scout)")) # "0" = the app's "Valve Proton only when needed": Valve's ARM64 Proton is fetched only for a title or # default set to a tool built from it, or while no own Proton build is installed. VALVE_PROTON_ENV = "DD_VALVE_PROTON" @@ -1012,10 +1015,15 @@ def manifest_text(appid, name, installdir, bare=False): return text[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' if bare else text -def app_manifest(steam_root, app): +def manifest_paths(steam_root, app): for library in libraries(steam_root): + yield os.path.join(library, "steamapps", "appmanifest_%s.acf" % app) + + +def app_manifest(steam_root, app): + for path in manifest_paths(steam_root, app): try: - with open(os.path.join(library, "steamapps", "appmanifest_%s.acf" % app), encoding="utf-8", errors="replace") as f: + with open(path, encoding="utf-8", errors="replace") as f: return tokenize(f.read()) except OSError: continue @@ -1030,6 +1038,57 @@ def manifest_flags(tokens): return 0 +def installed_manifest(path): + try: + with open(path, encoding="utf-8", errors="replace") as f: + return bool(manifest_flags(tokenize(f.read())) & FULLY_INSTALLED) + except OSError: + return False + + +def seed_unavailable_arm64_tools(steam_root): + entries = appinfo_entries(os.path.join(steam_root, "appcache", "appinfo.vdf"), + [app for app, _ in ARM64_TOOL_DEPENDENCIES]) + steamapps = os.path.join(steam_root, "steamapps") + os.makedirs(steamapps, exist_ok=True) + seeded = [] + for app, display in ARM64_TOOL_DEPENDENCIES: + entry = entries.get(app) + if entry is not None: + if entry["type"] not in ("", "tool"): + continue + if "arm64" in entry["osarch"] or "aarch64" in entry["osarch"]: + continue + existing = [p for p in manifest_paths(steam_root, app) if os.path.isfile(p)] + if any(installed_manifest(p) for p in existing): + continue + name = (entry or {}).get("name") or display + installdir = (entry or {}).get("installdir") or name + path = existing[0] if existing else os.path.join(steamapps, "appmanifest_%s.acf" % app) + temporary = None + try: + with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", + dir=os.path.dirname(path), + prefix=".appmanifest_", delete=False) as f: + temporary = f.name + f.write(manifest_text(app, name, installdir, True)) + if existing: + os.replace(temporary, path) + else: + os.link(temporary, path) + except OSError as e: + print("steam-compatibility: could not mark %s installed (%s)" % (app, e)) + continue + finally: + if temporary is not None: + try: + os.unlink(temporary) + except OSError: + pass + seeded.append(app) + return seeded + + def valve_proton_on_demand(): return os.environ.get(VALVE_PROTON_ENV) == "0" @@ -1801,6 +1860,11 @@ def main(): steam_root = sys.argv[1] if "--valve-proton-needed" in sys.argv[2:]: sys.exit(0 if valve_proton_needed(steam_root) else 1) + if "--seed-arm64-tools" in sys.argv[2:]: + seeded = seed_unavailable_arm64_tools(steam_root) + if seeded: + print("steam-compatibility: marked unavailable ARM64 tool(s) installed: %s" % ", ".join(seeded)) + return if "--x64" in sys.argv[2:]: x64_repoint(steam_root, os.environ.get("DD_COMPAT_TOOL"), "--live" in sys.argv[2:]) return diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index a8ced09425..77152b105d 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -15,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -34,7 +36,8 @@ "NAME=\"Xbox 360 Controller (%d)\"\n" \ "PHYS=\"usb-fakeinput/input%d\"\n" -#define RING_SDL_ID 0x045e028eu +#define STEAM_VIRTUAL_VENDOR 0x28de +#define STEAM_VIRTUAL_PRODUCT 0x11ff #define PARENT_NAME "droiddeck-input" #define PARENT_SYSPATH_FORMAT "/sys/devices/droiddeck%d/" PARENT_NAME "%d" @@ -141,66 +144,8 @@ static int any_virtual_pad(void) { return 0; } -static char *sdl_id_list_text(const char *list) { - char *text = NULL; - char *grown; - size_t length = 0; - size_t got; - FILE *file; - - if (list[0] != '@') return strdup(list); - file = fopen(list + 1, "re"); - if (file == NULL) return NULL; - do { - grown = realloc(text, length + 4097); - if (grown == NULL) { - free(text); - fclose(file); - return NULL; - } - text = grown; - got = fread(text + length, 1, 4096, file); - length += got; - } while (got > 0); - fclose(file); - text[length] = '\0'; - return text; -} - -static int sdl_id_list_entries(const char *list, int *has_ring) { - char *text = sdl_id_list_text(list); - char *spot = text; - uint32_t entry; - int entries = 0; - - *has_ring = 0; - if (text == NULL) return 0; - while ((spot = strstr(spot, "0x")) != NULL) { - entry = (uint32_t)(uint16_t)strtol(spot, &spot, 0) << 16; - spot = strstr(spot, "0x"); - if (spot == NULL) break; - entry |= (uint16_t)strtol(spot, &spot, 0); - entries++; - if (entry == RING_SDL_ID) *has_ring = 1; - } - free(text); - return entries; -} - -static int sdl_bus_skips_ring_pad(void) { - const char *steam_virtual = getenv("FAKE_EVDEV_STEAM_VIRTUAL"); - const char *except = getenv("SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT"); - const char *ignore = getenv("SDL_GAMECONTROLLER_IGNORE_DEVICES"); - int has_ring; - - if (steam_virtual != NULL && atoi(steam_virtual) != 0) return 1; - if (except != NULL && sdl_id_list_entries(except, &has_ring) > 0) return !has_ring; - return ignore != NULL && sdl_id_list_entries(ignore, &has_ring) > 0 && has_ring; -} - static const char *ring_uevent_format(void) { - if (uinput_enabled() && any_virtual_pad()) return PAD_PHYSICAL_UEVENT_FORMAT; - return sdl_bus_skips_ring_pad() ? PAD_UEVENT_FORMAT : PAD_PHYSICAL_UEVENT_FORMAT; + return uinput_enabled() && any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT; } static void refresh_locked(int node) { @@ -514,6 +459,60 @@ static int caller_in_library(void *caller, const char *library) { static int caller_is_winebus(void *caller) { return caller_in_library(caller, "winebus.so"); } +static int note_winebus(struct dl_phdr_info *info, size_t size, void *data) { + (void)size; + if (info->dlpi_name == NULL || strstr(info->dlpi_name, "winebus.so") == NULL) return 0; + *(int *)data = 1; + return 1; +} + +static int winebus_reads_udev(void) { + const char *x360 = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360"); + int loaded = 0; + + if (x360 != NULL && atoi(x360) != 0) return 0; + dl_iterate_phdr(note_winebus, &loaded); + return loaded; +} + +static int ring_pad_fd(int fd) { + const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS"); + const char *entry; + struct stat opened; + struct stat ring; + char path[PATH_MAX]; + + if (spec == NULL || fstat(fd, &opened) != 0) return 0; + for (entry = spec; *entry != '\0';) { + char *end; + long slot = strtol(entry, &end, 10); + const char *next = strchr(entry, ';'); + size_t length; + + if (end != entry && *end == '=' && slot >= 0 && slot < RING_MAX) { + length = next != NULL ? (size_t)(next - end - 1) : strlen(end + 1); + if (length < sizeof(path)) { + memcpy(path, end + 1, length); + path[length] = '\0'; + if (stat(path, &ring) == 0 && ring.st_dev == opened.st_dev && ring.st_ino == opened.st_ino) return 1; + } + } + if (next == NULL) break; + entry = next + 1; + } + return 0; +} + +__attribute__((visibility("hidden"))) void dd_ring_pad_sdl_id(int fd, unsigned long request, void *arg, + void *caller, int rc) { + struct input_id *id = arg; + + if (rc != 0 || request != EVIOCGID || id == NULL) return; + if (!caller_in_library(caller, "libSDL") || !winebus_reads_udev() || !ring_pad_fd(fd)) return; + id->vendor = STEAM_VIRTUAL_VENDOR; + id->product = STEAM_VIRTUAL_PRODUCT; +} + typedef int (*sdl_rumble_fn)(void *, uint16_t, uint16_t, uint32_t); static _Atomic(sdl_rumble_fn) real_sdl_rumble; static __thread int winebus_sdl_call; diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index 38453ba5ab..6cd296b3d6 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -424,6 +424,8 @@ int dd_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute int dd_vdec_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); int dd_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, void *caller, int *rc) __attribute__((visibility("hidden"))); +void dd_ring_pad_sdl_id(int fd, unsigned long request, void *arg, void *caller, int rc) + __attribute__((visibility("hidden"))); int dd_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); @@ -444,6 +446,7 @@ int ioctl(int fd, unsigned long request, ...) { if (dd_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc; if (dd_writewatch_ioctl(real, fd, request, arg, &rc)) return rc; if (!dd_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg); + dd_ring_pad_sdl_id(fd, request, arg, __builtin_return_address(0), rc); dd_kgsl_track(real, fd, request, arg, &rc); dd_kgsl_chip_id_fixup(request, arg, rc); if (arg == NULL || !is_link_query(request)) return rc; diff --git a/tools/linuxfs/preload/robust.c b/tools/linuxfs/preload/robust.c index 12df5d662b..cfa7813844 100644 --- a/tools/linuxfs/preload/robust.c +++ b/tools/linuxfs/preload/robust.c @@ -140,7 +140,7 @@ static struct robust_list_head *thread_robust_head(void) { if ((uintptr_t)candidate & (sizeof(void *) - 1)) { continue; } - if (process_vm_readv(getpid(), &local, 1, &remote, 1, 0) != (ssize_t)sizeof(copy)) { + if (process_vm_readv(gettid(), &local, 1, &remote, 1, 0) != (ssize_t)sizeof(copy)) { continue; } uintptr_t entry = (uintptr_t)copy.list.next; diff --git a/tools/local-cross.Dockerfile b/tools/local-cross.Dockerfile index badaaf5efe..a517ee87c8 100644 --- a/tools/local-cross.Dockerfile +++ b/tools/local-cross.Dockerfile @@ -3,7 +3,7 @@ FROM ubuntu:24.04 ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update \ - && apt-get install -y binutils gcc g++ libvulkan-dev python3 zstd unzip \ + && apt-get install -y binutils gcc g++ libvulkan-dev python3 zstd unzip rpm2cpio cpio \ && if [ "$(uname -m)" = aarch64 ]; then \ for tool in gcc g++ strip readelf objdump ar; do ln -s "$(command -v $tool)" /usr/local/bin/aarch64-linux-gnu-$tool; done; \ else \ diff --git a/tools/nativeguest/README.md b/tools/nativeguest/README.md index 19571de96c..156c2927a1 100644 --- a/tools/nativeguest/README.md +++ b/tools/nativeguest/README.md @@ -17,6 +17,20 @@ same length: the code compares environment names by length) and extended with: Build: `tools/nativeguest/build.sh out.so` with an aarch64 glibc cross compiler. +## Root or an ordinary user + +Every program sees itself as root by default, which apt, dpkg and the session expect. +`DDNATV_USER=app` in a process's environment makes it, and everything it starts, the app's own +Android user instead, named `deck` (home `/root`): its ids, its files' owners, `/proc/*/status` and +peer credentials are the kernel's, and it may not change its ids. `DDNATV_BECOME=root` or `=app` in +a started program's environment switches that program and its children; the hook drops both +variables and puts `DDNATV_USER=app` first in the environment, where a peer's mode is read from +`/proc//environ`. A set-user-ID program owned by the app (shown as root's) starts as root. + +`droiddeck-user [COMMAND]` starts a shell or command that way, `sudo` and `su` return to root, and +Performance > "Desktop runs as a user" starts the whole Plasma session as `deck`. Statically linked +Go programs are patched once on disk and still see root. + ## Testing under Android's seccomp filter Some devices (eng builds, `setenforce 0` ROMs) run apps with no seccomp filter, so a hook that diff --git a/tools/nativeguest/ddnatv-hook.c b/tools/nativeguest/ddnatv-hook.c index 4070f55c85..bf4c1679e2 100644 --- a/tools/nativeguest/ddnatv-hook.c +++ b/tools/nativeguest/ddnatv-hook.c @@ -77,11 +77,13 @@ #include "hook/files.c" #include "hook/fileops.c" #include "hook/identity.c" +#include "hook/kept.c" #include "hook/privileged.c" #include "hook/env.c" #include "hook/exec_probe.c" #include "hook/static_programs.c" #include "hook/go_programs.c" +#include "hook/handoff.c" #include "hook/exec.c" #include "hook/net.c" #include "hook/sockets.c" diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c index 7c9a1ac77e..d83ad87492 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -99,6 +99,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const int has_exec_loader = 0; int has_preload_list = 0; const char *preload_value = NULL; + const char *become = NULL; while (envp && envp[count]) { const char *e = envp[count]; switch (e[0]) { @@ -127,6 +128,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const else if (strncmp(e, "DDNATV_HOSTNAME=", 16) == 0) has_hostname = 1; else if (strncmp(e, "DDNATV_LINK_ROOT=", 17) == 0) has_link_root = 1; else if (strncmp(e, "DDNATV_EXEC=", 12) == 0) has_exec_loader = 1; + else if (strncmp(e, "DDNATV_BECOME=", 14) == 0) become = e + 14; else if (strncmp(e, "DPKG_DEB_THREADS_MAX=", 21) == 0) has_threads_max = 1; else if (strncmp(e, "DEBIAN_FRONTEND=", 16) == 0) has_frontend = 1; else if (strncmp(e, "DEBCONF_FRONTEND=", 17) == 0) has_debconf_frontend = 1; @@ -138,9 +140,23 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const count++; } - char **new_env = calloc(count + 25, sizeof(char *)); + char **new_env = calloc(count + 26, sizeof(char *)); int dst = 0; + // The user the program runs as (hardlinks.c): this process's, whatever the environment it passes + // says, unless DDNATV_BECOME asks for one, or the program is set-user-ID root's (the app's files + // are root's), as the kernel would start it. First in the block, where a peer looks (sockets.c). + int as_app = app_user_mode(); + if (become) as_app = strcmp(become, "app") == 0; + else if (as_app && real_exe && real_exe[0] == '/') { + struct stat st; + if (real_fstatat(AT_FDCWD, real_exe, &st, 0) == 0 && S_ISREG(st.st_mode) && (st.st_mode & S_ISUID) + && st.st_uid == app_uid_now()) as_app = 0; + } + if (as_app) new_env[dst++] = strdup("DDNATV_USER=app"); for (int i = 0; i < count; i++) { + if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) { + continue; + } if (has_preload && envp[i][0] == 'L' && strncmp(envp[i], "LD_PRELOAD=", 11) == 0) { // ld.so opens these itself: the guest's paths are mapped to the rootfs, and the libraries every // program loads (DDNATV_PRELOAD) come first diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index eb2659f37d..db55262540 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOSYS; return -1; } + if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp); // Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0), // like the kernel would pass it; routing below uses the absolute form. @@ -452,7 +453,8 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e char resolved_target[PATH_MAX]; // Only intercept binaries/scripts within DDNATV_ROOT - if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename)) { + if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename) || + is_bound_guest_program(target)) { struct exec_probe probe; const char *elf_target = select_exec_target(target, resolved_target, sizeof(resolved_target), &probe); if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target; @@ -537,11 +539,9 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ELOOP; ret = -1; } else { - char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL); - ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1); - int saved_errno = errno; - free_modified_env(ddnatv_env, envp); - errno = saved_errno; + // The interpreter's exec prepares the environment, as posix_spawn's does: done here + // too, it dropped DDNATV_BECOME before the interpreter could take it (sudo SCRIPT) + ret = ddnatv_execve(rewritten_interp, new_argv, envp, depth + 1); } free(new_argv); return ret; @@ -659,7 +659,19 @@ pid_t fork(void) { int n = __atomic_add_fetch(&forks, 1, __ATOMIC_RELAXED); if (n == 1 || n >= DDNATV_FORKS_BEFORE_REHEARSAL) prepare_exec_in_parent(n >= DDNATV_FORKS_BEFORE_REHEARSAL ? 2 : 1); } + ddh_prepare(); + pid_t forker = (pid_t)syscall(SYS_gettid); + pid_t forking = (pid_t)syscall(SYS_getpid); pid_t pid = orig_fork(); + if (pid == 0) { + kept_forked(); + kept_close_forked(); + ddh_drop_worker_binder(); + ddh_forked(forker); + ddh_record_parent((pid_t)syscall(SYS_getpid), forking); + } else if (pid > 0) { + ddh_child_created(pid, 1); + } // A child forked from a signal handler that interrupted a rehearsal is not rehearsing: its // execve() is a real one (only read in the usual case, so no page is copied for it) if (pid == 0 && __atomic_load_n(&g_exec_rehearsal, __ATOMIC_RELAXED)) __atomic_store_n(&g_exec_rehearsal, 0, __ATOMIC_RELAXED); @@ -969,7 +981,8 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, } char *const *orig_ep = envp ? envp : environ; - int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path); + int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path) || + is_bound_guest_program(target); struct exec_probe probe; char resolved_target[PATH_MAX]; @@ -1065,6 +1078,215 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, static int apply_closefrom(posix_spawn_file_actions_t *actions); +// glibc's file actions (posix/spawn_int.h, unchanged since 2.35) +struct ddh_spawn_action { + enum { DDH_DO_CLOSE, DDH_DO_DUP2, DDH_DO_OPEN, DDH_DO_CHDIR, DDH_DO_FCHDIR, DDH_DO_CLOSEFROM, DDH_DO_TCSETPGRP } tag; + union { + struct { int fd; } close_action; + struct { int fd; int newfd; } dup2_action; + struct { int fd; char *path; int oflag; mode_t mode; } open_action; + struct { char *path; } chdir_action; + struct { int fd; } fchdir_action; + struct { int from; } closefrom_action; + struct { int fd; } setpgrp_action; + } action; +}; + +#ifndef POSIX_SPAWN_SETSID +#define POSIX_SPAWN_SETSID 0x80 +#endif + +static int ddh_spawn_errno(long ret) { + return ret < 0 ? errno : 0; +} + +static int ddh_spawn_close_part(unsigned int first, unsigned int last, void *unused) { + (void)unused; + return (int)call_orig_syscall(SYS_close_range, first, last, 0, 0, 0, 0); +} + +// What glibc's spawn child does before its exec (posix/spawni.c), as an errno. Its fd and +// directory work is done with system calls, not the hook's wrappers: those take locks that another +// thread of the parent may have held at fork() (Steam has many threads). +static int ddh_spawn_child_setup(const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr) { + short flags = 0; + if (attr) posix_spawnattr_getflags(attr, &flags); + if (flags & POSIX_SPAWN_SETSIGDEF) { + sigset_t def; + posix_spawnattr_getsigdefault(attr, &def); + for (int sig = 1; sig < _NSIG; sig++) { + if (sigismember(&def, sig) == 1) signal(sig, SIG_DFL); + } + } + if ((flags & POSIX_SPAWN_SETSID) && setsid() < 0) return errno; + if (flags & POSIX_SPAWN_SETPGROUP) { + pid_t group = 0; + posix_spawnattr_getpgroup(attr, &group); + if (setpgid(0, group) != 0) return errno; + } + if (flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM)) { + struct sched_param param; + posix_spawnattr_getschedparam(attr, ¶m); + int policy = 0; + posix_spawnattr_getschedpolicy(attr, &policy); + int r = (flags & POSIX_SPAWN_SETSCHEDULER) ? sched_setscheduler(0, policy, ¶m) : sched_setparam(0, ¶m); + if (r == -1) return errno; + } + const struct ddh_spawn_action *a = fa ? (const struct ddh_spawn_action *)fa->__actions : NULL; + char path[PATH_MAX]; + int err; + for (int i = 0; a && i < fa->__used; i++) { + switch (a[i].tag) { + case DDH_DO_CLOSE: + // the handoff table and the worker's binder stay open (kept fds) + if (!is_kept_fd(a[i].action.close_action.fd)) + call_orig_syscall(SYS_close, (unsigned long)a[i].action.close_action.fd, 0, 0, 0, 0, 0); + break; + case DDH_DO_OPEN: { + const char *real = rewrite_path(a[i].action.open_action.path, path, sizeof(path)); + // as glibc: the target goes first, so a full fd table still has room for the open + if (!is_kept_fd(a[i].action.open_action.fd)) + call_orig_syscall(SYS_close, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0, 0); + long fd = call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real, + (unsigned long)a[i].action.open_action.oflag, a[i].action.open_action.mode, 0, 0); + if (fd < 0) return errno; + if (fd != a[i].action.open_action.fd) { + if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)fd, (unsigned long)a[i].action.open_action.fd, 0, 0, 0, 0)))) + return err; + call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0); + } + break; + } + case DDH_DO_DUP2: { + int from = a[i].action.dup2_action.fd, to = a[i].action.dup2_action.newfd; + if (from == to) { + long fdflags = call_orig_syscall(SYS_fcntl, (unsigned long)from, F_GETFD, 0, 0, 0, 0); + if (fdflags < 0) return errno; + if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fcntl, (unsigned long)from, F_SETFD, (unsigned long)(fdflags & ~FD_CLOEXEC), 0, 0, 0)))) + return err; + } else if ((err = ddh_spawn_errno(call_orig_syscall(SYS_dup3, (unsigned long)from, (unsigned long)to, 0, 0, 0, 0)))) { + return err; + } + break; + } + case DDH_DO_CHDIR: { + const char *real = rewrite_path_follow(a[i].action.chdir_action.path, path, sizeof(path)); + if ((err = ddh_spawn_errno(call_orig_syscall(SYS_chdir, (unsigned long)real, 0, 0, 0, 0, 0)))) return err; + break; + } + case DDH_DO_FCHDIR: + if ((err = ddh_spawn_errno(call_orig_syscall(SYS_fchdir, (unsigned long)a[i].action.fchdir_action.fd, 0, 0, 0, 0, 0)))) + return err; + break; + case DDH_DO_CLOSEFROM: + for_each_range_without((unsigned int)a[i].action.closefrom_action.from, ~0U, g_kept_fds, g_kept_fd_count, + ddh_spawn_close_part, NULL); + break; + case DDH_DO_TCSETPGRP: + if (tcsetpgrp(a[i].action.setpgrp_action.fd, getpgrp()) != 0) return errno; + break; + } + } + if (flags & POSIX_SPAWN_SETSIGMASK) { + sigset_t mask; + posix_spawnattr_getsigmask(attr, &mask); + sigprocmask(SIG_SETMASK, &mask, NULL); + } + return 0; +} + +// posix_spawn() as fork() and execve(), so that ddh_try() sees the exec. -1 when it cannot be. +static int ddh_spawn_forked(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + if (fa) { + const struct ddh_spawn_action *a = (const struct ddh_spawn_action *)fa->__actions; + // A terminal action stays with glibc, which blocks signals around the file actions: here a + // SIGTTOU could stop the child at tcsetpgrp() with the parent waiting on its report. + for (int i = 0; i < fa->__used; i++) { + if ((unsigned)a[i].tag >= DDH_DO_TCSETPGRP) return -1; + } + } + // A scheduling policy or priority would apply to this child, not to the worker that runs the program + short spawn_flags = 0; + if (attr && posix_spawnattr_getflags(attr, &spawn_flags) == 0 && + (spawn_flags & (POSIX_SPAWN_SETSCHEDULER | POSIX_SPAWN_SETSCHEDPARAM))) + return -1; + // Not cancelled while the child is being started (its report is read, and its failure reaped): + // the pid would be lost with the child still running, and the report's fd left open. + int cancel = PTHREAD_CANCEL_ENABLE; + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel); + int report[2]; + if (pipe2(report, O_CLOEXEC) != 0) { + pthread_setcancelstate(cancel, NULL); + return -1; + } + // Every signal blocked from the fork to the exec, as glibc's posix_spawn() does: a signal to the + // group during a file action (an open of a FIFO that blocks) would otherwise run the caller's + // handler, or end the child, before the program is started. The child gets back the caller's mask, + // or the one the attributes ask for, just before its exec. + sigset_t all, caller; + sigfillset(&all); + pthread_sigmask(SIG_SETMASK, &all, &caller); + pid_t child = fork(); + if (child < 0) { + int err = errno; + pthread_sigmask(SIG_SETMASK, &caller, NULL); + close(report[0]); + close(report[1]); + pthread_setcancelstate(cancel, NULL); + return err; + } + if (child > 0) pthread_sigmask(SIG_SETMASK, &caller, NULL); + if (child == 0) { + call_orig_syscall(SYS_close, (unsigned long)report[0], 0, 0, 0, 0, 0); + // Out of the file actions' way: high, and one of the fds they leave open (closefrom(3) is common) + int to_parent = (int)call_orig_syscall(SYS_fcntl, (unsigned long)report[1], F_DUPFD_CLOEXEC, 1000, 0, 0, 0); + if (to_parent >= 0) { + call_orig_syscall(SYS_close, (unsigned long)report[1], 0, 0, 0, 0, 0); + ddh_keep(to_parent); + } else { + to_parent = report[1]; + } + int err = ddh_spawn_child_setup(fa, attr); + if (!err) { + // A signal still pending when the mask is restored must not run a handler copied from the + // caller: caught signals go back to their default, ignored ones stay ignored (exec keeps + // them), and SIGSYS keeps the hook's handler. + for (int sig = 1; sig < _NSIG; sig++) { + struct sigaction old; + if (sig == SIGSYS || sig == SIGKILL || sig == SIGSTOP) continue; + if (sigaction(sig, NULL, &old) != 0) continue; + if (old.sa_handler == SIG_IGN || old.sa_handler == SIG_DFL) continue; + struct sigaction def = {0}; + def.sa_handler = SIG_DFL; + sigaction(sig, &def, NULL); + } + short flags = 0; + if (attr) posix_spawnattr_getflags(attr, &flags); + if (!(flags & POSIX_SPAWN_SETSIGMASK)) sigprocmask(SIG_SETMASK, &caller, NULL); + execve(path, argv, envp); + err = errno; + } + syscall(SYS_write, to_parent, &err, sizeof(err)); + _exit(127); + } + close(report[1]); + int err = 0; + ssize_t n; + do n = read(report[0], &err, sizeof(err)); + while (n < 0 && errno == EINTR); + close(report[0]); + if (n == (ssize_t)sizeof(err)) { + while (waitpid(child, NULL, 0) < 0 && errno == EINTR) { + } + pthread_setcancelstate(cancel, NULL); + return err; + } + if (pid) *pid = child; + pthread_setcancelstate(cancel, NULL); + return 0; +} + int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, @@ -1074,7 +1296,18 @@ int posix_spawn(pid_t *pid, const char *path, if (bad) return bad; } posix_spawnattr_t sanitized; - return ddnatv_posix_spawn(pid, path, file_actions, spawn_attr_for_android(attrp, &sanitized), argv, envp, 0); + const posix_spawnattr_t *attr = spawn_attr_for_android(attrp, &sanitized); + if (ddh_spawn_wanted(path, argv, envp ? envp : environ)) { + int ret = ddh_spawn_forked(pid, path, file_actions, attr, argv, envp ? envp : environ); + if (ret != -1) return ret; + } + pid_t child = 0; + int ret = ddnatv_posix_spawn(&child, path, file_actions, attr, argv, envp, 0); + if (ret == 0) { + ddh_child_created(child, 0); + if (pid) *pid = child; + } + return ret; } int posix_spawnp(pid_t *pid, const char *file, diff --git a/tools/nativeguest/hook/exec_probe.c b/tools/nativeguest/hook/exec_probe.c index be708e9158..32dabeb982 100644 --- a/tools/nativeguest/hook/exec_probe.c +++ b/tools/nativeguest/hook/exec_probe.c @@ -983,6 +983,14 @@ static int is_host_interpreter(const char *interp, const char *rewritten) { return probe.android_interp; } +static int is_bound_guest_program(const char *path) { + if (g_ddnatv_root[0] == '\0' || !is_identity_bound_path(path)) return 0; + struct exec_probe probe; + probe_exec_file(path, &probe); + if (probe.is_elf) return probe.is_dynamic && !probe.android_interp; + return probe.n >= 2 && probe.hdr[0] == '#' && probe.hdr[1] == '!'; +} + // argv for running `script` with its interpreter: interp [arg] script args... (the script's own // argv[0] is dropped, as the kernel does). free() the result. static char **build_script_argv(const char *interp, const char *interp_arg, const char *script, char *const argv[]) { diff --git a/tools/nativeguest/hook/fileops.c b/tools/nativeguest/hook/fileops.c index 840812fe69..a515e6a248 100644 --- a/tools/nativeguest/hook/fileops.c +++ b/tools/nativeguest/hook/fileops.c @@ -739,10 +739,8 @@ char *getcwd(char *buf, size_t size) { static char *(*orig_getcwd)(char *, size_t) = NULL; if (!orig_getcwd) orig_getcwd = (char *(*)(char *, size_t))dlsym(RTLD_NEXT, "getcwd"); char *res = orig_getcwd ? orig_getcwd(buf, size) : NULL; - if (res) { - size_t len = strlen(res); - guest_path_of_mount_source(res, len, buf ? size : len + 1, NULL); - } + if (res && !buf) return guest_path_of_allocated_mount_source(res); + if (res) guest_path_of_mount_source(res, strlen(res), size, NULL); return res; } @@ -790,7 +788,8 @@ char *realpath(const char *path, char *resolved_path) { } } } - if (res) guest_path_of_mount_source(res, strlen(res), resolved_path ? PATH_MAX : strlen(res) + 1, NULL); + if (res && !resolved_path) return guest_path_of_allocated_mount_source(res); + if (res) guest_path_of_mount_source(res, strlen(res), PATH_MAX, NULL); return res; } diff --git a/tools/nativeguest/hook/files.c b/tools/nativeguest/hook/files.c index 37a8a85636..318adb79ef 100644 --- a/tools/nativeguest/hook/files.c +++ b/tools/nativeguest/hook/files.c @@ -155,7 +155,7 @@ static void proc_status_root_ids(char *text, size_t len, const char *field, unsi // The status file with the app's ids as root's, in a memory file; -2 when `path` is no such file // or is opened for writing. static int open_proc_status(const char *path, int flags) { - if ((flags & O_ACCMODE) != O_RDONLY || !is_proc_status_path(path) || !reader_compares_process_ids()) return -2; + if ((flags & O_ACCMODE) != O_RDONLY || app_user_mode() || !is_proc_status_path(path) || !reader_compares_process_ids()) return -2; int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); if (fd < 0) return -1; char text[16384]; diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c new file mode 100644 index 0000000000..0827c29823 --- /dev/null +++ b/tools/nativeguest/hook/handoff.c @@ -0,0 +1,2774 @@ +// Part of libddnatv-hook.so, included by ddnatv-hook.c after exec.c. +// +// Exec handoff. Android counts every process in the app's cgroup against its child-process limit, +// but not the app's own processes (docs/phantom-processes.md). A program a guest starts with +// fork() + execve() can instead run as the main process of one of the app's worker processes: the +// forked child sends the exec to the app (DD_SPAWN, an abstract socket) with its open fds, records +// the worker's pid in a table it shares with its parent, and exits. For the parent nothing changes: +// wait*(), kill() and SIGCHLD treat the pid fork() returned as that program until it exits; its exit +// status reaches the table from the program's hook, or for a signal from the app's report (see +// ddh_check_gone()), and the parent gets SIGCHLD. +// +// Only programs named in DD_HANDOFF (basenames separated by ':', or "*") are handed off, and, once +// the app is near Android's limit, a shell's children (ddh_pressed). The child's +// side runs where vfork() children run too, so it allocates nothing and writes no globals. +#include +#include + +#define DDH_SLOTS 1024 +#define DDH_FREE 0 +#define DDH_CLAIMED 3 +#define DDH_HANDED 1 +#define DDH_EXITED 2 +#define DDH_TAKEN 4 // its exit is being reported to one waiter +#define DDH_NO_STATUS INT32_MIN +#define DDH_MAGIC 0x6464686f +#define DDH_TABLE_FD 800 + +struct ddh_entry { + int32_t child; // the pid the parent got from fork() + int32_t real; // the worker's pid + int32_t parent; + int32_t state; + int32_t status; // wait status + int32_t reaped; // the parent has reaped the forked child itself + int32_t pad[2]; + // The app's report of a program that died without exit() or _exit() (GuestWorkers.reportExit): + // the wait status and the child it is for, in one 8-byte write. Only this side changes state. + int32_t app[2] __attribute__((aligned(8))); + int64_t child_start; // the forked child's start time: tells it from a later process given its pid + int32_t guessed; // the status is the timeout's guess: set only while the entry is held (TAKEN) + int32_t gen; // moved on by every claim of the slot, never 0, kept through a release (ddh_reaped()) + // When its worker was first seen gone, with the child that was for: child << 32 | seconds. Set by + // compare-and-swap only, so a waiter that looked before the slot changed hands cannot overwrite it. + uint64_t gone; +}; + +struct ddh_table { + int32_t magic; + int32_t pad[15]; + struct ddh_entry e[DDH_SLOTS]; +}; + +static struct ddh_table *g_ddh; // this process's table, for the children it forks +// A table given up while a close from before it was kept may still be under way: open, unkept, and +// tried again (not another made) until that close is over, so a close that never ends costs one fd. +static struct ddh_table *g_ddh_candidate; +static int g_ddh_candidate_fd = -1; +static int g_ddh_fd = -1; +static pid_t g_ddh_owner; +// The parent's table, when this image was exec'd by a child the parent forked (a wrapper such as +// env or a script that execs its program): that exec can still be handed off. +static struct ddh_table *g_ddh_up; +static int g_ddh_up_fd = -1; + +static const char *ddh_env(char *const envp[], const char *name) { + size_t n = strlen(name); + for (char *const *e = envp; e && *e; e++) { + if (strncmp(*e, name, n) == 0 && (*e)[n] == '=') return *e + n + 1; + } + return NULL; +} + +// DD_HANDOFF_DEBUG=1 writes the trace to stderr; an absolute path appends it to that file instead +// (stderr can be a pipe a program parses, or one nobody reads). +static void ddh_log(const char *setting, const char *line, size_t len) { + if (!setting || len == 0) return; + if (setting[0] != '/') { + syscall(SYS_write, 2, line, len); + return; + } + // non-blocking: a FIFO with no reader must not hold up the call being traced (a kill()) + int fd = (int)syscall(SYS_openat, AT_FDCWD, setting, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC | O_NONBLOCK, 0644); + if (fd < 0) return; + syscall(SYS_write, fd, line, len); + syscall(SYS_close, fd); +} + +// In the parent, before fork(): the table the children write to. +static void ddh_prepare_failed(const char *step) { + const char *debug = getenv("DD_HANDOFF_DEBUG"); + if (!debug) return; + char line[96]; + int len = snprintf(line, sizeof(line), "ddnatv handoff: %d no table: %s errno %d\n", (int)getpid(), step, errno); + if (len > 0) ddh_log(debug, line, (size_t)len); +} + +static void ddh_keep(int fd); +static void ddh_unkeep(int fd); + +// An fd's target that is one of Android's binder devices (directly or through binderfs). +static int ddh_is_binder(const char *target) { + return strcmp(target, "/dev/binder") == 0 || strcmp(target, "/dev/hwbinder") == 0 || + strcmp(target, "/dev/vndbinder") == 0 || strncmp(target, "/dev/binderfs/", 14) == 0; +} + +// The table the children write to, in a process of a session that hands programs off (DD_SPAWN). +// One thread makes it; a fork() while another thread is making it goes without (its child runs here). +static int g_ddh_preparing; + + +// Set by the waits with __WNOTHREAD: only children this thread forked are selected. +static __thread pid_t t_ddh_only_thread; + +// Which of this process's threads forked which child, in memory this process shares with the +// children it forks: the child may exec wrappers before it claims an entry, and those cannot carry +// it. One record per pid, at the pid's own index: two live children never share a pid, so nothing is +// ever full or pushed out, and a fork that gets a pid replaces whatever record a gone child left +// there; a record is never removed, and the child's start time in it tells it from a later child's. +// A child of fork() writes its own record before it can exit, so before its pid can be anyone +// else's (ddh_forked()); a posix_spawn() child runs nothing of this before its exec, so the parent +// writes its record once the call returns, by when it may be gone (ddh_forked_by()). Mapped when +// first needed, and only the pages of pids used are ever touched. One word: a record is only ever +// whole. A child not in here (a raw clone()) is no thread's for a __WNOTHREAD wait. +#define DDH_FORKS (1u << 22) /* PID_MAX_LIMIT */ +static uint64_t *g_ddh_forks; + +// child << 42 | thread << 20 | known << 19 | self << 18 | the child's start time's low 18 bits: pids +// and thread ids are below 2^22 (PID_MAX_LIMIT). The start time tells the record of one child from +// that of a later one given the same pid: a handoff entry holds its forked child's start time +// (child_start), and a record that does not match it is not that child's. Without the known bit it +// was not read, and matches any; 18 bits are 2^18 clock ticks (43 minutes at 100 Hz) apart. Self: +// the child wrote it, while it had the pid. +#define DDH_REC_KNOWN 0x80000u +#define DDH_REC_SELF 0x40000u +#define DDH_REC_START 0x3ffffu +static long ddh_start_time(pid_t pid); +static uint64_t ddh_fork_record(pid_t child, pid_t thread, long start, int self) { + uint64_t when = start > 0 ? ((uint64_t)start & DDH_REC_START) | DDH_REC_KNOWN : 0; + if (self) when |= DDH_REC_SELF; + return (uint64_t)((uint32_t)child & 0x3fffff) << 42 | (uint64_t)((uint32_t)thread & 0x3fffff) << 20 | when; +} +static pid_t ddh_record_child(uint64_t r) { return (pid_t)(r >> 42); } +static pid_t ddh_record_thread(uint64_t r) { return (pid_t)((r >> 20) & 0x3fffff); } +// Whether a record names a child that started at start (a time read for it, > 0) +static int ddh_record_started(uint64_t r, long start) { + return (r & DDH_REC_KNOWN) && start > 0 && ((uint64_t)start & DDH_REC_START) == (r & DDH_REC_START); +} + +static uint64_t *ddh_forks(int create) { + uint64_t *map = __atomic_load_n(&g_ddh_forks, __ATOMIC_ACQUIRE); + if (map || !create) return map; + void *fresh = mmap(NULL, (size_t)DDH_FORKS * sizeof(uint64_t), PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + if (fresh == MAP_FAILED) return NULL; + uint64_t *none = NULL; + if (__atomic_compare_exchange_n(&g_ddh_forks, &none, (uint64_t *)fresh, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) + return fresh; + munmap(fresh, (size_t)DDH_FORKS * sizeof(uint64_t)); + return none; +} + +// Whether the child a record names, started when it says, has a handoff whose program is running or +// whose exit is not yet reported: such a child loses its __WNOTHREAD owner with its record. +static int ddh_record_pending(uint64_t r) { + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + if (!t || !(r & DDH_REC_KNOWN)) return 0; + pid_t me = getpid(), child = ddh_record_child(r); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &t->e[i]; + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st == DDH_CLAIMED || st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->parent == me && + e->child == child && ddh_record_started(r, (long)e->child_start)) return 1; + } + return 0; +} + +// The record of a posix_spawn() child, by the parent: by now the child may be gone, its pid another +// child's. +static void ddh_forked_by(pid_t child, pid_t thread) { + uint64_t *map = ddh_forks(1); + if (!map || child <= 0) return; + int saved = errno; + long start = ddh_start_time(child); + errno = saved; + uint64_t mine = ddh_fork_record(child, thread, start, 0); + uint64_t *slot = &map[(uint32_t)child % DDH_FORKS]; + uint64_t seen = __atomic_load_n(slot, __ATOMIC_ACQUIRE); + for (;;) { + // A fork child that could not read its own start time (out of fds, say) has no time to tell its + // record by, and the time read here may be that child's own: whether it is a later child than + // this one, maybe yet to hand its program off, cannot be told. Its record stays. (The cost: + // this child, if the fork child was an earlier one, has no record; a handoff it makes through + // a wrapper is then no thread's for a __WNOTHREAD wait.) + if (seen && ddh_record_child(seen) == child && (seen & DDH_REC_SELF) && !(seen & DDH_REC_KNOWN)) return; + if (seen && ddh_record_child(seen) == child && (seen & DDH_REC_KNOWN)) { + // A child that recorded itself, started when the time read here says, has the pid: this + // one is gone, and that time was the other child's. + if ((seen & DDH_REC_SELF) && ddh_record_started(seen, start)) return; + // A later child given the pid (this one reaped while its record was being made) has + // recorded itself already: its record stays. It is that child's only while the process + // that has the pid now started when it says; any other record of the pid is an earlier + // child's. A record without a start time (this child was gone before it was read) + // matches any child of the pid, a later one's too. + if (!ddh_record_started(seen, start)) { + saved = errno; + long now = ddh_start_time(child); + errno = saved; + if (ddh_record_started(seen, now)) return; + // Neither child has the pid now: one whose program still runs in a worker, its + // forked child reaped by another thread, keeps its record unless this child's runs too. + if (!ddh_record_started(mine, now) && ddh_record_pending(seen) && !ddh_record_pending(mine)) return; + } + } + if (__atomic_compare_exchange_n(slot, &seen, mine, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) return; + } +} + +// The thread that forked child, by the record of the fork whose child started at child_start (-1: +// any); 0 when there is none. +static pid_t ddh_forking_thread(pid_t child, long child_start) { + uint64_t *map = ddh_forks(0); + uint64_t r = map && child > 0 ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0; + if (!r || ddh_record_child(r) != child) return 0; + if ((r & DDH_REC_KNOWN) && child_start > 0 && !ddh_record_started(r, child_start)) return 0; // another child's + return ddh_record_thread(r); +} + +// In a forked child, by the thread that forked it: the child records itself in the parent's fork +// records first, while its pid is still its own. The thread making the table did not come along, so +// the child may make its own, and fork records of its own: it starts with an empty map (none, if it +// cannot map one, and then hands nothing off). +static void ddh_forked(pid_t thread) { + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELAXED); + if (g_ddh_candidate) munmap(g_ddh_candidate, sizeof(struct ddh_table)); // its fd: close-on-exec + g_ddh_candidate = NULL; + g_ddh_candidate_fd = -1; + uint64_t *old = __atomic_exchange_n(&g_ddh_forks, NULL, __ATOMIC_ACQ_REL); + if (!old) return; + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) { + int saved = errno; + pid_t me = (pid_t)syscall(SYS_getpid); + // tests only: as a child that cannot read its start time + long start = getenv("DDH_TEST_FORK_START_UNKNOWN") ? -1 : ddh_start_time(me); + uint64_t mine = ddh_fork_record(me, thread, start, 1); + __atomic_store_n(&old[(uint32_t)me % DDH_FORKS], mine, __ATOMIC_RELEASE); + errno = saved; + } + munmap(old, (size_t)DDH_FORKS * sizeof(uint64_t)); + ddh_forks(1); +} + +// Tests only ("FD"): once the table's fd is kept, before the wait for earlier closes, a byte to FD. +static void ddh_table_kept_gate(void) { + const char *gate = getenv("DDH_TEST_TABLE_KEPT"); + if (!gate) return; + int saved = errno; + char c = 1; + syscall(SYS_write, atoi(gate), &c, 1); + errno = saved; +} + +static int ddh_prepare_table(void); +static int ddh_new_table(int *made_fd, struct ddh_table **made); +static int ddh_is_table(int fd, const struct ddh_table *t); + +static void ddh_prepare(void) { + // the parent records which thread forks each child (ddh_forked_by()); a child refuses a handoff + // when it cannot (ddh_try()) + if (getenv("DD_SPAWN")) ddh_forks(1); + // A thread with a table of its own makes none: its fd would be in no other thread's table. + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !getenv("DD_SPAWN") || t_kept_split) return; + // Not cancelled from taking the guard to giving it back (the wait for earlier closes sleeps, a + // cancellation point, and asynchronous cancellation could strike anywhere), which would leave the + // guard taken and the candidate's state half kept for every later fork. The guard goes back + // before cancellation can come again. + int cancel = PTHREAD_CANCEL_ENABLE; + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel); + if (!__atomic_exchange_n(&g_ddh_preparing, 1, __ATOMIC_ACQ_REL)) { + // a second try for a table another thread's close took before it was kept + for (int attempt = 0; !g_ddh && attempt < 2 && !ddh_prepare_table(); attempt++) {} + __atomic_store_n(&g_ddh_preparing, 0, __ATOMIC_RELEASE); + } + pthread_setcancelstate(cancel, NULL); +} + +// 1 when the table is made (g_ddh), 0 when its fd went to another thread's close before that one +// could see it was kept, or such a close was not over in time; the other failures are logged and end +// the trying too (1). +static int ddh_prepare_table(void) { + struct ddh_table *p = g_ddh_candidate; + int fd = g_ddh_candidate_fd; + g_ddh_candidate = NULL; + g_ddh_candidate_fd = -1; + if (p && ddh_is_table(fd, p)) { + ddh_keep(fd); + } else { + if (p) munmap(p, sizeof(struct ddh_table)); // closed since: a new one + if (!ddh_new_table(&fd, &p)) return 1; + } + // Another thread's close() or close_range() that looked at the kept fds before this one was among + // them may have closed it (and an open() taken the number): once those are over, it is still this + // table, or it is given up. Given up, the number is not closed here: a close still under way may + // close it any time, and another thread then reuse it before a close here would come. + ddh_table_kept_gate(); + int settled = kept_settle(); + if (!settled || !ddh_is_table(fd, p)) { + ddh_unkeep(fd); + if (!settled && ddh_is_table(fd, p)) { + g_ddh_candidate = p; + g_ddh_candidate_fd = fd; + } else { + munmap(p, sizeof(struct ddh_table)); + } + return 0; + } + g_ddh_fd = fd; + g_ddh_owner = getpid(); + __atomic_store_n(&g_ddh, p, __ATOMIC_RELEASE); + return 1; +} + +// A new table, kept: 0 when one cannot be made (logged). +static int ddh_new_table(int *made_fd, struct ddh_table **made) { + int fd = (int)syscall(SYS_memfd_create, "ddnatv-handoff", 1 /* MFD_CLOEXEC */); + if (fd < 0) { + ddh_prepare_failed("memfd_create"); + return 0; + } + if (ftruncate(fd, sizeof(struct ddh_table)) != 0) { + ddh_prepare_failed("ftruncate"); + close(fd); + return 0; + } + struct ddh_table *p = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) { + ddh_prepare_failed("mmap"); + close(fd); + return 0; + } + // Out of the way of the numbers programs redirect, and kept open when a child closes every + // inherited fd before exec (Python's subprocess does): the child needs it for its handoff. + int high = (int)syscall(SYS_fcntl, fd, F_DUPFD_CLOEXEC, DDH_TABLE_FD); + if (high >= 0) { + syscall(SYS_close, fd); + fd = high; + } + ddh_keep(fd); + p->magic = DDH_MAGIC; + p->pad[0] = getpid(); + // A nonce that tells this table's fd from any other (inode numbers are rewritten by the hardlink emulation) + if (syscall(SYS_getrandom, &p->pad[1], 2 * sizeof(int32_t), 0) != 2 * (long)sizeof(int32_t)) { + p->pad[1] = (int32_t)time(NULL); + p->pad[2] = (int32_t)(intptr_t)p; + } + *made_fd = fd; + *made = p; + return 1; +} + + +// Whether fd is still this table: a program may have put a file of its own at that number. +static int ddh_is_table(int fd, const struct ddh_table *t) { + int32_t head[4]; + if (fd < 0 || syscall(SYS_pread64, fd, head, sizeof(head), 0) != (long)sizeof(head)) return 0; + return head[0] == t->magic && head[1] == t->pad[0] && head[2] == t->pad[1] && head[3] == t->pad[2]; +} + +// The open fds from 3 on, ascending (as /proc lists them): how many, at most max; -1 without /proc. +static int ddh_list_fds(int *fds, int max) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return -1; + int n = 0; + char buf[4096]; + long got; + while ((got = syscall(SYS_getdents64, dir, buf, sizeof(buf))) > 0) { + for (long off = 0; off < got;) { + unsigned short reclen; + memcpy(&reclen, buf + off + 16, sizeof(reclen)); + const char *name = buf + off + 19; + off += reclen ? reclen : got; + if (name[0] < '0' || name[0] > '9') continue; + int fd = atoi(name); + if (fd >= 3 && fd != dir && n < max) fds[n++] = fd; + } + } + syscall(SYS_close, dir); + return n; +} + +#define DDH_LISTED_FDS 2048 + +// A table inherited across exec: the parent's if its owner is still our parent, else closed. +static void ddh_find_parent_table(void) { + char path[64], target[64]; + pid_t parent = (pid_t)syscall(SYS_getppid); + // The table a worker's program reports its exit to (DDH_TABLE), also for what it execs + int report = -1; + const char *spec = getenv("DDH_TABLE"); + if (spec && getenv("DDH_WORKER_PID") && atoi(getenv("DDH_WORKER_PID")) == getpid()) report = atoi(spec); + static int open_fds[DDH_LISTED_FDS]; + int count = ddh_list_fds(open_fds, DDH_LISTED_FDS); + for (int i = 0; i < count; i++) { + int fd = open_fds[i]; + if (fd == report) { + ddh_keep(fd); + continue; + } + int n = snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + if (n <= 0) continue; + long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1); + if (len <= 0) continue; + target[len] = 0; + if (strncmp(target, "/memfd:ddnatv-handoff", 21) != 0) continue; + struct ddh_table *t = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (t != MAP_FAILED && t->magic == DDH_MAGIC && t->pad[0] == parent && !g_ddh_up) { + g_ddh_up = t; + g_ddh_up_fd = fd; + syscall(SYS_fcntl, fd, F_SETFD, FD_CLOEXEC); + ddh_keep(fd); + continue; + } + if (t != MAP_FAILED) munmap(t, sizeof(struct ddh_table)); + syscall(SYS_close, fd); + } +} + +// The worker's binder fds (DDH_WORKER_PID names the worker's process). Only that process may hold +// them: a child holding a copy keeps the worker alive in the system's eyes after its program exits. +static int g_ddh_binder[8]; +static int g_ddh_nbinder; +static pid_t g_ddh_worker; + +// Both change the list only between kept_change_begin() and kept_change_end() (hook/privileged.c), +// as other threads may be reading it. A thread with a table of its own changes its own copy. +static void ddh_unkeep(int fd) { + kept_change_begin(); + int *fds = t_kept_split ? t_kept_fds : g_kept_fds; + int *count = t_kept_split ? &t_kept_count : &g_kept_fd_count; + int n = *count; + for (int i = 0; i < n; i++) { + if (fds[i] != fd) continue; + for (int j = i; j + 1 < n; j++) __atomic_store_n(&fds[j], fds[j + 1], __ATOMIC_RELAXED); + __atomic_store_n(count, n - 1, __ATOMIC_RELAXED); + break; + } + kept_change_end(); +} + +static void ddh_keep(int fd) { + kept_change_begin(); + int *fds = t_kept_split ? t_kept_fds : g_kept_fds; + int *count = t_kept_split ? &t_kept_count : &g_kept_fd_count; + int n = *count, found = 0; + for (int i = 0; i < n; i++) found |= fds[i] == fd; + if (n < DDNATV_MAX_KEPT_FDS && !found) { + int i = n; + while (i > 0 && fds[i - 1] > fd) { + __atomic_store_n(&fds[i], fds[i - 1], __ATOMIC_RELAXED); + i--; + } + __atomic_store_n(&fds[i], fd, __ATOMIC_RELAXED); + __atomic_store_n(count, n + 1, __ATOMIC_RELAXED); + } + kept_change_end(); +} + +// A dup2() or dup3() onto the parent's pidfd (ddh_parent_lives()) or its spare: the check goes on with +// the other, so that the program gets the number it asked for; if the call then fails, nothing has +// changed (ddh_parent_pidfd_settle()). Returns the number the program takes over, or -1. +static int ddh_parent_pidfd_moves(int target); +static void ddh_parent_pidfd_settle(int from, int done); +static int ddh_parent_pidfd_lock(int target); +static void ddh_parent_pidfd_unlock(int locked); + +static void ddh_drop_worker_binder(void) { + if (g_ddh_nbinder == 0 || getpid() == g_ddh_worker) return; + for (int i = 0; i < g_ddh_nbinder; i++) { + ddh_unkeep(g_ddh_binder[i]); + syscall(SYS_close, g_ddh_binder[i]); + } + g_ddh_nbinder = 0; + g_cloexec_kept_count = 0; +} + +static void ddh_find_worker_binder(void) { + const char *worker = getenv("DDH_WORKER_PID"); + if (!worker) return; + g_ddh_worker = (pid_t)atoi(worker); + char path[64], target[32]; + static int open_fds[DDH_LISTED_FDS]; + int count = ddh_list_fds(open_fds, DDH_LISTED_FDS); + for (int i = 0; i < count && g_ddh_nbinder < 8; i++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", open_fds[i]); + long len = syscall(SYS_readlinkat, AT_FDCWD, path, target, sizeof(target) - 1); + if (len <= 0) continue; + target[len] = 0; + if (ddh_is_binder(target)) g_ddh_binder[g_ddh_nbinder++] = open_fds[i]; + } + if (getpid() == g_ddh_worker) { + // The program closing every fd it did not open (gamescope does) would end the worker. + for (int i = 0; i < g_ddh_nbinder; i++) { + ddh_keep(g_ddh_binder[i]); + g_cloexec_kept_fds[i] = g_ddh_binder[i]; + } + g_cloexec_kept_count = g_ddh_nbinder; + } + ddh_drop_worker_binder(); +} + +// In the program a worker runs for a handed-off child (DDH_TABLE "FD:SLOT:PARENT:CHILD"): its exit +// status goes into the parent's table here; the app reports it from Android's exit record only when +// the program never got to exit() or _exit() (a signal). +static struct ddh_table *g_ddh_report; +static int g_ddh_report_slot = -1; +static pid_t g_ddh_report_parent; +static pid_t g_ddh_report_child; +// The forked parent as a pidfd, opened at the start: readable once it has exited, reaped or not. +static int g_ddh_parent_pidfd = -1; + +// A second copy of it, made with it: a dup2() onto the pidfd's number moves the check to the spare, +// and no descriptor is ever made later, when another thread's close() or close_range() could be +// closing the number it would get. Both are kept (close() and close_range() leave them alone) from +// the start, before the program runs. Without a spare (a second dup2() onto it), the pidfd is given +// up and /proc answers. +static int g_ddh_parent_spare = -1; +// What the dup2() under way takes over: 1 the pidfd (the spare is the pidfd meanwhile), 2 the spare. +// Only changed with g_ddh_pidfd_lock held. +static int g_ddh_pidfd_move; + +static int ddh_parent_pidfd_moves(int target) { + // In a table of its own, a kept number the program takes over is let go of in this thread's copy + // only: the other threads' pidfd stays where it is. + if (t_kept_split) return target >= 0 && is_kept_fd(target) ? target : -1; + int fd = __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE); + int spare = __atomic_load_n(&g_ddh_parent_spare, __ATOMIC_ACQUIRE); + if (target < 0 || (target != fd && target != spare)) return -1; + if (target == fd) { + __atomic_store_n(&g_ddh_parent_spare, -1, __ATOMIC_RELEASE); + __atomic_store_n(&g_ddh_parent_pidfd, spare, __ATOMIC_RELEASE); + g_ddh_pidfd_move = 1; + } else { + __atomic_store_n(&g_ddh_parent_spare, -1, __ATOMIC_RELEASE); + g_ddh_pidfd_move = 2; + } + return target; +} + +static void ddh_parent_pidfd_settle(int from, int done) { + if (from < 0) return; + if (t_kept_split) { + if (done) ddh_unkeep(from); + return; + } + int move = g_ddh_pidfd_move; + g_ddh_pidfd_move = 0; + // the program's file now: its close() closes it + if (done) { + ddh_unkeep(from); + return; + } + // the dup failed and left the number as it was, still the pidfd (or the spare) and still kept + if (move == 1) { + int spare = __atomic_exchange_n(&g_ddh_parent_pidfd, from, __ATOMIC_ACQ_REL); + __atomic_store_n(&g_ddh_parent_spare, spare, __ATOMIC_RELEASE); + } else if (move == 2) { + __atomic_store_n(&g_ddh_parent_spare, from, __ATOMIC_RELEASE); + } +} + +// Held by every dup2()/dup3() of a process that has had the pidfd, from the move through the dup to +// the settling, and by fork() around the fork: no relocation can interleave with another. Every +// signal is blocked while it is held, so a handler that calls dup2() never waits for it on its own +// thread. ddh_parent_lives() only tries it. Released in a forked child. +static pthread_mutex_t g_ddh_pidfd_lock = PTHREAD_MUTEX_INITIALIZER; +static __thread uint64_t t_ddh_pidfd_mask; +static int g_ddh_had_pidfd; + +static void ddh_pidfd_hold(void) { + uint64_t all = ~0ull; + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&t_ddh_pidfd_mask, 8, 0, 0); + pthread_mutex_lock(&g_ddh_pidfd_lock); +} + +static void ddh_pidfd_release(void) { + pthread_mutex_unlock(&g_ddh_pidfd_lock); + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&t_ddh_pidfd_mask, 0, 8, 0, 0); +} + +static int ddh_parent_pidfd_lock(int target) { + (void)target; + if (!__atomic_load_n(&g_ddh_had_pidfd, __ATOMIC_ACQUIRE)) return 0; + ddh_pidfd_hold(); + return 1; +} + +static void ddh_parent_pidfd_unlock(int locked) { + if (locked) ddh_pidfd_release(); +} + +// The line of /proc/PID/cgroup that names the app's per-process cgroup ("...:/uid_U/pid_P"). +static int ddh_cgroup_line(pid_t pid, const char *want, char *out, size_t size) { + char path[48], buf[512]; + snprintf(path, sizeof(path), "/proc/%d/cgroup", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, buf, sizeof(buf) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + buf[n] = 0; + if (want) return strstr(buf, want) != NULL; + char mine[32]; + snprintf(mine, sizeof(mine), "/pid_%d\n", (int)pid); + char *at = strstr(buf, mine); + if (!at) return 0; + char *start = at; + while (start > buf && start[-1] != '\n') start--; + size_t len = (size_t)(at - start) + strlen(mine); + if (len + 1 > size) return 0; + memcpy(out, start, len); + out[len] = 0; + return 1; +} + +// A live process (not a zombie) in the cgroup that line names. +static int ddh_cgroup_member(pid_t pid, const char *line) { + char path[48], stat[256]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, stat, sizeof(stat) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + stat[n] = 0; + char *paren = strrchr(stat, ')'); + if (!paren || paren[1] != ' ' || paren[2] == 'Z' || paren[2] == 'X') return 0; + return ddh_cgroup_line(pid, line, NULL, 0); +} + +static pid_t ddh_find_cgroup_member(const char *line, pid_t self) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return 0; + char entries[8192]; + pid_t found = 0; + long n; + while (!found && (n = syscall(SYS_getdents64, dir, entries, sizeof(entries))) > 0) { + for (long off = 0; off < n && !found;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + const char *name = entries + off + 19; + off += reclen ? reclen : n; + if (name[0] < '1' || name[0] > '9') continue; + pid_t pid = (pid_t)atoi(name); + if (pid != self && ddh_cgroup_member(pid, line)) found = pid; + } + } + syscall(SYS_close, dir); + return found; +} + +static void ddh_linger_note(const char *what, long value) { + const char *debug = getenv("DD_HANDOFF_DEBUG"); + if (!debug) return; + char text[160]; + int len = snprintf(text, sizeof(text), "ddnatv handoff: %d linger: %s %ld\n", (int)getpid(), what, value); + if (len > 0) ddh_log(debug, text, (size_t)len); +} + +// Android kills every process in a worker's cgroup when the worker's own process ends: a program's +// daemon (wineserver forks it and exits) or a job it left running would die with it. So the program's +// process stays, as if it had exited (no fds but the worker's binder, no signals), until they are gone. +static void ddh_linger(int flush) { + char line[160]; + pid_t self = getpid(); + // Not with other threads, which would go on running the program's code meanwhile. + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/task", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return; + char entries[512]; + int threads = 0; + long n = syscall(SYS_getdents64, dir, entries, sizeof(entries)); + for (long off = 0; off < n;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + threads += entries[off + 19] >= '1' && entries[off + 19] <= '9'; + off += reclen ? reclen : n; + } + syscall(SYS_close, dir); + if (threads != 1) { + ddh_linger_note("threads", threads); + return; + } + if (!ddh_cgroup_line(self, NULL, line, sizeof(line))) { + ddh_linger_note("no cgroup line", 0); + return; + } + pid_t member = ddh_find_cgroup_member(line, self); + ddh_linger_note("cgroup member", member); + if (member <= 0) return; + if (flush) fflush(NULL); + sigset_t all; + sigfillset(&all); + sigprocmask(SIG_SETMASK, &all, NULL); + close_range(0, ~0U, 0); + while (member > 0) { + while (syscall(SYS_wait4, -1, NULL, WNOHANG, NULL) > 0) { + } + struct timespec second = {1, 0}; + nanosleep(&second, NULL); + if (!ddh_cgroup_member(member, line)) member = ddh_find_cgroup_member(line, self); + } +} + +static void ddh_register_group(void); +static void ddh_unregister_group(void); +static pid_t ddh_logical_pgrp(void); +static pid_t ddh_logical_group(pid_t real); +static long ddh_start_time(pid_t pid); +static int ddh_parent_lives(pid_t parent, long child_start); + +// From exit() (on_exit, arg 1) or _exit() (arg NULL) in a worker's own process. +// Only a handed-off child lingers: the app waits for the death of the programs it starts itself +// (the session's root) to tear everything down. +static void ddh_report_exit(int status, void *from_exit) { + if (!g_ddh_report || getpid() != g_ddh_worker) return; + // exit() flushes stdio after its on_exit() handlers: before the parent can see the exit here + if (from_exit) fflush(NULL); + struct ddh_entry *e = &g_ddh_report->e[g_ddh_report_slot]; + // Still this program's entry: the parent frees it when the forked child dies before handing off + // (and a later child may have it by now). + // From the state read (the forked child may still move it from CLAIMED to HANDED): a parent + // that freed the entry meanwhile keeps it freed. + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + for (int unknown = 0;;) { + // TAKEN: the parent's check of a gone worker holds the entry (ddh_check_gone()) and gives it + // back as it was when it is not the child it looked at. Wait that out, however long the parent + // takes, while there is a parent to give it back. When /proc cannot say (out of fds), kill() + // can, without a new fd, except for a parent that has exited and is not reaped: 5 s then. + int lives = st == DDH_TAKEN ? ddh_parent_lives(e->parent, (long)e->child_start) : 0; + if (lives < 0) { + int saved = errno; + lives = (syscall(SYS_kill, e->parent, 0) == 0 || errno != ESRCH) && unknown++ < 5000; + errno = saved; + } + if (lives) { + struct timespec ts = {0, 1000 * 1000}; + syscall(SYS_nanosleep, &ts, NULL); + st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + continue; + } + if ((st != DDH_HANDED && st != DDH_CLAIMED) || e->parent != g_ddh_report_parent || + (g_ddh_report_child > 0 && e->child != g_ddh_report_child)) + break; + e->status = (status & 0xff) << 8; + if (__atomic_compare_exchange_n(&e->state, &st, DDH_EXITED, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { + if (g_ddh_report_parent > 0) syscall(SYS_kill, g_ddh_report_parent, SIGCHLD); + break; + } + } + ddh_linger(from_exit != NULL); + ddh_unregister_group(); +} + +// A program that leaves with _exit() skips on_exit(): a daemon's first process does, once it has +// forked the daemon (wineserver), and its parent waits for that status. +__attribute__((noreturn)) static void ddh_real_exit(const char *name, int status) { + void (*real)(int) = (void (*)(int))dlsym(RTLD_NEXT, name); + if (real) real(status); + syscall(SYS_exit_group, status); + __builtin_unreachable(); +} + +void _exit(int status) { + ddh_report_exit(status, NULL); + ddh_real_exit("_exit", status); +} + +void _Exit(int status) { + ddh_report_exit(status, NULL); + ddh_real_exit("_Exit", status); +} + +static void ddh_setup_report(void) { + const char *spec = getenv("DDH_TABLE"); + if (!spec || g_ddh_worker != getpid()) return; + int fd = -1, slot = -1, parent = 0, child = 0; + if (sscanf(spec, "%d:%d:%d:%d", &fd, &slot, &parent, &child) < 3 || slot < 0 || slot >= DDH_SLOTS) return; + struct ddh_table *t = mmap(NULL, sizeof(struct ddh_table), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (t == MAP_FAILED || t->magic != DDH_MAGIC) return; + g_ddh_report = t; + g_ddh_report_slot = slot; + g_ddh_report_parent = parent; + g_ddh_report_child = child; + // the parent itself, not a later process given its pid (one that started after its child) + int pidfd = (int)call_orig_syscall(__NR_pidfd_open, (unsigned long)parent, 0, 0, 0, 0, 0); + long started = ddh_start_time(parent), child_start = t->e[slot].child_start; + if (pidfd >= 0 && started >= 0 && child_start >= 0 && started > child_start) { + syscall(SYS_close, pidfd); + pidfd = -1; + } + if (pidfd >= 0) { + // out of the way of the numbers programs pick for themselves + int high = (int)call_orig_syscall(SYS_fcntl, (unsigned long)pidfd, F_DUPFD_CLOEXEC, 900, 0, 0, 0); + if (high >= 0) { + syscall(SYS_close, pidfd); + pidfd = high; + } + ddh_keep(pidfd); + if (!is_kept_fd(pidfd)) { + // no room in the kept list: the program could close it, and /proc answers + syscall(SYS_close, pidfd); + pidfd = -1; + } + } + if (pidfd >= 0) { + g_ddh_parent_pidfd = pidfd; + int spare = (int)call_orig_syscall(SYS_fcntl, (unsigned long)pidfd, F_DUPFD_CLOEXEC, 900, 0, 0, 0); + if (spare >= 0) ddh_keep(spare); + if (spare >= 0 && is_kept_fd(spare)) g_ddh_parent_spare = spare; + else if (spare >= 0) syscall(SYS_close, spare); + __atomic_store_n(&g_ddh_had_pidfd, 1, __ATOMIC_RELEASE); + pthread_atfork(ddh_pidfd_hold, ddh_pidfd_release, ddh_pidfd_release); + } + on_exit(ddh_report_exit, (void *)1); + ddh_register_group(); +} + +// In a program a worker started: the state its forked parent had, sent along with the exec. Not in +// the app's shell that execs it (DDH_WRAPPER): bash changes its signal mask (it unblocks SIGCHLD), +// and its exec keeps bash's. +static void ddh_apply_inherited(void) { + if (getenv("DDH_WRAPPER")) return; + const char *ign = getenv("DDH_SIGIGN"); + if (ign) { + unsigned long mask = strtoul(ign, NULL, 10); + for (int sig = 1; sig < 32; sig++) { + if (sig == SIGKILL || sig == SIGSTOP) continue; + struct sigaction sa; + if (sigaction(sig, NULL, &sa) != 0) continue; + int want = (mask >> (sig - 1)) & 1; + if (want && sa.sa_handler != SIG_IGN) signal(sig, SIG_IGN); + else if (!want && sa.sa_handler == SIG_IGN) signal(sig, SIG_DFL); + } + unsetenv("DDH_SIGIGN"); + } + const char *nofile = getenv("DDH_NOFILE"); + if (nofile) { + struct rlimit lim; + // "SOFT:HARD": both as the forked child had them, the hard limit too, which a program can + // only lower (no higher than the worker's) + if (getrlimit(RLIMIT_NOFILE, &lim) == 0) { + char *end = NULL; + rlim_t want = (rlim_t)strtoull(nofile, &end, 10); + if (end && *end == ':') { + rlim_t hard = (rlim_t)strtoull(end + 1, NULL, 10); + if (hard < lim.rlim_max) lim.rlim_max = hard; + } + lim.rlim_cur = want < lim.rlim_max ? want : lim.rlim_max; + setrlimit(RLIMIT_NOFILE, &lim); + } + unsetenv("DDH_NOFILE"); + } + const char *mask = getenv("DDH_UMASK"); + if (mask) { + umask((mode_t)strtoul(mask, NULL, 10)); + unsetenv("DDH_UMASK"); + } + // The blocked signals: the forked parent's, or none for a program the app started. A worker + // execs from Android's main thread, which blocks SIGQUIT, SIGUSR1 and SIGPIPE. + const char *blocked = getenv("DDH_SIGMASK"); + if (blocked) { + unsigned long long bits = strtoull(blocked, NULL, 10); + sigset_t set; + sigemptyset(&set); + for (int sig = 1; sig <= 64 && sig < NSIG; sig++) { + if ((bits >> (sig - 1)) & 1) sigaddset(&set, sig); + } + sigprocmask(SIG_SETMASK, &set, NULL); + unsetenv("DDH_SIGMASK"); + } +} + +static void ddh_open_parents(void); +static void ddh_record_own_parent(void); + +__attribute__((constructor)) static void ddh_init(void) { + ddh_apply_inherited(); + ddh_find_worker_binder(); + ddh_setup_report(); + ddh_find_parent_table(); + // tests only: as when the table could not be made here, and the first fork makes it + if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare(); + ddh_open_parents(); + ddh_record_own_parent(); + ddnatv_manage_sigchld(); +} + +static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) { + for (int i = 1; argv && argv[i]; i++) { + if (strncmp(argv[i], prefix, len) == 0) return 1; + } + return 0; +} + +// An entry is a basename, or "name+prefix" for that program only when an argument starts with prefix. +static int ddh_listed(const char *list, const char *name, char *const argv[]) { + if (!list || !name || !*name) return 0; + if (strcmp(list, "*") == 0) return 1; + size_t n = strlen(name); + for (const char *p = list; *p;) { + const char *end = strchr(p, ':'); + size_t len = end ? (size_t)(end - p) : strlen(p); + const char *plus = memchr(p, '+', len); + size_t base = plus ? (size_t)(plus - p) : len; + if (base == n && strncmp(p, name, n) == 0 && + (!plus || ddh_has_arg(argv, plus + 1, len - base - 1))) return 1; + if (!end) break; + p = end + 1; + } + return 0; +} + +static const char *ddh_base(const char *path) { + const char *s = path ? strrchr(path, '/') : NULL; + return s ? s + 1 : path; +} + +struct ddh_buf { + char *p; + size_t len, cap; +}; + +static void ddh_put(struct ddh_buf *b, const char *s, size_t n) { + if (b->p && b->len < b->cap) memcpy(b->p + b->len, s, n < b->cap - b->len ? n : b->cap - b->len); + b->len += n; +} + +static void ddh_puts(struct ddh_buf *b, const char *s) { ddh_put(b, s, strlen(s)); } + +static void ddh_putint(struct ddh_buf *b, long v) { + char tmp[24]; + int i = sizeof(tmp); + int neg = v < 0; + unsigned long u = neg ? 0UL - (unsigned long)v : (unsigned long)v; // no overflow for LONG_MIN + do { + tmp[--i] = (char)('0' + u % 10); + u /= 10; + } while (u); + if (neg) tmp[--i] = '-'; + ddh_put(b, tmp + i, sizeof(tmp) - i); +} + +static void ddh_putstr(struct ddh_buf *b, const char *s) { + static const char hex[] = "0123456789abcdef"; + ddh_put(b, "\"", 1); + for (const unsigned char *c = (const unsigned char *)s; *c; c++) { + if (*c == '"' || *c == '\\') { + char esc[2] = {'\\', (char)*c}; + ddh_put(b, esc, 2); + } else if (*c < 0x20) { + char esc[6] = {'\\', 'u', '0', '0', hex[*c >> 4], hex[*c & 15]}; + ddh_put(b, esc, 6); + } else { + ddh_put(b, (const char *)c, 1); + } + } + ddh_put(b, "\"", 1); +} + +static void ddh_putarray(struct ddh_buf *b, char *const v[]) { + ddh_put(b, "[", 1); + for (int i = 0; v && v[i]; i++) { + if (i) ddh_put(b, ",", 1); + ddh_putstr(b, v[i]); + } + ddh_put(b, "]", 1); +} + +#define DDH_MAX_FDS 240 +#define DDH_FDS_PER_CHUNK 60 + +// The fds the program would have inherited: every open fd without FD_CLOEXEC, but skip (the table). +static int ddh_open_fds(int *fds, int max, int skip) { + int n = 0; + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return -1; + char buf[4096]; + for (;;) { + long got = syscall(SYS_getdents64, dir, buf, sizeof(buf)); + if (got <= 0) break; + for (long off = 0; off < got;) { + struct { + uint64_t ino; + int64_t off; + unsigned short reclen; + unsigned char type; + char name[]; + } *d = (void *)(buf + off); + off += d->reclen; + if (d->name[0] < '0' || d->name[0] > '9') continue; + int fd = 0; + for (const char *c = d->name; *c; c++) fd = fd * 10 + (*c - '0'); + if (fd == dir || fd == skip) continue; + int flags = (int)syscall(SYS_fcntl, fd, F_GETFD); + if (flags < 0 || (flags & FD_CLOEXEC)) continue; + // A worker's binder fd, inherited from the worker this process runs in: it keeps that + // worker alive and must not take the place of the new worker's own. + char link[64], target[32]; + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); + long tlen = syscall(SYS_readlinkat, AT_FDCWD, link, target, sizeof(target) - 1); + if (tlen > 0) { + target[tlen] = 0; + if (ddh_is_binder(target)) continue; + } + if (n == max) { + syscall(SYS_close, dir); + return -1; + } + fds[n++] = fd; + } + } + syscall(SYS_close, dir); + return n; +} + +// The interpreter a script names on its "#!" line ("/usr/bin/env NAME" gives NAME), into buf. +// In a forked child: system calls only, as the hook's own open() and close() take locks another +// thread of the parent may have held at fork(). +static const char *ddh_interpreter(const char *path, char *buf, size_t size) { + char real[PATH_MAX]; + // non-blocking, and only a regular file: the path could name a FIFO + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(path, real, sizeof(real)), + O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); + if (fd < 0) return NULL; + struct stat st; + if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISREG(st.st_mode)) { + syscall(SYS_close, fd); + return NULL; + } + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)buf, size - 1, 0, 0, 0); + syscall(SYS_close, fd); + if (n < 3 || buf[0] != '#' || buf[1] != '!') return NULL; + buf[n] = 0; + char *p = buf + 2; + while (*p == ' ' || *p == '\t') p++; + char *end = p; + while (*end && *end != ' ' && *end != '\t' && *end != '\n') end++; + char *word = NULL; + if (*end == ' ' || *end == '\t') { + word = end + 1; + while (*word == ' ' || *word == '\t') word++; + } + *end = 0; + const char *name = ddh_base(p); + if (strcmp(name, "env") == 0 && word && *word) { + end = word; + while (*end && *end != ' ' && *end != '\t' && *end != '\n') end++; + *end = 0; + return word; + } + return name; +} + +// An aarch64 ELF image the kernel would load, whose interpreter, if it names one, is in the guest's +// root; fd is the image. +static int ddh_elf_startable(int fd) { + Elf64_Ehdr eh; + if (syscall(SYS_pread64, fd, &eh, sizeof(eh), 0) != (long)sizeof(eh) || eh.e_ident[EI_CLASS] != ELFCLASS64 || + eh.e_machine != EM_AARCH64 || (eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || + eh.e_phentsize != sizeof(Elf64_Phdr) || eh.e_phnum == 0 || eh.e_phnum > 64) + return 0; + for (int i = 0; i < eh.e_phnum; i++) { + Elf64_Phdr ph; + if (syscall(SYS_pread64, fd, &ph, sizeof(ph), (long)(eh.e_phoff + (Elf64_Off)i * sizeof(ph))) != (long)sizeof(ph)) + return 0; + if (ph.p_type != PT_INTERP) continue; + char interp[PATH_MAX], real[PATH_MAX]; + if (ph.p_filesz == 0 || ph.p_filesz >= sizeof(interp) || + syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz) + return 0; + interp[ph.p_filesz] = 0; + return call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(interp, real, sizeof(real)), + R_OK, 0, 0, 0) == 0; + } + return 1; +} + +// Whether an exec of path would get as far as the program: an ELF image the kernel would load, or a +// script whose "#!" interpreter is there to run. Anything else fails in the exec, which must happen +// here then, so that the caller (posix_spawn() above all) gets its error rather than a worker's exit +// status. +static int ddh_startable(const char *path) { + char real[PATH_MAX], head[256]; + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(path, real, sizeof(real)), + O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); + if (fd < 0) return 0; + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)head, sizeof(head) - 1, 0, 0, 0); + int elf = n >= 4 && memcmp(head, "\177ELF", 4) == 0 && ddh_elf_startable(fd); + syscall(SYS_close, fd); + if (n >= 4 && memcmp(head, "\177ELF", 4) == 0) return elf; + if (n < 3 || head[0] != '#' || head[1] != '!') return 0; + head[n] = 0; + char *p = head + 2; + while (*p == ' ' || *p == '\t') p++; + char *end = p; + while (*end && *end != ' ' && *end != '\t' && *end != '\n' && *end != '\r') end++; + *end = 0; + if (*p != '/') return 0; + return call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)rewrite_path(p, real, sizeof(real)), X_OK, 0, 0, 0) == 0; +} + +// Whether s is valid UTF-8: the app reads the request as UTF-8, and any other byte would reach the +// program changed (a file name in Latin-1, say), where a local exec passes it on as it is. +static int ddh_utf8(const char *s) { + const unsigned char *p = (const unsigned char *)s; + while (*p) { + int n = *p < 0x80 ? 0 : (*p & 0xe0) == 0xc0 ? 1 : (*p & 0xf0) == 0xe0 ? 2 : (*p & 0xf8) == 0xf0 ? 3 : -1; + if (n < 0 || (n == 1 && *p < 0xc2) || (n == 3 && *p > 0xf4)) return 0; + unsigned int cp = n == 0 ? *p : *p & (0x3f >> n); + for (int i = 1; i <= n; i++) { + if ((p[i] & 0xc0) != 0x80) return 0; + cp = (cp << 6) | (p[i] & 0x3f); + } + if ((n == 2 && (cp < 0x800 || (cp >= 0xd800 && cp <= 0xdfff))) || (n == 3 && (cp < 0x10000 || cp > 0x10ffff))) return 0; + p += n + 1; + } + return 1; +} + +static int ddh_all_utf8(char *const v[]) { + for (int i = 0; v && v[i]; i++) { + if (!ddh_utf8(v[i])) return 0; + } + return 1; +} + +static int ddh_program_listed(const char *list, const char *filename, char *const argv[]) { + char shebang[256]; + const char *interp; + // "python3 SCRIPT" and "sh SCRIPT" are matched by the script's name too (and only an + // interpreter's: "pidof wineserver" is not wineserver) + const char *prog = ddh_base(filename); + int interpreter = strcmp(prog, "sh") == 0 || strcmp(prog, "bash") == 0 || strcmp(prog, "dash") == 0 || + strncmp(prog, "python", 6) == 0 || strncmp(prog, "perl", 4) == 0; + const char *script = interpreter && argv && argv[0] && argv[1] && argv[1][0] != '-' ? ddh_base(argv[1]) : NULL; + return ddh_listed(list, ddh_base(filename), argv) || (argv && ddh_listed(list, ddh_base(argv[0]), argv)) || + (script && ddh_listed(list, script, argv)) || + ((interp = ddh_interpreter(filename, shebang, sizeof(shebang))) && ddh_listed(list, interp, argv)); +} + +// Whether a posix_spawn() of this program should be handed off: glibc's spawn child makes the exec +// system call itself, past ddh_try(), so such a spawn is started with fork() and execve() instead. +// The hook's exec ends these at once and its posix_spawn() runs them (exec.c): never handed off. +static int ddh_exec_stub(const char *path) { + static const char *const exec_stubs[] = {"mandb", "mandb.real", "update-mime-database", "update-desktop-database", + "install-info", "install-sgmlcatalog"}; + for (size_t i = 0; path && i < sizeof(exec_stubs) / sizeof(exec_stubs[0]); i++) { + if (strcmp(ddh_base(path), exec_stubs[i]) == 0) return 1; + } + return 0; +} + +// Android's limit is 32 counted processes for the whole app. Past this many, a shell's (or make's, +// or xargs') child goes to a worker even when it is not listed: those wait for their children with +// wait(), which the hook answers. Other parents may track a child by pidfd or /proc, which would see +// the forked child exit at once. +#define DDH_PRESSURE 20 + +static int ddh_waiter(pid_t pid); +static int ddh_counted(void); +static int ddh_pressure_keeps(const char *filename, char *const argv[]); + +// DD_HANDOFF_PRESSURE sets another count (tests) +static int ddh_pressure(char *const envp[]) { + const char *v = ddh_env(envp, "DD_HANDOFF_PRESSURE"); + return v && *v ? atoi(v) : DDH_PRESSURE; +} + +static int ddh_spawn_wanted(const char *path, char *const argv[], char *const envp[]) { + if (!path || ddh_exec_stub(path)) return 0; + const char *list = ddh_env(envp, "DD_HANDOFF"); + if (!ddh_env(envp, "DD_SPAWN") || !list) return 0; + // as ddh_pressed() would in the child (GNU make spawns its recipes' shells) + return ddh_program_listed(list, path, argv) || (!ddh_pressure_keeps(path, argv) && ddh_waiter(getpid()) && ddh_counted() >= ddh_pressure(envp)); +} + +static long ddh_read_proc(const char *path, char *buf, size_t size) { + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + long n = syscall(SYS_read, fd, buf, size - 1); + syscall(SYS_close, fd); + if (n < 0) return -1; + buf[n] = 0; + return n; +} + +// How many of the app's processes Android counts against its limit (PhantomProcessList): those in an +// app process's cgroup, uid_U/pid_P, other than P. The guest sees only this uid's processes, which +// are the ones it counts. Without a usable /proc, -1. +static int ddh_counted(void) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return -1; + int counted = 0; + char buf[4096]; + for (;;) { + long n = syscall(SYS_getdents64, dir, buf, sizeof(buf)); + if (n <= 0) break; + for (long off = 0; off < n;) { + struct ddh_dirent { + uint64_t ino; + int64_t off; + unsigned short reclen; + unsigned char type; + char name[]; + } *d = (struct ddh_dirent *)(buf + off); + off += d->reclen; + if (d->name[0] < '1' || d->name[0] > '9') continue; + char path[48], cgroup[512]; + snprintf(path, sizeof(path), "/proc/%s/cgroup", d->name); + if (ddh_read_proc(path, cgroup, sizeof(cgroup)) <= 0) continue; + const char *v2 = strstr(cgroup, "0::/uid_"); + const char *app = v2 ? strstr(v2, "/pid_") : NULL; + if (!app) continue; + app += 5; + size_t len = strspn(app, "0123456789"); + if (len > 0 && (len != strlen(d->name) || strncmp(app, d->name, len) != 0)) counted++; + } + } + syscall(SYS_close, dir); + return counted; +} + +static int ddh_waiter(pid_t pid) { + char path[48], name[32]; + snprintf(path, sizeof(path), "/proc/%d/comm", (int)pid); + if (ddh_read_proc(path, name, sizeof(name)) <= 0) return 0; + name[strcspn(name, "\n")] = 0; + static const char *const waiters[] = {"bash", "sh", "dash", "zsh", "ksh", "mksh", "fish", "make", "gmake", "xargs"}; + for (size_t i = 0; i < sizeof(waiters) / sizeof(waiters[0]); i++) { + if (strcmp(name, waiters[i]) == 0) return 1; + } + return 0; +} + +// Never handed off for want of room: the Steam client and its launch chain, which the client tracks +// as its own processes (see the docs' "Not handed off" and "Tried and dropped"), however started (the +// arm64 client directly or through env, the x86-64 one through droiddeck-steam-x64). +// +// Nor the quick tools a shell runs for their output: the session's scripts run dozens at a game's start +// (droiddeck-seed-redists alone about 17 within a second), and each would be an app process of its own, +// a zygote fork and a bind, for a few milliseconds of work while the game starts. Counted for those +// milliseconds instead. Only tools that end on their own: not tail (-f), tee, sleep, timeout or env. +static int ddh_pressure_keeps(const char *filename, char *const argv[]) { + static const char *const kept[] = {"steam", "steam.sh", "steamwebhelper", "droiddeck-steam-x64", "reaper", + "steam-launch-wrapper", "pw-audio-namespace", "gamescope", "gamescopereaper"}; + static const char *const quick[] = {"awk", "basename", "cat", "cut", "date", "dirname", "egrep", "expr", "fgrep", + "gawk", "grep", "head", "id", "jq", "ls", "mawk", "mkdir", "mktemp", "pgrep", + "pidof", "printf", "ps", "readlink", "realpath", "rm", "sed", "seq", "sort", + "stat", "touch", "tr", "uname", "uniq", "wc", "xprop"}; + if (filename) { + for (size_t k = 0; k < sizeof(quick) / sizeof(quick[0]); k++) { + if (strcmp(ddh_base(filename), quick[k]) == 0) return 1; + } + } + for (int i = -1; i < 0 || (argv && argv[i]); i++) { + const char *s = i < 0 ? filename : argv[i]; + if (!s) continue; + if (strstr(s, "/Steam/") || strstr(s, "/.steam/")) return 1; + for (size_t k = 0; k < sizeof(kept) / sizeof(kept[0]); k++) { + if (strcmp(ddh_base(s), kept[k]) == 0) return 1; + } + } + return 0; +} + +// Whether this child is a job a shell with job control runs: a child of a shell, in a process group +// other than the shell's. The shell stops, continues and waits for it with WUNTRACED, and a +// handed-off program's stops and continues never reach a wait (they happen to its worker, which is +// not the shell's child), so such a job is never handed off, listed or not. +static int ddh_job_control_job(void) { + pid_t parent = (pid_t)syscall(SYS_getppid); + return ddh_waiter(parent) && (pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent); +} + +// Whether this is a program a desktop launcher starts for the user (DD_HANDOFF_LAUNCHERS names the +// launchers: Plasma's shell, KRunner, Dolphin): a plain fork and exec, still in the launcher's process +// group and session, with no controlling terminal. Those launchers are Qt programs, which wait with +// waitpid() once they have no pidfds (privileged.c), so the program's exit reaches them. A child the +// launcher set up as a terminal's (a session and a terminal of its own) stays its own child. +static int ddh_launched(const char *filename, char *const argv[], char *const envp[]) { + const char *list = ddh_env(envp, "DD_HANDOFF_LAUNCHERS"); + if (!list || !*list || ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv)) return 0; + pid_t parent = (pid_t)syscall(SYS_getppid); + char path[48], name[32]; + snprintf(path, sizeof(path), "/proc/%d/comm", (int)parent); + if (ddh_read_proc(path, name, sizeof(name)) <= 0) return 0; + name[strcspn(name, "\n")] = 0; + if (!ddh_listed(list, name, NULL)) return 0; + if ((pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent) || + (pid_t)syscall(SYS_getsid, 0) != (pid_t)syscall(SYS_getsid, parent)) + return 0; + // /dev/tty opens only for a process with a controlling terminal + int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty", + O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0); + if (tty >= 0) syscall(SYS_close, tty); + return tty < 0; +} + +static int ddh_pressed(const char *filename, char *const argv[], char *const envp[]) { + if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0; + // Not a job in the foreground of its controlling terminal: a handed-off program has none (the + // worker's setsid()), so /dev/tty, ^C and job control would miss it, whatever its standard fds + // are ("cmd | less", "less < file", output redirected). A job started with & from a shell without + // job control runs in the foreground group reading /dev/null: that one goes. + pid_t fg = 0; + int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty", + O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0); + int foreground = tty >= 0 && syscall(SYS_ioctl, tty, TIOCGPGRP, &fg) == 0 && fg == (pid_t)syscall(SYS_getpgid, 0); + if (tty >= 0) syscall(SYS_close, tty); + if (foreground) { + struct stat st; + if (call_orig_syscall(SYS_fstat, 0, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISCHR(st.st_mode) || + st.st_rdev != makedev(1, 3)) + return 0; + } + return ddh_counted() >= ddh_pressure(envp); +} + +// In a forked child at execve(): hands the program to a worker and exits, or returns to exec it here. +static void ddh_debug(char *const envp[], const char *what, const char *filename) { + const char *debug = ddh_env(envp, "DD_HANDOFF_DEBUG"); + if (!debug) return; + char line[512]; + struct ddh_buf b = {line, 0, sizeof(line) - 1}; + ddh_puts(&b, "ddnatv handoff: "); + ddh_putint(&b, getpid()); + ddh_puts(&b, " (parent "); + ddh_putint(&b, (long)syscall(SYS_getppid)); + ddh_puts(&b, ", session "); + ddh_putint(&b, (long)syscall(SYS_getsid, 0)); + ddh_puts(&b, ") "); + ddh_puts(&b, what); + ddh_puts(&b, " "); + ddh_puts(&b, filename ? filename : "?"); + ddh_puts(&b, "\n"); + if (b.len > b.cap) b.len = b.cap; + ddh_log(debug, line, b.len); +} + +// match_file and match_argv are what DD_HANDOFF is matched against; the request carries filename and +// argv. They differ where the exec itself is a start through the system linker (the bionic runtime: +// "/system/bin/linker64 PROGRAM ARGS", tools/bionic-runtime/handoff.c), which is listed by PROGRAM. +static void ddh_try_as(const char *filename, char *const argv[], char *const envp[], const char *match_file, + char *const match_argv[]) { + struct ddh_table *table; + int table_fd; + // one look: the fields are read only once the table is seen published + struct ddh_table *own = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + pid_t own_owner = own ? g_ddh_owner : 0; + if (own && getpid() != own_owner) { + table = own; + table_fd = g_ddh_fd; + } else if (g_ddh_up && (pid_t)syscall(SYS_getppid) == g_ddh_up->pad[0]) { + table = g_ddh_up; + table_fd = g_ddh_up_fd; + } else { + table = NULL; + table_fd = -1; + } + // After a split (here or in the thread that forked this process), the table's number is this + // table's only while it is still kept here: one made later by another thread is in no copy. + if (table_fd >= 0 && (t_kept_split || g_kept_split) && !is_kept_fd(table_fd)) table_fd = -1; + if (table_fd < 0) { + if (ddh_env(envp, "DD_HANDOFF_DEBUG")) { + char why[160]; + snprintf(why, sizeof(why), "not a child its parent can track (table %d owner %d up %d up-owner %d ppid %d):", + own != NULL, (int)own_owner, g_ddh_up != NULL, g_ddh_up ? g_ddh_up->pad[0] : 0, (int)(pid_t)syscall(SYS_getppid)); + ddh_debug(envp, why, filename); + } + return; + } + const char *sock = ddh_env(envp, "DD_SPAWN"); + const char *list = ddh_env(envp, "DD_HANDOFF"); + if (!sock || !list) return; + if (!ddh_forks(0)) { + ddh_debug(envp, "no fork records:", filename); + return; + } + if (access(filename, X_OK) != 0) { + ddh_debug(envp, "not executable here:", filename); + return; + } + if (!ddh_is_table(table_fd, table)) { + ddh_debug(envp, "table fd lost:", filename); + return; + } + // Whatever this exec becomes can still hand off its own exec (a wrapper, a script). + syscall(SYS_fcntl, table_fd, F_SETFD, 0); + if (ddh_job_control_job()) { + ddh_debug(envp, "a job-control job:", filename); + return; + } + if (!ddh_program_listed(list, match_file, match_argv) && !ddh_launched(match_file, match_argv, envp) && + !ddh_pressed(match_file, match_argv, envp)) { + ddh_debug(envp, "not listed:", filename); + return; + } + if (!ddh_startable(filename)) { + ddh_debug(envp, "would not start:", filename); + return; + } + if (!ddh_utf8(filename) || !ddh_all_utf8(argv) || !ddh_all_utf8(envp)) { + ddh_debug(envp, "not all UTF-8:", filename); + return; + } + + int fds[DDH_MAX_FDS + 1]; + int nfds = ddh_open_fds(fds, DDH_MAX_FDS, table_fd); + if (nfds < 0) return; + + int slot = -1; + for (int i = 0; i < DDH_SLOTS; i++) { + int expected = DDH_FREE; + if (__atomic_compare_exchange_n(&table->e[i].state, &expected, DDH_CLAIMED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) { + slot = i; + break; + } + } + if (slot < 0) return; + struct ddh_entry *e = &table->e[slot]; + int32_t gen = __atomic_load_n(&e->gen, __ATOMIC_RELAXED) + 1; + __atomic_store_n(&e->gen, gen ? gen : 1, __ATOMIC_RELEASE); + pid_t me = getpid(), parent = (pid_t)syscall(SYS_getppid); + // Before the request: the app checks them before it reports an exit into this entry, which a + // later handoff may have taken over by then. + e->child = me; + e->parent = parent; + e->real = 0; + // One look at the group: waitpid(0) and waitpid(-GROUP) pick the child by it, and the request + // names the group it stands for from it (the parent can move this child meanwhile). + pid_t real_group = getpgrp(); + e->pad[1] = real_group; + e->status = DDH_NO_STATUS; + __atomic_store_n((uint64_t *)e->app, 0, __ATOMIC_RELAXED); + e->child_start = ddh_start_time(me); + char cwd[PATH_MAX]; + // The guest's name for it, else the kernel's (the worker's cd takes either). A directory with no + // name (removed) cannot be sent: the exec stays here, in it. + if (!getcwd(cwd, sizeof(cwd))) { + int err = errno; + long n = call_orig_syscall(SYS_getcwd, (unsigned long)cwd, sizeof(cwd), 0, 0, 0, 0); + // Outside this process's root (a program in Steam's runtime container): the rest is the path + // from Android's root, where the worker runs + static const char unreachable[] = "(unreachable)/"; + if (n > 0 && strncmp(cwd, unreachable, sizeof(unreachable) - 1) == 0) + memmove(cwd, cwd + sizeof(unreachable) - 2, strlen(cwd + sizeof(unreachable) - 2) + 1); + if (n <= 0 || cwd[0] != '/') { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + char why[160]; + snprintf(why, sizeof(why), "no name for the working directory (errno %d, then %ld/%d \"%.40s\"):", err, n, + n < 0 ? errno : 0, n > 0 ? cwd : ""); + ddh_debug(envp, why, filename); + return; + } + char why[64]; + snprintf(why, sizeof(why), "kernel name for the working directory (errno %d):", err); + ddh_debug(envp, why, cwd); + } + if (!ddh_utf8(cwd)) { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + ddh_debug(envp, "working directory not UTF-8:", cwd); + return; + } + // What the program would have inherited here and a worker does not have: ignored signals, the + // open-files limit, the umask (ddh_apply_inherited() restores them in the program). + unsigned long ignored = 0; + for (int sig = 1; sig < 32; sig++) { + struct sigaction sa; + if (sigaction(sig, NULL, &sa) == 0 && sa.sa_handler == SIG_IGN) ignored |= 1UL << (sig - 1); + } + struct rlimit nofile = {0, 0}; + getrlimit(RLIMIT_NOFILE, &nofile); + mode_t mask = umask(0); + umask(mask); + sigset_t blocked; + pid_t anchor = getenv("DDH_WORKER_PID") ? (pid_t)atoi(getenv("DDH_WORKER_PID")) : parent; + long parent_start = ddh_start_time(parent), anchor_start = ddh_start_time(anchor); + pid_t group = ddh_logical_group(real_group); + unsigned long blocked_bits = 0; + if (sigprocmask(SIG_BLOCK, NULL, &blocked) == 0) { + for (int sig = 1; sig <= 64 && sig < NSIG; sig++) { + if (sigismember(&blocked, sig) == 1) blocked_bits |= 1UL << (sig - 1); + } + } + + struct ddh_buf b = {0}; + for (int pass = 0; pass < 2; pass++) { + b.len = 0; + ddh_puts(&b, "{\"file\":"); + ddh_putstr(&b, filename); + ddh_puts(&b, ",\"argv\":"); + ddh_putarray(&b, argv); + ddh_puts(&b, ",\"envlist\":"); + ddh_putarray(&b, envp); + ddh_puts(&b, ",\"cwd\":"); + ddh_putstr(&b, cwd); + ddh_puts(&b, ",\"fds\":["); + for (int i = 0; i < nfds; i++) { + if (i) ddh_put(&b, ",", 1); + ddh_putint(&b, fds[i]); + } + ddh_puts(&b, "],\"fdchunks\":"); + ddh_putint(&b, DDH_FDS_PER_CHUNK); + ddh_puts(&b, ",\"table\":"); + ddh_putint(&b, nfds); + ddh_puts(&b, ",\"slot\":"); + ddh_putint(&b, slot); + ddh_puts(&b, ",\"parent\":"); + ddh_putint(&b, parent); + ddh_puts(&b, ",\"child\":"); + ddh_putint(&b, me); + ddh_puts(&b, ",\"sigign\":"); + ddh_putint(&b, (long)ignored); + ddh_puts(&b, ",\"nofile\":"); + ddh_putint(&b, (long)nofile.rlim_cur); + ddh_puts(&b, ",\"nofilemax\":"); + ddh_putint(&b, (long)nofile.rlim_max); + ddh_puts(&b, ",\"umask\":"); + ddh_putint(&b, (long)mask); + ddh_puts(&b, ",\"pgid\":"); + ddh_putint(&b, (long)group); + // the session it belongs to (DD_SPAWN_SESSION), which the app starts it for, not a later one + const char *session = ddh_env(envp, "DD_SPAWN_SESSION"); + if (session && *session >= '1' && *session <= '9') { + ddh_puts(&b, ",\"session\":"); + ddh_putint(&b, strtol(session, NULL, 10)); + } + ddh_puts(&b, ",\"sigmask\":"); + ddh_putint(&b, (long)blocked_bits); + ddh_puts(&b, ",\"anchor\":"); + ddh_putint(&b, (long)anchor); + // their start times now, while both are surely the ones meant (see ddh_logical_parent) + ddh_puts(&b, ",\"pstart\":"); + ddh_putint(&b, parent_start); + ddh_puts(&b, ",\"astart\":"); + ddh_putint(&b, anchor_start); + // the worker runs the program only once this side has its pid (the "go" below) + ddh_puts(&b, ",\"ack\":true}"); + if (pass == 0) { + b.cap = b.len + 4; + b.p = mmap(NULL, b.cap, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (b.p == MAP_FAILED) { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + return; + } + } + } + fds[nfds] = table_fd; + + long pid = -1; + int s = (int)syscall(SYS_socket, AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + struct sockaddr_un addr = {.sun_family = AF_UNIX}; + size_t namelen = strlen(sock); + if (s >= 0 && namelen + 1 < sizeof(addr.sun_path)) { + memcpy(addr.sun_path + 1, sock, namelen); + socklen_t alen = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + namelen); + if (syscall(SYS_connect, s, &addr, alen) == 0) { + uint32_t len = (uint32_t)b.len; + unsigned char header[4] = {(unsigned char)(len >> 24), (unsigned char)(len >> 16), (unsigned char)(len >> 8), (unsigned char)len}; + long sent = 0; + while (sent < (long)(b.len + 4)) { + long more = sent < 4 ? syscall(SYS_sendto, s, header + sent, 4 - sent, MSG_NOSIGNAL, NULL, 0) + : syscall(SYS_sendto, s, b.p + (sent - 4), b.len + 4 - sent, MSG_NOSIGNAL, NULL, 0); + if (more <= 0) break; + sent += more; + } + // Then the fds, at most DDH_FDS_PER_CHUNK with each byte: the app's LocalSocket takes + // no more than 64 fds in one read. + for (int at = 0; sent == (long)(b.len + 4) && at < nfds + 1; at += DDH_FDS_PER_CHUNK) { + int count = nfds + 1 - at < DDH_FDS_PER_CHUNK ? nfds + 1 - at : DDH_FDS_PER_CHUNK; + char marker = 'F'; + struct iovec iov = {&marker, 1}; + char control[CMSG_SPACE(sizeof(int) * DDH_FDS_PER_CHUNK)]; + struct msghdr msg = {.msg_iov = &iov, .msg_iovlen = 1, .msg_control = control, + .msg_controllen = CMSG_SPACE(sizeof(int) * count)}; + struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); + cm->cmsg_level = SOL_SOCKET; + cm->cmsg_type = SCM_RIGHTS; + cm->cmsg_len = CMSG_LEN(sizeof(int) * count); + memcpy(CMSG_DATA(cm), fds + at, sizeof(int) * count); + if (syscall(SYS_sendmsg, s, &msg, MSG_NOSIGNAL) != 1) sent = -1; + } + if (sent == (long)(b.len + 4)) { + char reply[64]; + size_t got = 0; + while (got < sizeof(reply) - 1) { + long r = syscall(SYS_read, s, reply + got, 1); + if (r < 0 && errno == EINTR) continue; // the program may already be running + if (r <= 0 || reply[got] == '\n') break; + got++; + } + reply[got] = 0; + if (strncmp(reply, "pid ", 4) == 0) pid = atol(reply + 4); + // Without it the app does not let the worker run the program, and it runs here. + if (pid > 0 && syscall(SYS_sendto, s, "go\n", 3, MSG_NOSIGNAL, NULL, 0) != 3) pid = -1; + // Then the app's last word, once the worker has taken the program on: "ok", or it + // never runs there and runs here. + if (pid > 0) { + char last[32]; + size_t have = 0; + while (have < sizeof(last) - 1) { + long r = syscall(SYS_read, s, last + have, 1); + if (r < 0 && errno == EINTR) continue; + if (r <= 0 || last[have] == '\n') break; + have++; + } + last[have] = 0; + if (strcmp(last, "ok") != 0) pid = -1; + } + } + } + } + if (s >= 0) syscall(SYS_close, s); + munmap(b.p, b.cap); + if (pid <= 0) { + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); + ddh_debug(envp, "spawner refused", filename); + return; + } + e->child = me; + e->parent = parent; + e->real = (int32_t)pid; + e->reaped = 0; + int expected = DDH_CLAIMED; + // the app may already have written DDH_EXITED for a program that ended at once + __atomic_compare_exchange_n(&e->state, &expected, DDH_HANDED, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); + // Tests only ("FD"): the forked child waits for a byte on FD before it exits, as one descheduled + // here would, while its program's exit may already be in the table. + const char *hold = ddh_env(envp, "DDH_TEST_SHIM_HOLD"); + char *end = NULL; + long hold_fd = hold && *hold ? strtol(hold, &end, 10) : -1; + if (hold_fd > 0 && hold_fd < INT_MAX && end && *end == 0) { + char c; + while (syscall(SYS_read, (int)hold_fd, &c, 1) < 0 && errno == EINTR) {} + } + syscall(SYS_exit_group, 0); +} + +static void ddh_try(const char *filename, char *const argv[], char *const envp[]) { + ddh_try_as(filename, argv, envp, filename, argv); +} + +// ---- the parent's side ----------------------------------------------------------------------- + +static struct ddh_entry *ddh_find(pid_t child) { + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || child <= 0) return NULL; + pid_t me = getpid(); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &g_ddh->e[i]; + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->parent == me && e->child == child) return e; + } + return NULL; +} + +// Whether e's forked child is reaped. A wait marks it with the generation e had when the wait found it +// (ddh_mark_reaped()), so a mark that comes after the slot went to a later handoff, the wait having +// been held up between its reap and the mark, marks nothing: the later child still counts as not +// reaped, and a reap of it later finds it or ECHILD, which is the same. +static int ddh_reaped(const struct ddh_entry *e) { + int32_t mark = __atomic_load_n(&e->reaped, __ATOMIC_ACQUIRE); + return mark != 0 && mark == __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE); +} + +static void ddh_mark_reaped(struct ddh_entry *e, int32_t gen) { __atomic_store_n(&e->reaped, gen, __ATOMIC_RELEASE); } + +// The generation of e, the entry of child: 0 when the slot has gone to another child meanwhile. +static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) { + int32_t gen = __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE); + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0; +} + +// ---- children no wait will come for ------------------------------------------------------------ +// +// Every session process is a child subreaper (tools/linuxfs/preload/subreaper.c): a process whose +// parent exits goes to its nearest ancestor in the session, not to init, which some vendor kernels +// kill. Most programs never wait for a child they did not fork, so what they adopt stays a zombie (the +// grandchildren of Qt's startDetached() under Plasma's shell, KWin and kaccess). Each process records +// here, at its pid, the parent that started it and its own start time (DD_PARENTS, one file for the +// session): a zombie whose record names another parent was adopted. +static uint64_t *g_ddh_parents; + +static void ddh_open_parents(void) { + const char *name = getenv("DD_PARENTS"); + if (!name || !*name || __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE)) return; + char path[PATH_MAX]; + const char *real = rewrite_path(name, path, sizeof(path)); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real, + O_RDWR | O_CREAT | O_CLOEXEC, 0600, 0, 0); + if (fd < 0) return; + size_t size = (size_t)DDH_FORKS * sizeof(uint64_t); + struct stat st; + if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size < size) + call_orig_syscall(SYS_ftruncate, (unsigned long)fd, size, 0, 0, 0, 0); + // past the file's end a page would fault (SIGBUS): mapped only once the file has its size + void *map = MAP_FAILED; + if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size >= size) + map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + syscall(SYS_close, fd); + if (map == MAP_FAILED) return; + uint64_t *none = NULL; + if (!__atomic_compare_exchange_n(&g_ddh_parents, &none, (uint64_t *)map, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) + munmap(map, size); +} + +static uint64_t ddh_parent_record(pid_t parent, long start) { return (uint64_t)(uint32_t)parent << 32 | (uint32_t)start; } + +static void ddh_record_parent(pid_t me, pid_t parent) { + uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE); + if (!map || me <= 0) return; + int saved = errno; + long start = ddh_start_time(me); + errno = saved; + if (start > 0) __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record(parent, start), __ATOMIC_RELEASE); +} + +// At a program's start, unless its fork recorded it: the child of a vfork(), of glibc's own +// posix_spawn() (popen(), system()) or of a raw clone() records the parent it has now, which is +// still the one that started it (a vfork()'s waits for the exec). +static void ddh_record_own_parent(void) { + uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE); + if (!map) return; + pid_t me = (pid_t)syscall(SYS_getpid); + int saved = errno; + long start = ddh_start_time(me); + errno = saved; + if (start <= 0) return; + uint64_t r = __atomic_load_n(&map[(uint32_t)me % DDH_FORKS], __ATOMIC_ACQUIRE); + if ((uint32_t)r == (uint32_t)start && r >> 32) return; + __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record((pid_t)syscall(SYS_getppid), start), __ATOMIC_RELEASE); +} + +// /proc/PID/stat's state and start time, from a signal handler: 0 when it cannot be read. +static int ddh_proc_state(pid_t pid, char *state, long *start, pid_t *ppid) { + char path[48] = "/proc/", digits[16], stat[512]; + int n = 0, len = 6; + for (unsigned int v = (unsigned int)pid; v || !n; v /= 10) digits[n++] = (char)('0' + v % 10); + while (n) path[len++] = digits[--n]; + memcpy(path + len, "/stat", 6); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + long got = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)stat, sizeof(stat) - 1, 0, 0, 0); + call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0); + if (got <= 0) return 0; + stat[got] = 0; + char *p = strrchr(stat, ')'); + if (!p || p[1] != ' ' || !p[2]) return 0; + *state = p[2]; + // ") S PPID": field 4; starttime is field 22 + long parent = 0; + for (const char *q = p + 4; *q >= '0' && *q <= '9'; q++) parent = parent * 10 + (*q - '0'); + *ppid = (pid_t)parent; + for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' '); + long t = 0; + for (const char *q = p ? p + 1 : ""; *q >= '0' && *q <= '9'; q++) t = t * 10 + (*q - '0'); + *start = t; + return 1; +} + +// Reaps child if no wait will come for it: the forked child of a handed-off program (its program's +// exit stays in the table for the program's own waits, as when a wait reaps it), or a child this +// process adopted. 1 when it did. +static int ddh_reap_unwaited(pid_t me, pid_t child) { + char state = 0; + long start = 0; + pid_t ppid = 0; + if (!ddh_proc_state(child, &state, &start, &ppid) || state != 'Z' || ppid != me) return 0; + struct ddh_entry *e = ddh_find(child); + int32_t gen = e ? ddh_gen_of(e, child) : 0; + if (gen) { + if (ddh_reaped(e) || call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) != child) return 0; + ddh_mark_reaped(e, gen); + return 1; + } + uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE); + uint64_t r = map ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0; + if (!r || (uint32_t)r != (uint32_t)start || (pid_t)(r >> 32) == me || !(r >> 32)) return 0; + return call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) == child; +} + +// From the SIGCHLD handler (signals.c): the zombies among this process's children that no wait will +// come for. The kernel names one zombie at a time; past one the program will reap itself, /proc. +static void ddh_reap_unclaimed(void) { + if (!__atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE) && !__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return; + int saved = errno; + pid_t me = (pid_t)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0); + // past 64 reaped this way, the rest from /proc too + int scan = 1; + for (int i = 0; i < 64; i++) { + siginfo_t si; + memset(&si, 0, sizeof(si)); + if (call_orig_syscall(SYS_waitid, P_ALL, 0, (unsigned long)&si, WEXITED | WNOHANG | WNOWAIT, 0, 0) != 0 || si.si_pid <= 0) { + scan = 0; + break; + } + if (!ddh_reap_unwaited(me, si.si_pid)) { + break; + } + } + int dir = scan ? (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc", + O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0) : -1; + char buf[2048]; + while (dir >= 0) { + long n = call_orig_syscall(SYS_getdents64, (unsigned long)dir, (unsigned long)buf, sizeof(buf), 0, 0, 0); + if (n <= 0) break; + for (long off = 0; off < n;) { + struct ddh_reap_dirent { + uint64_t ino; + int64_t off; + unsigned short reclen; + unsigned char type; + char name[]; + } *d = (struct ddh_reap_dirent *)(buf + off); + off += d->reclen; + long pid = 0; + const char *c = d->name; + for (; *c >= '0' && *c <= '9'; c++) pid = pid * 10 + (*c - '0'); + if (!*c && pid > 0 && pid != me) ddh_reap_unwaited(me, (pid_t)pid); + } + } + if (dir >= 0) call_orig_syscall(SYS_close, (unsigned long)dir, 0, 0, 0, 0, 0); + errno = saved; +} + +// Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it. +static int ddh_take(struct ddh_entry *e) { + int expected = DDH_EXITED; + return __atomic_compare_exchange_n(&e->state, &expected, DDH_TAKEN, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE); +} + +// Gives a taken exit back, for a later wait (its forked child is not reaped yet). +static void ddh_untake(struct ddh_entry *e) { __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); } + +// 1 alive, 0 exited, -1 not known (/proc could not be read, out of fds say) +static int ddh_thread_alive(pid_t thread) { + char path[64], stat[256]; + snprintf(path, sizeof(path), "/proc/self/task/%d/stat", (int)thread); + int saved = errno; + long n = ddh_read_proc(path, stat, sizeof(stat)); + int failed = errno; + errno = saved; + if (n <= 0) return failed == ENOENT || failed == ESRCH ? 0 : -1; + char *s = strrchr(stat, ')'); + return s && s[1] == ' ' && s[2] != 'Z' && s[2] != 'X'; +} + +// The first live thread of the group, in its thread list's order (which /proc/self/task lists), +// as the kernel picks a new parent for an exited thread's children (find_alive_thread()); 0 when +// /proc cannot say. +static pid_t ddh_first_live_thread(void) { + int dir = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/task", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0) return 0; + pid_t found = 0; + int unknown = 0; + char buf[2048]; + for (long n; !found && !unknown && (n = syscall(SYS_getdents64, dir, buf, sizeof(buf))) > 0;) { + for (long off = 0; off < n && !found && !unknown;) { + struct ddh_task_dirent { + uint64_t ino; + int64_t off; + unsigned short reclen; + unsigned char type; + char name[]; + } *d = (struct ddh_task_dirent *)(buf + off); + off += d->reclen; + pid_t tid = (pid_t)atoi(d->name); + int alive = tid > 0 ? ddh_thread_alive(tid) : 0; + if (alive < 0) unknown = 1; + else if (alive > 0) found = tid; + } + } + syscall(SYS_close, dir); + return unknown ? 0 : found; +} + +// The thread a child's exit goes to now: the one that forked it while that lives, then the one the +// kernel moved it to, the group's first live thread. Only an exit /proc confirms moves it: when /proc +// cannot say, the forking thread keeps it. +static pid_t ddh_child_owner(const struct ddh_entry *e) { + pid_t thread = ddh_forking_thread(e->child, (long)e->child_start); + if (thread <= 0 || ddh_thread_alive(thread) != 0) return thread; + pid_t heir = ddh_first_live_thread(); + return heir > 0 ? heir : thread; +} + +// Whether a wait for pid (-1: any child, 0: one in our group, -G: one in group G) takes e's child. +static int ddh_selects(const struct ddh_entry *e, pid_t pid) { + if (t_ddh_only_thread) { + // Not this thread's, or not known yet (the fork is still being recorded): not for this wait. + if (ddh_child_owner(e) != t_ddh_only_thread) return 0; + } + if (pid > 0) return e->child == pid; + if (pid == -1) return 1; + return e->pad[1] == (pid == 0 ? getpgrp() : -pid); +} + +static void ddh_release(struct ddh_entry *e, int *status); + +// A new child of ours got pid: an entry naming it for an earlier process (its forked child reaped +// early, as the wait above does, so the pid was free again) stands for a program the pid no longer +// reaches. The real child owns the pid from now on: kill() and wait() go to it, and that program's +// exit is dropped. Only after the pid space has wrapped around while that program runs. Told apart by +// start time, not by the reaped flag: another thread may have reaped that forked child and not yet +// marked it, and the new child may already have handed off a program of its own under the pid. +// Without both start times (the new child already reaped too) nothing is dropped: an entry of the +// new child's own must not be, and a stale one needs the pid space to wrap besides. +static void ddh_drop_stale(pid_t pid) { + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + if (!t || pid <= 0) return; + pid_t me = getpid(); + long start = -2; // read once, when an entry names the pid + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &t->e[i]; + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st != DDH_HANDED && st != DDH_EXITED) || e->parent != me || e->child != pid) continue; + if (start == -2) start = ddh_start_time(pid); + if (e->child_start < 0 || start < 0 || e->child_start == start) continue; + if (__atomic_compare_exchange_n(&e->state, &st, DDH_TAKEN, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) + ddh_release(e, NULL); + } +} + +// Tests only ("FD TID"): holds the record of thread TID's forks until a byte can be read from FD, as a +// parent thread descheduled between its fork and the record would be. +static void ddh_record_gate(void) { + const char *gate = getenv("DDH_TEST_RECORD_GATE"), *tid = gate ? strchr(gate, ' ') : NULL; + if (!tid || atoi(tid + 1) != (int)syscall(SYS_gettid)) return; + int saved = errno; + char c; + while (syscall(SYS_read, atoi(gate), &c, 1) < 0 && errno == EINTR) {} + errno = saved; +} + +// A new child at pid, which recorded itself (a fork() child) or is recorded here (a spawned one) +static void ddh_child_created(pid_t pid, int recorded) { + if (pid <= 0) return; + ddh_record_gate(); + ddh_drop_stale(pid); + // only where children can hand off + if (!recorded && __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) ddh_forked_by(pid, (pid_t)syscall(SYS_gettid)); +} + +// Takes e's exit for a wait for pid, checked again once taken: between finding e and taking it, +// another waiter may have released the slot and a later child of ours (or one of another group) +// have exited in it. +static int ddh_take_for(struct ddh_entry *e, pid_t pid) { + if (!ddh_take(e)) return 0; + if (e->parent == getpid() && ddh_selects(e, pid)) return 1; + ddh_untake(e); + return 0; +} + +static int ddh_any_live(pid_t pid) { + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return 0; + pid_t me = getpid(); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &g_ddh->e[i]; + int st = __atomic_load_n(&e->state, __ATOMIC_ACQUIRE); + if ((st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN || st == DDH_CLAIMED) && e->parent == me && ddh_selects(e, pid)) return 1; + } + return 0; +} + +// The entry of child while it is still handing its program off (its request is with the app). +static struct ddh_entry *ddh_claiming(pid_t child) { + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || child <= 0) return NULL; + pid_t me = getpid(); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &g_ddh->e[i]; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_CLAIMED && e->parent == me && e->child == child) return e; + } + return NULL; +} + +// A worker that is gone with no status from the app (it crashed with the app): reported as killed. +// A worker that is gone: its program's end as the app reported it (a signal), else, with no report +// after a while (the app crashed with it), as killed. +static void ddh_check_gone(void) { + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + if (!t) return; + pid_t me = getpid(); + for (int i = 0; i < DDH_SLOTS; i++) { + struct ddh_entry *e = &t->e[i]; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_HANDED || e->parent != me) continue; + pid_t child = e->child; + if (syscall(SYS_kill, e->real, 0) == 0 || errno != ESRCH) continue; + int32_t report[2]; + uint64_t both = __atomic_load_n((uint64_t *)e->app, __ATOMIC_ACQUIRE); + memcpy(report, &both, sizeof(report)); + int32_t status = SIGKILL; + if (report[1] == child && report[1] != 0) { + status = report[0]; + } else { + // The app looks the status up for up to a second after the worker's death: wait longer. + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + // The time is kept with the child it is for: a slot taken over since by another child + // starts its own count. + uint64_t seen = __atomic_load_n(&e->gone, __ATOMIC_ACQUIRE); + if ((uint32_t)(seen >> 32) != (uint32_t)child) { + uint64_t mark = (uint64_t)(uint32_t)child << 32 | (uint32_t)(now.tv_sec + 1); + __atomic_compare_exchange_n(&e->gone, &seen, mark, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); + continue; + } + if (now.tv_sec + 1 - (int64_t)(uint32_t)seen < 3) continue; + } + // Only this side moves HANDED to EXITED, the entry held meanwhile and still the child looked at: + // a waiter may have finished with it and a new handoff taken the slot since the look above. + int expected = DDH_HANDED; + if (!__atomic_compare_exchange_n(&e->state, &expected, DDH_TAKEN, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) continue; + if (e->child != child || e->parent != me) { + __atomic_store_n(&e->state, DDH_HANDED, __ATOMIC_RELEASE); + continue; + } + // a status the program wrote itself is kept + int32_t none = DDH_NO_STATUS; + if (__atomic_compare_exchange_n(&e->status, &none, status, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED) && + report[1] != child) + e->guessed = 1; // an app report that comes before the exit is taken wins (ddh_status) + __atomic_store_n(&e->state, DDH_EXITED, __ATOMIC_RELEASE); + } +} + +static int ddh_status(const struct ddh_entry *e) { + if (!e->guessed) return e->status; + // SIGKILL was the timeout's guess (no report then): the app's report, if it has come since + int32_t report[2]; + uint64_t both = __atomic_load_n((const uint64_t *)e->app, __ATOMIC_ACQUIRE); + memcpy(report, &both, sizeof(report)); + return report[1] != 0 && report[1] == e->child ? report[0] : e->status; +} + +static void ddh_release(struct ddh_entry *e, int *status) { + if (status) *status = ddh_status(e); + memset(e, 0, offsetof(struct ddh_entry, state)); + e->status = 0; + e->reaped = 0; + e->pad[0] = 0; + e->pad[1] = 0; + e->guessed = 0; + __atomic_store_n(&e->gone, 0, __ATOMIC_RELAXED); + __atomic_store_n((uint64_t *)e->app, 0, __ATOMIC_RELAXED); + __atomic_store_n(&e->state, DDH_FREE, __ATOMIC_RELEASE); +} + +typedef pid_t (*ddh_wait4_f)(pid_t, int *, int, struct rusage *); + +static ddh_wait4_f ddh_real_wait4(void) { + static ddh_wait4_f f; + if (!f) f = (ddh_wait4_f)dlsym(RTLD_NEXT, "wait4"); + return f; +} + +// A wait interrupted by a signal: as the real call, which a handler installed with SA_RESTART restarts. +// The app's and the program's SIGCHLD are the usual ones. +// Tests only ("IN OUT TID"): thread TID's wait, once its look has found a child, writes a byte to OUT +// and waits for one on IN, as a waiter descheduled before it takes that child would. +static void ddh_wait_gate(int code) { + const char *gate = getenv("DDH_TEST_WAIT_GATE"); + int in, out, tid; + if (!gate || sscanf(gate, "%d %d %d", &in, &out, &tid) != 3 || tid != (int)syscall(SYS_gettid)) return; + int saved = errno; + char c = (char)code; // the event it found (CLD_EXITED, CLD_STOPPED...) + syscall(SYS_write, out, &c, 1); + while (syscall(SYS_read, in, &c, 1) < 0 && errno == EINTR) {} + errno = saved; +} + +// The forked child of an entry whose program has exited: 1 once reaped (or already gone), 0 when it is +// still exiting and WNOHANG was asked for, or the wait was interrupted. Gone means another wait reaped +// it, and that one never reports it (ddh_wait()). +// Tests only ("IN OUT TID"): as ddh_wait_gate(), once thread TID's wait has reaped a forked child +// that handed its program off and before it marks the entry. +static void ddh_reap_gate(void) { + const char *gate = getenv("DDH_TEST_REAP_GATE"); + int in, out, tid; + if (!gate || sscanf(gate, "%d %d %d", &in, &out, &tid) != 3 || tid != (int)syscall(SYS_gettid)) return; + int saved = errno; + char c = 1; + syscall(SYS_write, out, &c, 1); + while (syscall(SYS_read, in, &c, 1) < 0 && errno == EINTR) {} + errno = saved; +} + +static int ddh_reap_shim(ddh_wait4_f real, struct ddh_entry *e, pid_t child, int options) { + (void)e; + pid_t r = real(child, NULL, options & (WNOHANG | __WALL | __WNOTHREAD), NULL); + return r == child || (r < 0 && errno == ECHILD); +} + +// The program of an exited entry a wait for pid takes: its pid and status, the entry released (or +// left for the next wait when keep), or 0 when none is ready. Every exited entry, not just the first: +// one whose forked child is still exiting is skipped (the caller's real wait reaps that exit, or a +// later pass does) and the next one may be ready. +static pid_t ddh_reap_exited(ddh_wait4_f real, pid_t pid, int *status, int keep, int flags) { + struct ddh_table *t = __atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE); + for (int i = 0; t && i < DDH_SLOTS; i++) { + struct ddh_entry *e = &t->e[i]; + if (__atomic_load_n(&e->state, __ATOMIC_ACQUIRE) != DDH_EXITED || !ddh_take_for(e, pid)) continue; + pid_t child = e->child; + if (!ddh_reaped(e) && !ddh_reap_shim(real, e, child, WNOHANG | flags)) { + ddh_untake(e); + continue; + } + ddh_mark_reaped(e, __atomic_load_n(&e->gen, __ATOMIC_ACQUIRE)); + if (keep) { + if (status) *status = ddh_status(e); + ddh_untake(e); + } else { + ddh_release(e, status); + } + return child; + } + return 0; +} + +// 20 ms, or -1 (EINTR) when a signal's handler interrupted it. The read of a timerfd restarts, as a +// wait does, after a handler installed with SA_RESTART; nanosleep() never does. +static int ddh_nap(void) { + pthread_testcancel(); // as the wait it stands for would be: nothing is held here + int fd = (int)syscall(SYS_timerfd_create, CLOCK_MONOTONIC, O_CLOEXEC); + if (fd < 0) { + struct timespec ts = {0, 20 * 1000 * 1000}; + nanosleep(&ts, NULL); + return 0; + } + struct itimerspec when = {{0, 0}, {0, 20 * 1000 * 1000}}; + uint64_t ticks; + long r = syscall(SYS_timerfd_settime, fd, 0, &when, NULL) == 0 ? syscall(SYS_read, fd, &ticks, sizeof(ticks)) : 0; + int err = errno; + syscall(SYS_close, fd); + if (r < 0 && err == EINTR) { + errno = EINTR; + return -1; + } + return 0; +} + +static pid_t ddh_wait(pid_t pid, int *status, int options, struct rusage *ru) { + ddh_wait4_f real = ddh_real_wait4(); + if (!real) { + errno = ENOSYS; + return -1; + } + // As waitid(): the kernel's alone for options it refuses (WNOWAIT among them), for __WCLONE + // alone, which selects no forked child, and for INT_MIN, a group it refuses (ESRCH) + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || pid == INT_MIN || + (options & ~(WNOHANG | WUNTRACED | WCONTINUED | __WALL | __WNOTHREAD | __WCLONE)) || + ((options & __WCLONE) && !(options & __WALL))) + return real(pid, status, options, ru); + // After a nap a signal interrupted, one more look before EINTR: the signal may be the SIGCHLD + // that reports an exit. + int interrupted = 0; + for (;;) { + ddh_check_gone(); + // with __WNOTHREAD, another thread's child is not one this wait may take (ddh_selects()) + struct ddh_entry *e = pid > 0 ? ddh_find(pid) : NULL; + if (e && !ddh_selects(e, pid)) e = NULL; + if (pid > 0 && e) { + int32_t gen = ddh_gen_of(e, pid); + if (gen && !ddh_reaped(e) && real(pid, NULL, WNOHANG | (options & (__WALL | __WNOTHREAD)), NULL) == pid) + ddh_mark_reaped(e, gen); + if (ddh_take_for(e, pid)) { + // the forked child is between its last write and its exit: reap it first, or a later + // wait() would report its pid a second time (not blocking for WNOHANG: then later) + if (!ddh_reaped(e) && !ddh_reap_shim(real, e, pid, options)) { + ddh_untake(e); + return (options & WNOHANG) ? 0 : -1; + } + if (ru) memset(ru, 0, sizeof(*ru)); + ddh_release(e, status); + return pid; + } + if (options & WNOHANG) return 0; + if (interrupted) { + errno = EINTR; + return -1; + } + interrupted = ddh_nap() != 0; + continue; + } + pid_t done = pid <= 0 ? ddh_reap_exited(real, pid, status, 0, options & (__WALL | __WNOTHREAD)) : 0; + if (done > 0) { + if (ru) memset(ru, 0, sizeof(*ru)); + return done; + } + int live = pid <= 0 && ddh_any_live(pid); + // A look first (WNOWAIT), then the reap of the child it found alone. A forked child that + // handed its program off is only ever reaped here, never reported, however late this wait gets + // to it: another wait may have reported its program already. + idtype_t type = pid > 0 ? P_PID : pid == -1 ? P_ALL : P_PGID; + id_t id = pid > 0 ? (id_t)pid : pid == 0 ? (id_t)syscall(SYS_getpgid, 0) : (id_t)-pid; + int look = WEXITED | WNOWAIT | (options & (__WALL | __WNOTHREAD | __WCLONE)) | + ((options & WUNTRACED) ? WSTOPPED : 0) | ((options & WCONTINUED) ? WCONTINUED : 0) | + ((live || (options & WNOHANG)) ? WNOHANG : 0); + siginfo_t seen; + memset(&seen, 0, sizeof(seen)); + // libc's waitid(): a blocking look stays a cancellation point, as the wait4() it stands for is + static int (*libc_waitid)(idtype_t, id_t, siginfo_t *, int); + if (!libc_waitid) libc_waitid = (int (*)(idtype_t, id_t, siginfo_t *, int))dlsym(RTLD_NEXT, "waitid"); + pid_t r = libc_waitid ? libc_waitid(type, id, &seen, look) + : (pid_t)call_orig_syscall(SYS_waitid, (unsigned long)type, (unsigned long)id, (unsigned long)&seen, + (unsigned long)look, 0, 0); + if (r == 0 && seen.si_pid > 0) { + pid_t child = seen.si_pid; + ddh_wait_gate(seen.si_code); + // A stop or a continue reaps nothing: reported as it is, the entry and the claim left alone + int ended = seen.si_code == CLD_EXITED || seen.si_code == CLD_KILLED || seen.si_code == CLD_DUMPED; + struct ddh_entry *h = ended ? ddh_find(child) : NULL; + int32_t gen = h ? ddh_gen_of(h, child) : 0; + if (gen && !ddh_reaped(h)) { + real(child, NULL, WNOHANG | (options & (__WALL | __WNOTHREAD)), NULL); + ddh_reap_gate(); + ddh_mark_reaped(h, gen); // the forked child that handed its program off + continue; + } + int wstatus = 0; + if (!ended) { + // Only the kind of event looked at: the child may have gone on since, handed its + // program off and exited, and a wait4() would take that exit, the forked child's. + siginfo_t got; + struct rusage usage; + memset(&got, 0, sizeof(got)); + memset(&usage, 0, sizeof(usage)); + int kind = seen.si_code == CLD_CONTINUED ? WCONTINUED : WSTOPPED; + if (call_orig_syscall(SYS_waitid, P_PID, (unsigned long)child, (unsigned long)&got, + (unsigned long)(kind | WNOHANG | (options & (__WALL | __WNOTHREAD))), (unsigned long)&usage, + 0) != 0 || + got.si_pid != child) + continue; // another wait took it + // as wait4() has it: a stop's whole code (a ptrace event's bits above the signal too) + wstatus = got.si_code == CLD_CONTINUED ? 0xffff : (got.si_status << 8) | 0x7f; + if (ru) *ru = usage; + if (status) *status = wstatus; + return child; + } + r = real(child, &wstatus, options | WNOHANG, ru); + if (r != child) continue; // another wait took it + // A forked child that died while handing its program off (a signal): its entry is done. + if ((WIFEXITED(wstatus) || WIFSIGNALED(wstatus)) && (h = ddh_claiming(r))) ddh_release(h, NULL); + if (status) *status = wstatus; + return r; + } + // No child left: a handoff may have claimed its entry since the look above, and another + // waiter reaped its forked child. The program still runs, so this wait goes on. + if (!live && r < 0 && errno == ECHILD) { + struct ddh_entry *c = pid > 0 ? ddh_find(pid) : NULL, *k = pid > 0 ? ddh_claiming(pid) : NULL; + live = pid > 0 ? (c && ddh_selects(c, pid)) || (k && ddh_selects(k, pid)) : ddh_any_live(pid); + errno = ECHILD; + } + if (!live) return r; + if (r < 0 && errno != ECHILD) return r; + if (options & WNOHANG) return 0; + if (interrupted) { + errno = EINTR; + return -1; + } + interrupted = ddh_nap() != 0; + } +} + +// The wait's own selector, the one before it given back after: a wait from a signal's handler +// leaves the one it interrupted as it was. +static pid_t ddh_wait_as_thread(pid_t pid, int *status, int options, struct rusage *ru) { + pid_t outer = t_ddh_only_thread; + t_ddh_only_thread = (options & __WNOTHREAD) ? (pid_t)syscall(SYS_gettid) : 0; + pid_t r = ddh_wait(pid, status, options, ru); + int saved = errno; + t_ddh_only_thread = outer; + errno = saved; + return r; +} + +pid_t wait4(pid_t pid, int *status, int options, struct rusage *ru) { return ddh_wait_as_thread(pid, status, options, ru); } +pid_t waitpid(pid_t pid, int *status, int options) { return ddh_wait_as_thread(pid, status, options, NULL); } +pid_t wait(int *status) { return ddh_wait_as_thread(-1, status, 0, NULL); } +pid_t wait3(int *status, int options, struct rusage *ru) { return ddh_wait_as_thread(-1, status, options, ru); } + +static int ddh_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { + typedef int (*f_t)(idtype_t, id_t, siginfo_t *, int); + static f_t real; + if (!real) real = (f_t)dlsym(RTLD_NEXT, "waitid"); + if (!real) { + errno = ENOSYS; + return -1; + } + // A wait without exits never takes a forked child's exit for the program's. Invalid option bits + // (which the kernel refuses), __WCLONE alone (which selects no forked child) and group 1 (init's, + // which a waitpid() selector of -1 would take for any child): the real call. __WALL and + // __WNOTHREAD go along with each call made here. + int carried = options & (__WALL | __WNOTHREAD); + if (!__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) || !(options & WEXITED) || + (options & ~(WEXITED | WSTOPPED | WCONTINUED | WNOHANG | WNOWAIT | __WALL | __WNOTHREAD | __WCLONE)) || + ((options & __WCLONE) && !(options & __WALL)) || + (idtype != P_PID && idtype != P_ALL && idtype != P_PGID) || (idtype == P_PGID && id == 1)) + return real(idtype, id, info, options); + if ((idtype == P_PID && (pid_t)id <= 0) || (idtype == P_PGID && (pid_t)id < 0)) { + errno = EINVAL; + return -1; + } + // As a waitpid() selector: a pid, -1 for any child, 0 for our group, -G for group G + pid_t which = idtype == P_PID ? (pid_t)id : idtype == P_PGID ? (id == 0 ? 0 : -(pid_t)id) : -1; + ddh_wait4_f w4 = ddh_real_wait4(); + // Each event is looked at (WNOWAIT) before it is taken: the forked child of a handed-off program + // exits once the program has started, and that exit is reaped here and never reported. Any other + // event is then taken from that child alone, so the caller gets the kernel's siginfo for it. + int interrupted = 0; + for (;;) { + ddh_check_gone(); + int status = 0; + pid_t r = ddh_reap_exited(w4, which, &status, options & WNOWAIT, carried); + if (r > 0) { + if (info) { + memset(info, 0, sizeof(*info)); + info->si_signo = SIGCHLD; + info->si_pid = r; + info->si_uid = (uid_t)call_orig_syscall(SYS_getuid, 0, 0, 0, 0, 0, 0); // the real one, as the kernel reports, not the root the hook shows + if (WIFEXITED(status)) { + info->si_code = CLD_EXITED; + info->si_status = WEXITSTATUS(status); + } else { + info->si_code = WCOREDUMP(status) ? CLD_DUMPED : CLD_KILLED; + info->si_status = WTERMSIG(status); + } + } + return 0; + } + int live = ddh_any_live(which); + siginfo_t seen; + memset(&seen, 0, sizeof(seen)); + if (real(idtype, id, &seen, options | WNOWAIT | (live ? WNOHANG : 0)) < 0) { + if (errno != ECHILD) return -1; + // a handoff may have claimed its entry since the look above, and another waiter reaped + // its forked child: the program still runs + if (!live && !(live = ddh_any_live(which))) { + errno = ECHILD; + return -1; + } + } else if (seen.si_pid > 0) { + pid_t child = seen.si_pid; + ddh_wait_gate(seen.si_code); + int exited = seen.si_code == CLD_EXITED || seen.si_code == CLD_KILLED || seen.si_code == CLD_DUMPED; + struct ddh_entry *h = exited ? ddh_find(child) : NULL; + int32_t gen = h ? ddh_gen_of(h, child) : 0; + if (gen && !ddh_reaped(h)) { + if (w4 && w4(child, NULL, WNOHANG | carried, NULL) == child) + ddh_mark_reaped(h, gen); // the forked child that handed its program off + continue; + } + if (options & WNOWAIT) { + // An exit with no entry found may be a forked child whose entry another wait has + // released since the look, taking it with its program's status: still there now, it + // is no such child (its entry would have been found), else the look starts over. + if (exited) { + siginfo_t again; + memset(&again, 0, sizeof(again)); + if (real(P_PID, (id_t)child, &again, WEXITED | WNOWAIT | WNOHANG | carried) < 0 || again.si_pid != child) + continue; + seen = again; + } + if (info) *info = seen; + return 0; + } + // Only the kind of event looked at: a stop's child may have gone on since, handed its + // program off and exited, and that exit is the forked child's, not one to report. + int kind = exited ? WEXITED : seen.si_code == CLD_CONTINUED ? WCONTINUED : WSTOPPED; + siginfo_t got; + memset(&got, 0, sizeof(got)); + if (real(P_PID, (id_t)child, &got, kind | carried | WNOHANG) < 0 || got.si_pid != child) continue; // another waiter took it + // A forked child that died while handing its program off (a signal): its entry is done. + int died = got.si_code == CLD_EXITED || got.si_code == CLD_KILLED || got.si_code == CLD_DUMPED; + if (died && !ddh_find(child) && (h = ddh_claiming(child))) ddh_release(h, NULL); + if (info) *info = got; + return 0; + } + if (!live || (options & WNOHANG)) { + if (info) memset(info, 0, sizeof(*info)); + return 0; + } + if (interrupted) { + errno = EINTR; + return -1; + } + interrupted = ddh_nap() != 0; + } +} + +int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { + pid_t outer = t_ddh_only_thread; + t_ddh_only_thread = (options & __WNOTHREAD) ? (pid_t)syscall(SYS_gettid) : 0; + int r = ddh_waitid(idtype, id, info, options); + int saved = errno; + t_ddh_only_thread = outer; + errno = saved; + return r; +} + +// Whether pgid is zygote's process group, which every process of the app is in until it starts a +// session of its own: signalling it would reach the app itself. +static int ddh_app_group(pid_t pgid) { + char path[32], name[16] = ""; + snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)pgid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, name, sizeof(name) - 1); + syscall(SYS_close, fd); + return n > 0 && strncmp(name, "zygote", 6) == 0; +} + +// A handed-off program runs in a session of its own (the worker's setsid()), out of the process +// group its forked parent's child was in, so a signal to that group (Steam ends a game with one) +// would miss it. Each one is listed here as GROUP.PID.START, GROUP being the group it stands for, +// and a signal to GROUP also goes to the group the program leads. +#define DDH_GROUPS "/run/droiddeck-handoff-groups" + +static long ddh_start_time(pid_t pid) { + char path[64], stat[512]; + // its main thread's, which is the process's: an emulator (qemu-user) answers /proc//stat + // itself, with values of its own, but not the task's file, so a process and its parent read the + // same start time + snprintf(path, sizeof(path), "/proc/%d/task/%d/stat", (int)pid, (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + long n = syscall(SYS_read, fd, stat, sizeof(stat) - 1); + syscall(SYS_close, fd); + if (n <= 0) return -1; + stat[n] = 0; + char *p = strrchr(stat, ')'); + // starttime is field 22; after ") " comes field 3 + for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' '); + return p ? atol(p + 1) : -1; +} + +// The group a process stands for: its worker's (DDH_PGID) while it is in the group its worker leads. +static pid_t ddh_logical_group(pid_t real) { + const char *worker = getenv("DDH_WORKER_PID"), *group = getenv("DDH_PGID"); + if (worker && group && real == (pid_t)atoi(worker)) return (pid_t)atoi(group); + return real; +} + +static pid_t ddh_logical_pgrp(void) { return ddh_logical_group(getpgrp()); } + +// Whether parent is still the process that forked the child started at child_start: not gone, not +// exited and waiting to be reaped (the kernel reparents at the exit, not at the reaping), and not a +// later process given the pid, which started after that child. child_start -1: not checked. +// 1 yes, 0 no, -1 when /proc could not be read for another reason (out of fds, say). +static int ddh_parent_lives(pid_t parent, long child_start) { + // The dup2()/dup3() wrappers move the pidfd only under this lock, so no move falls between the + // look and the poll; when another thread holds it, /proc answers instead. + uint64_t all = ~0ull, mask = 0; + int blocked = __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) >= 0 && + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&mask, 8, 0, 0) == 0; + int locked = blocked && pthread_mutex_trylock(&g_ddh_pidfd_lock) == 0; + int held = locked ? __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) : -1; + int fd = held; + if (fd >= 0 && t_kept_split && !is_kept_fd(fd)) { + // a table of its own, where the program took that number over: the spare, if still there + int spare = __atomic_load_n(&g_ddh_parent_spare, __ATOMIC_ACQUIRE); + fd = spare >= 0 && is_kept_fd(spare) ? spare : -1; + } + if (parent == g_ddh_report_parent && fd >= 0) { + // No new fd, and exited counts whether reaped or not. Only while the number still is that + // pidfd, before and after the poll (a raw close() can take it), and only a clear answer: + // anything else asks /proc. This thread's table, which is not the first thread's after a split. + char path[40], before[32], after[32]; + snprintf(path, sizeof(path), "/proc/thread-self/fd/%d", fd); + int saved = errno; + long len = syscall(SYS_readlinkat, AT_FDCWD, path, before, sizeof(before) - 1); + struct pollfd p = {fd, POLLIN, 0}; + long n = len > 0 ? syscall(SYS_ppoll, &p, 1, &(struct timespec){0, 0}, NULL, 0) : -1; + long len2 = n >= 0 ? syscall(SYS_readlinkat, AT_FDCWD, path, after, sizeof(after) - 1) : -1; + errno = saved; + if (len > 0) before[len] = 0; + if (len2 > 0) after[len2] = 0; + int clear = n >= 0 && len2 > 0 && strcmp(before, "anon_inode:[pidfd]") == 0 && strcmp(after, before) == 0 && + __atomic_load_n(&g_ddh_parent_pidfd, __ATOMIC_ACQUIRE) == held && !(p.revents & (POLLNVAL | POLLERR)); + pthread_mutex_unlock(&g_ddh_pidfd_lock); + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0); + if (clear) return !(p.revents & POLLIN); + } else { + if (locked) pthread_mutex_unlock(&g_ddh_pidfd_lock); + if (blocked) call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0); + } + char path[48], stat[512]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)parent); + int saved = errno; + long n = ddh_read_proc(path, stat, sizeof(stat)); + int failed = errno; + errno = saved; + // only a parent known gone: a lookup that failed otherwise (out of fds, say) proves nothing (-1) + if (n <= 0) return failed == ENOENT || failed == ESRCH ? 0 : -1; + char *s = strrchr(stat, ')'); + if (!s || s[1] != ' ' || s[2] == 'Z' || s[2] == 'X') return 0; + for (int field = 2; s && field < 22; field++) s = strchr(s + 1, ' '); + long start = s ? atol(s + 1) : -1; + return !(start >= 0 && child_start >= 0 && start > child_start); +} + +// A handed-off program's parent is zygote, which the guest cannot see: a launcher that watches its +// parent through /proc/ took it for gone at once. getppid() answers with the process that +// forked it (DDH_TABLE's parent) while that one lives, and init once it is gone, as after the +// kernel's reparenting. /proc//stat keeps the real parent (see docs, "Tried and dropped"). +pid_t getppid(void) { + pid_t real = (pid_t)syscall(SYS_getppid); + const char *worker = getenv("DDH_WORKER_PID"), *spec = getenv("DDH_TABLE"); + if (!worker || !spec || (pid_t)atoi(worker) != getpid()) return real; + // fd:slot:parent:child + const char *p = strchr(spec, ':'); + p = p ? strchr(p + 1, ':') : NULL; + pid_t parent = p ? (pid_t)atoi(p + 1) : 0; + if (parent <= 0) return real; + long child = g_ddh_report && g_ddh_report_slot >= 0 ? (long)g_ddh_report->e[g_ddh_report_slot].child_start : -1; + return ddh_parent_lives(parent, child) != 0 ? parent : 1; +} + +static char g_ddh_group_entry[96]; +static int g_ddh_parent_entry; + +static int ddh_open_groups(int create) { + char dir[PATH_MAX]; + const char *real_dir = rewrite_path(DDH_GROUPS, dir, sizeof(dir)); + if (create) call_orig_syscall(SYS_mkdirat, (unsigned long)AT_FDCWD, (unsigned long)real_dir, 0755, 0, 0, 0); + return (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real_dir, + O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0); +} + +// Also P, "START PARENT ANCHOR": the process that forked this program's child, the parent it +// has in place of the worker's (see ddh_signal_reaper_tree()), and the worker's program that process +// descends from (DDH_ANCHOR), for when it is gone: Wine starts a process through a fork that exits. +static void ddh_register_group(void) { + if (getpid() != g_ddh_worker) return; + int dir = ddh_open_groups(1); + if (dir < 0) return; + long start = ddh_start_time(getpid()); + char name[96], text[96]; + const char *group = getenv("DDH_PGID"); + if (group) { + snprintf(name, sizeof(name), "%d.%d.%ld", atoi(group), (int)getpid(), start); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)dir, (unsigned long)name, O_WRONLY | O_CREAT | O_CLOEXEC, 0644, 0, 0); + if (fd >= 0) { + syscall(SYS_close, fd); + snprintf(g_ddh_group_entry, sizeof(g_ddh_group_entry), "%s", name); + } + } + if (g_ddh_report_parent > 0) { + snprintf(name, sizeof(name), "P%d", (int)getpid()); + // with their start times: a pid followed later may have been reused by then + // the start times the request recorded (DDH_PSTART, DDH_ASTART): one read now could be a + // reused pid's, the forking process having exited meanwhile + const char *anchor_env = getenv("DDH_ANCHOR"), *pstart = getenv("DDH_PSTART"), *astart = getenv("DDH_ASTART"); + pid_t anchor = anchor_env ? (pid_t)atoi(anchor_env) : g_ddh_report_parent; + int len = snprintf(text, sizeof(text), "%ld %d %d %ld %ld\n", start, (int)g_ddh_report_parent, (int)anchor, + pstart ? atol(pstart) : ddh_start_time(g_ddh_report_parent), + astart ? atol(astart) : ddh_start_time(anchor)); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)dir, (unsigned long)name, + O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644, 0, 0); + if (fd >= 0) { + call_orig_syscall(SYS_write, (unsigned long)fd, (unsigned long)text, (unsigned long)len, 0, 0, 0); + syscall(SYS_close, fd); + g_ddh_parent_entry = 1; + } + } + syscall(SYS_close, dir); +} + +static void ddh_unregister_group(void) { + if ((!g_ddh_group_entry[0] && !g_ddh_parent_entry) || getpid() != g_ddh_worker) return; + int dir = ddh_open_groups(0); + if (dir < 0) return; + if (g_ddh_group_entry[0]) call_orig_syscall(SYS_unlinkat, (unsigned long)dir, (unsigned long)g_ddh_group_entry, 0, 0, 0, 0); + if (g_ddh_parent_entry) { + char name[24]; + snprintf(name, sizeof(name), "P%d", (int)getpid()); + call_orig_syscall(SYS_unlinkat, (unsigned long)dir, (unsigned long)name, 0, 0, 0, 0); + } + syscall(SYS_close, dir); + g_ddh_group_entry[0] = 0; + g_ddh_parent_entry = 0; +} + +// The process that forked pid's child (or, gone, the worker's program it descended from), when pid +// is a handed-off program; else 0. +static pid_t ddh_logical_parent(pid_t pid) { + char path[PATH_MAX], text[96]; + const char *real_dir = rewrite_path(DDH_GROUPS, path, sizeof(path)); + if (real_dir != path) snprintf(path, sizeof(path), "%s", real_dir); + size_t used = strlen(path); + if (used + 16 >= sizeof(path)) return 0; + snprintf(path + used, sizeof(path) - used, "/P%d", (int)pid); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)text, sizeof(text) - 1, 0, 0, 0); + syscall(SYS_close, fd); + if (n <= 0) return 0; + text[n] = 0; + long start = 0, parent_start = -1, anchor_start = -1; + int parent = 0, anchor = 0; + if (sscanf(text, "%ld %d %d %ld %ld", &start, &parent, &anchor, &parent_start, &anchor_start) < 5 || + ddh_start_time(pid) != start) + return 0; + // -1: it was gone already when the program started (Wine forks through one that exits at once) + if (parent > 1 && parent_start >= 0 && ddh_start_time(parent) == parent_start) return (pid_t)parent; + if (anchor > 1 && anchor_start >= 0 && ddh_start_time(anchor) == anchor_start) return (pid_t)anchor; + return 0; +} + +// Signals the groups of the programs standing for group; returns how many took it. +static int ddh_signal_stand_ins(pid_t group, int sig, pid_t done) { + char dir[PATH_MAX]; + const char *real_dir = rewrite_path(DDH_GROUPS, dir, sizeof(dir)); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + char prefix[24], entries[4096]; + int plen = snprintf(prefix, sizeof(prefix), "%d.", (int)group); + int sent = 0; + long n; + while ((n = syscall(SYS_getdents64, fd, entries, sizeof(entries))) > 0) { + for (long off = 0; off < n;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + const char *name = entries + off + 19; + off += reclen ? reclen : n; + if (strncmp(name, prefix, (size_t)plen) != 0) continue; + int real = 0; + long start = 0; + if (sscanf(name + plen, "%d.%ld", &real, &start) != 2 || real <= 1) continue; + if (ddh_start_time(real) != start) { + call_orig_syscall(SYS_unlinkat, (unsigned long)fd, (unsigned long)name, 0, 0, 0, 0); // gone, or its pid reused + continue; + } + if (real == done || ddh_app_group(real)) continue; + if (syscall(SYS_kill, -real, sig) == 0) sent++; + } + } + syscall(SYS_close, fd); + return sent; +} + +static int ddh_kill_group(pid_t pid, int sig) { + pid_t group = pid == 0 ? ddh_logical_pgrp() : -pid; + pid_t own = pid == 0 ? getpgrp() : -pid; + // The caller's own group last: the signal may end the caller. + long ret = -1; + int err = ESRCH; + if (group != own && !ddh_app_group(group) && syscall(SYS_kill, -group, sig) == 0) ret = 0; + if (ddh_signal_stand_ins(group, sig, own) > 0) ret = 0; + if (syscall(SYS_kill, pid, sig) == 0) ret = 0; + else err = errno; + if (ret != 0) errno = err; + return (int)ret; +} + +// The kernel's parent of pid, from /proc//stat; 0 when unknown. +static pid_t ddh_proc_parent(pid_t pid) { + char path[48], stat[512]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, stat, sizeof(stat) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + stat[n] = 0; + char *p = strrchr(stat, ')'); + return p && p[1] == ' ' && p[2] && p[3] == ' ' ? (pid_t)atoi(p + 4) : 0; +} + +// Steam's "reaper SteamLaunch AppId=N -- ...", which runs a game's launch. +static int ddh_is_steam_reaper(pid_t pid) { + char path[48], cmd[128]; + snprintf(path, sizeof(path), "/proc/%d/cmdline", (int)pid); + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + long n = syscall(SYS_read, fd, cmd, sizeof(cmd) - 1); + syscall(SYS_close, fd); + if (n <= 0) return 0; + cmd[n] = 0; + size_t first = strlen(cmd); + return (size_t)n > first + 1 && strcmp(ddh_base(cmd), "reaper") == 0 && strcmp(cmd + first + 1, "SteamLaunch") == 0; +} + +static int ddh_descends_from(pid_t pid, pid_t ancestor) { + for (int depth = 0; pid > 1 && depth < 64; depth++) { + if (pid == ancestor) return 1; + pid_t up = ddh_logical_parent(pid); + pid = up > 0 ? up : ddh_proc_parent(pid); + } + return 0; +} + +// Steam ends a game by signalling its launch's reaper, which ends every process under it; the +// handed-off ones are not under it, so they (and the groups they lead) get the signal here. All are +// found before any is signalled: one that exits takes its place in the chain of parents with it. +// SIGINT goes as SIGTERM: Wine takes SIGINT for a console's Ctrl+C, which windowed programs ignore. +static void ddh_signal_reaper_tree(pid_t reaper, int sig) { + int dir = ddh_open_groups(0); + if (dir < 0) return; + pid_t found[256]; + int count = 0; + char entries[4096]; + long n; + while ((n = syscall(SYS_getdents64, dir, entries, sizeof(entries))) > 0) { + for (long off = 0; off < n;) { + unsigned short reclen; + memcpy(&reclen, entries + off + 16, sizeof(reclen)); + const char *name = entries + off + 19; + off += reclen ? reclen : n; + if (name[0] != 'P' || name[1] < '1' || name[1] > '9') continue; + pid_t pid = (pid_t)atoi(name + 1); + if (count < 256 && ddh_logical_parent(pid) > 0 && ddh_descends_from(pid, reaper)) found[count++] = pid; + } + } + syscall(SYS_close, dir); + for (int i = 0; i < count; i++) syscall(SYS_kill, -found[i], sig == SIGINT ? SIGTERM : sig); +} + +int killpg(int pgrp, int sig) { + if (pgrp < 0) { + errno = EINVAL; + return -1; + } + return kill(-pgrp, sig); +} + +int kill(pid_t pid, int sig) { + if (__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE) && pid > 0) { + // A child still handing its program off: the signal is for the program, which the forked + // child (stopped or killed by it) could no longer hand off or account for. Up to 3 s for the + // app's answer; a cold worker start takes well under one. + struct ddh_entry *claim = ddh_claiming(pid); + for (int i = 0; claim && i < 300 && __atomic_load_n(&claim->state, __ATOMIC_ACQUIRE) == DDH_CLAIMED; i++) { + struct timespec ts = {0, 10 * 1000 * 1000}; + nanosleep(&ts, NULL); + } + struct ddh_entry *e = ddh_find(pid); + if (e && __atomic_load_n(&e->state, __ATOMIC_ACQUIRE) == DDH_HANDED) pid = e->real; + } + // -1 is every process this one may signal, the app's own among them + if (sig != 0 && (pid == -1 || (pid <= 0 && ddh_app_group(pid == 0 ? getpgrp() : -pid)))) { + errno = EPERM; + return -1; + } + if (pid < -1 || pid == 0) { + if (sig != 0 && getenv("DD_HANDOFF_DEBUG")) { + char line[96]; + int len = snprintf(line, sizeof(line), "ddnatv handoff: %d kill group %d (stands for %d), %d\n", (int)getpid(), + pid == 0 ? (int)getpgrp() : (int)-pid, pid == 0 ? (int)ddh_logical_pgrp() : (int)-pid, sig); + if (len > 0) ddh_log(getenv("DD_HANDOFF_DEBUG"), line, (size_t)len); + } + return ddh_kill_group(pid, sig); + } + if (pid > 1 && (sig == SIGINT || sig == SIGTERM || sig == SIGKILL || sig == SIGHUP) && ddh_is_steam_reaper(pid)) + ddh_signal_reaper_tree(pid, sig); + if (sig != 0 && getenv("DD_HANDOFF_DEBUG")) { + char line[160], comm[32] = "?"; + int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/comm", O_RDONLY | O_CLOEXEC); + if (fd >= 0) { + long n = syscall(SYS_read, fd, comm, sizeof(comm) - 1); + if (n > 0) comm[n - 1] = 0; + syscall(SYS_close, fd); + } + int len = snprintf(line, sizeof(line), "ddnatv handoff: %d (%s) kill(%d, %d)\n", (int)getpid(), comm, (int)pid, sig); + if (len > 0) ddh_log(getenv("DD_HANDOFF_DEBUG"), line, (size_t)len); + } + return (int)syscall(SYS_kill, pid, sig); +} diff --git a/tools/nativeguest/hook/hardlinks.c b/tools/nativeguest/hook/hardlinks.c index 29cc5bc4b9..ffdc805673 100644 --- a/tools/nativeguest/hook/hardlinks.c +++ b/tools/nativeguest/hook/hardlinks.c @@ -445,6 +445,49 @@ static void load_app_ids(void) { __atomic_store_n(&g_app_uid, uid, __ATOMIC_RELAXED); } +// DDNATV_USER=app: this process and what it starts run as the app's own user, an ordinary user +// ("deck"), instead of root. Its ids, its files' owners and its peers' ids are then the kernel's, +// so programs that refuse root (Firefox, Chromium, makepkg) or compare owners need no exception. +// DDNATV_BECOME in a started program's environment ("root" for sudo, "app" for droiddeck-user) +// changes the user for that program and everything it starts (env.c). +static int g_user_mode = -1; + +static int app_user_mode(void) { + int mode = __atomic_load_n(&g_user_mode, __ATOMIC_RELAXED); + if (mode < 0) { + const char *value = getenv("DDNATV_USER"); + mode = value && strcmp(value, "app") == 0; + __atomic_store_n(&g_user_mode, mode, __ATOMIC_RELAXED); + } + return mode; +} + +static uid_t app_uid_now(void) { + if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids(); + return __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED); +} + +static gid_t app_gid_now(void) { + if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids(); + return __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED); +} + +// What the process calls its own user and group: root's, or the app's in app user mode +static uid_t presented_uid(void) { return app_user_mode() ? app_uid_now() : 0; } +static gid_t presented_gid(void) { return app_user_mode() ? app_gid_now() : 0; } + +// Whether a set*id() call may set these ids (-1 leaves one as it is): root may set any; an ordinary +// user only the one it has, as there is no other to have +static int may_set_ids(int group, uint32_t a, uint32_t b, uint32_t c) { + if (!app_user_mode()) return 1; + uint32_t own = group ? (uint32_t)app_gid_now() : (uint32_t)app_uid_now(); + uint32_t ids[3] = {a, b, c}; + for (int i = 0; i < 3; i++) { + if (ids[i] != UINT32_MAX && ids[i] != own) return 0; + } + return 1; +} + #define ANDROID_MEDIA_RW_GID ((gid_t)1023) static void present_owner_as_root(uid_t *uid, gid_t *gid) { @@ -452,6 +495,11 @@ static void present_owner_as_root(uid_t *uid, gid_t *gid) { uid_t app_uid = __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED); gid_t app_gid = __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED); if (app_uid == (uid_t)-1) return; + if (app_user_mode()) { + // Shared storage is the user's, as it is root's otherwise + if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = app_uid; + return; + } if (uid && *uid == app_uid) *uid = 0; if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = 0; if (gid && *gid == app_gid) *gid = 0; diff --git a/tools/nativeguest/hook/identity.c b/tools/nativeguest/hook/identity.c index ab48039d9d..f862f768f3 100644 --- a/tools/nativeguest/hook/identity.c +++ b/tools/nativeguest/hook/identity.c @@ -5,20 +5,28 @@ #ifndef DDNATV_HOST_TEST -// Fakeroot identity hooks for APT and DPKG to operate without superuser restrictions -uid_t getuid(void) { return 0; } -uid_t geteuid(void) { return 0; } -gid_t getgid(void) { return 0; } -gid_t getegid(void) { return 0; } +// Fakeroot identity hooks for APT and DPKG to operate without superuser restrictions. In app user +// mode (hardlinks.c) the ids are the app's and may only be "changed" to themselves, as the kernel +// allows an ordinary user; Android's seccomp filter refuses the real calls to apps. +uid_t getuid(void) { return presented_uid(); } +uid_t geteuid(void) { return presented_uid(); } +gid_t getgid(void) { return presented_gid(); } +gid_t getegid(void) { return presented_gid(); } -int setuid(uid_t uid) { (void)uid; return 0; } -int seteuid(uid_t uid) { (void)uid; return 0; } -int setgid(gid_t gid) { (void)gid; return 0; } -int setegid(gid_t gid) { (void)gid; return 0; } -int setreuid(uid_t ruid, uid_t euid) { (void)ruid; (void)euid; return 0; } -int setregid(gid_t rgid, gid_t egid) { (void)rgid; (void)egid; return 0; } -int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (void)suid; return 0; } -int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; } +static int set_own_ids(int group, uint32_t a, uint32_t b, uint32_t c) { + if (may_set_ids(group, a, b, c)) return 0; + errno = EPERM; + return -1; +} + +int setuid(uid_t uid) { return set_own_ids(0, uid, -1, -1); } +int seteuid(uid_t uid) { return set_own_ids(0, uid, -1, -1); } +int setgid(gid_t gid) { return set_own_ids(1, gid, -1, -1); } +int setegid(gid_t gid) { return set_own_ids(1, gid, -1, -1); } +int setreuid(uid_t ruid, uid_t euid) { return set_own_ids(0, ruid, euid, -1); } +int setregid(gid_t rgid, gid_t egid) { return set_own_ids(1, rgid, egid, -1); } +int setresuid(uid_t ruid, uid_t euid, uid_t suid) { return set_own_ids(0, ruid, euid, suid); } +int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { return set_own_ids(1, rgid, egid, sgid); } int getgroups(int size, gid_t list[]) { if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1; @@ -32,8 +40,14 @@ int __getgroups_chk(int size, gid_t list[], size_t listlen) { if (size > 0 && (size_t)size * sizeof(gid_t) > listlen) __chk_fail(); return getgroups(size, list); } -int setgroups(size_t size, const gid_t *list) { (void)size; (void)list; return 0; } -int initgroups(const char *user, gid_t group) { (void)user; (void)group; return 0; } +int setgroups(size_t size, const gid_t *list) { + (void)size; + (void)list; + if (!app_user_mode()) return 0; + errno = EPERM; + return -1; +} +int initgroups(const char *user, gid_t group) { (void)user; return setgroups(1, &group); } int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups) { (void)user; @@ -658,12 +672,60 @@ struct spwd *getspnam(const char *name) { } #endif /* !DDNATV_HOST_TEST */ +// In app user mode the app's ids are an ordinary user, "deck", whose home is root's (where the +// session keeps everything). The rootfs lists the app's uid as root's for proot, so these come first. +#define DDNATV_APP_USER "deck" + +static int app_user_passwd(const char *name, uid_t uid, int by_name, struct passwd *pwd, char *buf, size_t buflen) { + if (!app_user_mode()) return ENOENT; + if (by_name ? (!name || strcmp(name, DDNATV_APP_USER) != 0) : uid != app_uid_now()) return ENOENT; + static const char *const fields[] = {DDNATV_APP_USER, "x", "DroidDeck", "/root", "/bin/bash"}; + size_t need = 0; + for (size_t i = 0; i < 5; i++) need += strlen(fields[i]) + 1; + if (!pwd || !buf || need > buflen) return ERANGE; + char *out[5]; + char *cursor = buf; + for (size_t i = 0; i < 5; i++) { + size_t len = strlen(fields[i]) + 1; + memcpy(cursor, fields[i], len); + out[i] = cursor; + cursor += len; + } + pwd->pw_name = out[0]; + pwd->pw_passwd = out[1]; + pwd->pw_gecos = out[2]; + pwd->pw_dir = out[3]; + pwd->pw_shell = out[4]; + pwd->pw_uid = app_uid_now(); + pwd->pw_gid = app_gid_now(); + return 0; +} + +static int app_user_group(const char *name, gid_t gid, int by_name, struct group *grp, char *buf, size_t buflen) { + if (!app_user_mode()) return ENOENT; + if (by_name ? (!name || strcmp(name, DDNATV_APP_USER) != 0) : gid != app_gid_now()) return ENOENT; + size_t ptrs = 2 * sizeof(char *); + if (!grp || !buf || ptrs + sizeof(DDNATV_APP_USER) + 2 > buflen) return ERANGE; + char **members = (char **)buf; + char *cursor = buf + ptrs; + memcpy(cursor, DDNATV_APP_USER, sizeof(DDNATV_APP_USER)); + grp->gr_name = cursor; + cursor += sizeof(DDNATV_APP_USER); + memcpy(cursor, "x", 2); + grp->gr_passwd = cursor; + members[0] = NULL; + grp->gr_mem = members; + grp->gr_gid = app_gid_now(); + return 0; +} + static struct group s_grp_storage; static char s_grp_buf[2048]; static struct passwd s_pwd_storage; static char s_pwd_buf[2048]; struct group *DDNATV_NSS_SYM(getgrgid)(gid_t gid) { + if (app_user_group(NULL, gid, 0, &s_grp_storage, s_grp_buf, sizeof(s_grp_buf)) == 0) return &s_grp_storage; #ifndef DDNATV_HOST_TEST static struct group *(*orig_getgrgid)(gid_t) = NULL; if (!orig_getgrgid) orig_getgrgid = (struct group *(*)(gid_t))dlsym(RTLD_NEXT, "getgrgid"); @@ -677,6 +739,7 @@ struct group *DDNATV_NSS_SYM(getgrgid)(gid_t gid) { } struct group *DDNATV_NSS_SYM(getgrnam)(const char *name) { + if (app_user_group(name, 0, 1, &s_grp_storage, s_grp_buf, sizeof(s_grp_buf)) == 0) return &s_grp_storage; #ifndef DDNATV_HOST_TEST static struct group *(*orig_getgrnam)(const char *) = NULL; if (!orig_getgrnam) orig_getgrnam = (struct group *(*)(const char *))dlsym(RTLD_NEXT, "getgrnam"); @@ -690,6 +753,11 @@ struct group *DDNATV_NSS_SYM(getgrnam)(const char *name) { } int DDNATV_NSS_SYM(getgrgid_r)(gid_t gid, struct group *grp, char *buf, size_t buflen, struct group **result) { + int own = app_user_group(NULL, gid, 0, grp, buf, buflen); + if (own != ENOENT) { + if (result) *result = own == 0 ? grp : NULL; + return own; + } #ifndef DDNATV_HOST_TEST static int (*orig_getgrgid_r)(gid_t, struct group *, char *, size_t, struct group **) = NULL; if (!orig_getgrgid_r) orig_getgrgid_r = (int (*)(gid_t, struct group *, char *, size_t, struct group **))dlsym(RTLD_NEXT, "getgrgid_r"); @@ -714,6 +782,11 @@ int DDNATV_NSS_SYM(getgrgid_r)(gid_t gid, struct group *grp, char *buf, size_t b } int DDNATV_NSS_SYM(getgrnam_r)(const char *name, struct group *grp, char *buf, size_t buflen, struct group **result) { + int own = app_user_group(name, 0, 1, grp, buf, buflen); + if (own != ENOENT) { + if (result) *result = own == 0 ? grp : NULL; + return own; + } #ifndef DDNATV_HOST_TEST static int (*orig_getgrnam_r)(const char *, struct group *, char *, size_t, struct group **) = NULL; if (!orig_getgrnam_r) orig_getgrnam_r = (int (*)(const char *, struct group *, char *, size_t, struct group **))dlsym(RTLD_NEXT, "getgrnam_r"); @@ -756,6 +829,7 @@ static struct passwd *present_privsep_user_as_root(struct passwd *pwd) { } struct passwd *DDNATV_NSS_SYM(getpwuid)(uid_t uid) { + if (app_user_passwd(NULL, uid, 0, &s_pwd_storage, s_pwd_buf, sizeof(s_pwd_buf)) == 0) return &s_pwd_storage; #ifndef DDNATV_HOST_TEST static struct passwd *(*orig_getpwuid)(uid_t) = NULL; if (!orig_getpwuid) orig_getpwuid = (struct passwd *(*)(uid_t))dlsym(RTLD_NEXT, "getpwuid"); @@ -769,6 +843,7 @@ struct passwd *DDNATV_NSS_SYM(getpwuid)(uid_t uid) { } struct passwd *DDNATV_NSS_SYM(getpwnam)(const char *name) { + if (app_user_passwd(name, 0, 1, &s_pwd_storage, s_pwd_buf, sizeof(s_pwd_buf)) == 0) return &s_pwd_storage; #ifndef DDNATV_HOST_TEST static struct passwd *(*orig_getpwnam)(const char *) = NULL; if (!orig_getpwnam) orig_getpwnam = (struct passwd *(*)(const char *))dlsym(RTLD_NEXT, "getpwnam"); @@ -782,6 +857,11 @@ struct passwd *DDNATV_NSS_SYM(getpwnam)(const char *name) { } int DDNATV_NSS_SYM(getpwuid_r)(uid_t uid, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) { + int own = app_user_passwd(NULL, uid, 0, pwd, buf, buflen); + if (own != ENOENT) { + if (result) *result = own == 0 ? pwd : NULL; + return own; + } #ifndef DDNATV_HOST_TEST static int (*orig_getpwuid_r)(uid_t, struct passwd *, char *, size_t, struct passwd **) = NULL; if (!orig_getpwuid_r) orig_getpwuid_r = (int (*)(uid_t, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, "getpwuid_r"); @@ -810,6 +890,11 @@ int DDNATV_NSS_SYM(getpwuid_r)(uid_t uid, struct passwd *pwd, char *buf, size_t } int DDNATV_NSS_SYM(getpwnam_r)(const char *name, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) { + int own = app_user_passwd(name, 0, 1, pwd, buf, buflen); + if (own != ENOENT) { + if (result) *result = own == 0 ? pwd : NULL; + return own; + } #ifndef DDNATV_HOST_TEST static int (*orig_getpwnam_r)(const char *, struct passwd *, char *, size_t, struct passwd **) = NULL; if (!orig_getpwnam_r) orig_getpwnam_r = (int (*)(const char *, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, "getpwnam_r"); diff --git a/tools/nativeguest/hook/kept.c b/tools/nativeguest/hook/kept.c new file mode 100644 index 0000000000..a25b3813d4 --- /dev/null +++ b/tools/nativeguest/hook/kept.c @@ -0,0 +1,225 @@ +// Part of libddnatv-hook.so, included by ddnatv-hook.c before privileged.c, and of the bionic +// runtime's exec shim (tools/bionic-runtime/handoff.c): the descriptors close(), close_range() and +// closefrom() leave open. + +// The ARM translator of x86 devices and emulators (ndk_translation, houdini) keeps memory files of +// its own open in the process (ndk_translation at descriptor 3) and needs them whenever it +// translates more code: a program that closes every descriptor it did not open (sshd at start, +// closefrom(3)) made it abort later ("CHECK failed" in mmap_posix.cc). Its memory files open when +// the hook starts survive close(), close_range() and closefrom(); phones that run ARM code +// themselves have none. +#define DDNATV_MAX_KEPT_FDS 12 +static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending +static int g_kept_fd_count = 0; +// Of those, the ones also kept from close-on-exec: a worker process's binder fds (hook/handoff.c), +// which must outlive the program's own execs. +static int g_cloexec_kept_fds[8]; // ascending +static int g_cloexec_kept_count = 0; + +// The list can change while the program runs (hook/handoff.c keeps and lets go of its own fds): odd +// while a change is under way, which kept_change_begin() and kept_change_end() bracket. Readers take +// a whole copy (kept_snapshot()), so that another thread's close() or close_range() never works +// from a list half moved, which could close a kept fd. +static unsigned g_kept_seq; +static pthread_mutex_t g_kept_lock = PTHREAD_MUTEX_INITIALIZER; +static __thread uint64_t t_kept_mask; + +// A thread that split its descriptor table from the others' (close_range() with +// CLOSE_RANGE_UNSHARE) goes on with a copy of the list made at the split, which only it reads and +// changes: the shared list keeps describing the other threads' table, so a kept fd this thread's +// program takes over (a dup2() onto the parent's pidfd) stays kept there. A child it forks takes the +// copy over as its list (kept_forked()). +static __thread int t_kept_split; +static __thread int t_kept_fds[DDNATV_MAX_KEPT_FDS]; +static __thread int t_kept_count; +// In a process forked from such a thread: numbers published for the shared table (the handoff table's) +// may name other files here, or none. +static int g_kept_split; + +static int kept_snapshot(int *out) { + if (t_kept_split) { + for (int i = 0; i < t_kept_count; i++) out[i] = t_kept_fds[i]; + return t_kept_count; + } + for (;;) { + unsigned seq = __atomic_load_n(&g_kept_seq, __ATOMIC_ACQUIRE); + if (seq & 1) continue; + int n = __atomic_load_n(&g_kept_fd_count, __ATOMIC_RELAXED); + if (n > DDNATV_MAX_KEPT_FDS) n = DDNATV_MAX_KEPT_FDS; + for (int i = 0; i < n; i++) out[i] = __atomic_load_n(&g_kept_fds[i], __ATOMIC_RELAXED); + __atomic_thread_fence(__ATOMIC_ACQUIRE); + if (__atomic_load_n(&g_kept_seq, __ATOMIC_RELAXED) == seq) return n; + } +} + +static void kept_fork_prepare(void) { pthread_mutex_lock(&g_kept_lock); } +static void kept_fork_done(void) { pthread_mutex_unlock(&g_kept_lock); } +static void kept_register_fork(void) { pthread_atfork(kept_fork_prepare, kept_fork_done, kept_fork_done); } + +// Before anything takes g_kept_lock: a fork() in another thread then waits for it to be let go. +static void kept_register_once(void) { + static pthread_once_t once = PTHREAD_ONCE_INIT; + pthread_once(&once, kept_register_fork); +} + +// Every signal blocked meanwhile, so that no handler on this thread reads the list half changed (it +// would wait for the change forever) or changes it too; a fork() waits for the change to end, so a +// child never starts with one under way. +static void kept_change_begin(void) { + kept_register_once(); + uint64_t all = ~0ull; + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&t_kept_mask, 8, 0, 0); + pthread_mutex_lock(&g_kept_lock); + __atomic_store_n(&g_kept_seq, g_kept_seq + 1, __ATOMIC_RELAXED); + __atomic_thread_fence(__ATOMIC_RELEASE); +} + +static void kept_change_end(void) { + __atomic_store_n(&g_kept_seq, g_kept_seq + 1, __ATOMIC_RELEASE); + pthread_mutex_unlock(&g_kept_lock); + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&t_kept_mask, 0, 8, 0, 0); +} + +static int kept_any(void) { + return t_kept_split ? t_kept_count : __atomic_load_n(&g_kept_fd_count, __ATOMIC_RELAXED); +} + +// The process's threads (/proc/self/stat), or 0 when it cannot be read. +static int kept_threads(void) { + char buf[512]; + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc/self/stat", + O_RDONLY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + long n = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)buf, sizeof(buf) - 1, 0, 0, 0); + call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0); + if (n <= 0) return 0; + buf[n] = 0; + char *p = strrchr(buf, ')'); + // after the name: state, then 16 fields to num_threads + for (int field = 0; p && field < 18; field++) p = strchr(p + 1, ' '); + return p ? atoi(p + 1) : 0; +} + +// The calling thread's table split by split() (0, or -1 with errno), with the list copied for it in +// the same step: no keep or let-go of another thread falls between the copy and the split. A process +// with one thread keeps one table (the system copies only a shared one), and so one list. Threads that +// a thread with a table of its own starts later share that table but not its copy: not followed. +static int kept_split(int (*split)(void)) { + if (t_kept_split) return split(); + kept_register_once(); + uint64_t all = ~0ull, mask = 0; + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&all, (unsigned long)&mask, 8, 0, 0); + pthread_mutex_lock(&g_kept_lock); + int shared = kept_threads() != 1; + int r = split(); + int saved = errno; + if (r == 0 && shared) { + int n = g_kept_fd_count; + for (int i = 0; i < n; i++) t_kept_fds[i] = g_kept_fds[i]; + t_kept_count = n; + t_kept_split = 1; + } + pthread_mutex_unlock(&g_kept_lock); + call_orig_syscall(SYS_rt_sigprocmask, SIG_SETMASK, (unsigned long)&mask, 0, 8, 0, 0); + errno = saved; + return r; +} + +// In a forked child, whose only thread is the one that forked: a split thread's table is the child's. +static void kept_forked(void) { + if (!t_kept_split) return; + for (int i = 0; i < t_kept_count; i++) g_kept_fds[i] = t_kept_fds[i]; + g_kept_fd_count = t_kept_count; + t_kept_split = 0; + g_kept_split = 1; +} + +static int is_kept_fd(int fd) { + int kept[DDNATV_MAX_KEPT_FDS]; + int n = kept_snapshot(kept); + for (int i = 0; i < n; i++) { + if (kept[i] == fd) return 1; + } + return 0; +} + +// Closes under way (close(), close_range()), counted by the epoch they began in: one that looked at +// the list before a fd was added to it may still close that fd. A thread that makes and keeps a fd +// while others run (hook/handoff.c's table) moves the epoch on afterwards, waits for the closes of +// the one before (kept_settle()), and only then trusts the fd to be its own still. +static unsigned g_close_epoch; +// Per epoch, generation << 32 | count, one word: every change is one compare-and-swap, so a fork from +// a handler that interrupted a close's begin or end never splits one in two. A forked child moves the +// generation on and starts from none (kept_close_forked()): an end whose generation is gone counts +// nothing, and a begin whose swap failed takes the child's. +static uint64_t g_closers[2]; + +static void kept_close_end(uint64_t ticket); + +// The close's ticket: generation << 1 | epoch +static uint64_t kept_close_begin(void) { + for (;;) { + unsigned epoch = __atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1; + uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST); + if (!__atomic_compare_exchange_n(&g_closers[epoch], &word, word + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) + continue; + uint64_t ticket = (word >> 32) << 1 | epoch; + if ((__atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1) == epoch) return ticket; + kept_close_end(ticket); // the epoch moved on meanwhile: counted in the new one instead + } +} + +static void kept_close_end(uint64_t ticket) { + unsigned epoch = (unsigned)(ticket & 1); + uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST); + while ((word >> 32) == (ticket >> 1) && (word & 0xffffffffu) != 0 && + !__atomic_compare_exchange_n(&g_closers[epoch], &word, word - 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { + } +} + +// In a forked child: the closes the parent's threads were making are not the child's to wait for. +// (The forking thread's own, a close a handler interrupted to fork, then goes uncounted.) +static void kept_close_forked(void) { + for (int epoch = 0; epoch < 2; epoch++) { + uint64_t word = __atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST); + __atomic_store_n(&g_closers[epoch], ((word >> 32) + 1) << 32, __ATOMIC_SEQ_CST); + } +} + +static int kept_drained(unsigned epoch) { + for (int i = 0; i < 1000; i++) { + if ((__atomic_load_n(&g_closers[epoch], __ATOMIC_SEQ_CST) & 0xffffffffu) == 0) return 1; + struct timespec pause = {0, 1000 * 1000}; + nanosleep(&pause, NULL); + } + return 0; +} + +// 1 once every close that began before now has ended; 0 after a second without (one interrupted by +// a signal whose handler is the caller, say): then nothing it made since can be trusted. The epoch +// moves on only once the closes of the one before it are over too, so the two counts never mix one +// that is still under way from an earlier settle that gave up with the current one. +static int kept_settle(void) { + unsigned current = __atomic_load_n(&g_close_epoch, __ATOMIC_SEQ_CST) & 1; + if (!kept_drained(current ^ 1)) return 0; + unsigned old = __atomic_fetch_add(&g_close_epoch, 1, __ATOMIC_SEQ_CST) & 1; + return kept_drained(old); +} + +// Calls fn for each part of [first, last] that leaves out the descriptors in kept (ascending); +// the first nonzero answer of fn is returned, else 0. +static int for_each_range_without(unsigned int first, unsigned int last, const int *kept, int nkept, + int (*fn)(unsigned int, unsigned int, void *), void *arg) { + unsigned int from = first; + for (int i = 0; i < nkept && from <= last; i++) { + if (kept[i] < 0 || (unsigned int)kept[i] < from || (unsigned int)kept[i] > last) continue; + unsigned int k = (unsigned int)kept[i]; + if (k > from) { + int r = fn(from, k - 1, arg); + if (r != 0) return r; + } + if (k == last) return 0; + from = k + 1; + } + return from <= last ? fn(from, last, arg) : 0; +} diff --git a/tools/nativeguest/hook/net.c b/tools/nativeguest/hook/net.c index 69260a4243..de2459b74b 100644 --- a/tools/nativeguest/hook/net.c +++ b/tools/nativeguest/hook/net.c @@ -240,22 +240,38 @@ static void clear_dns_redirect(int fd) { int close(int fd) { static int (*orig_close)(int) = NULL; if (!orig_close) orig_close = (int (*)(int))dlsym(RTLD_NEXT, "close"); + uint64_t ticket = kept_close_begin(); // The ARM translator's memory file (privileged.c): left open, as if it were closed - if (g_kept_fd_count > 0 && is_kept_fd(fd)) return 0; + if (kept_any() > 0 && is_kept_fd(fd)) { + kept_close_end(ticket); + return 0; + } clear_dns_redirect(fd); set_chosen_port_fd(fd, 0); forget_proc_root_fd(fd); - return orig_close ? orig_close(fd) : -1; + int r = orig_close ? orig_close(fd) : -1; + int saved = errno; + kept_close_end(ticket); + errno = saved; + return r; } int dup2(int oldfd, int newfd) { static int (*orig_dup2)(int, int) = NULL; if (!orig_dup2) orig_dup2 = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2"); + int pidfd_from = -1, locked = 0; if (oldfd != newfd) { + // the bookkeeping's own locks before the pidfd's: its holder waits on nothing else clear_dns_redirect(newfd); set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd)); + locked = ddh_parent_pidfd_lock(newfd); + pidfd_from = ddh_parent_pidfd_moves(newfd); } int ret = orig_dup2 ? orig_dup2(oldfd, newfd) : -1; + ddh_parent_pidfd_settle(pidfd_from, ret >= 0); + int saved = errno; + ddh_parent_pidfd_unlock(locked); + errno = saved; if (ret >= 0) copy_proc_root_fd(oldfd, ret); return ret; } @@ -263,11 +279,19 @@ int dup2(int oldfd, int newfd) { int dup3(int oldfd, int newfd, int flags) { static int (*orig_dup3)(int, int, int) = NULL; if (!orig_dup3) orig_dup3 = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3"); + int pidfd_from = -1, locked = 0; if (oldfd != newfd) { + // the bookkeeping's own locks before the pidfd's: its holder waits on nothing else clear_dns_redirect(newfd); set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd)); + locked = ddh_parent_pidfd_lock(newfd); + pidfd_from = ddh_parent_pidfd_moves(newfd); } int ret = orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1; + ddh_parent_pidfd_settle(pidfd_from, ret >= 0); + int saved = errno; + ddh_parent_pidfd_unlock(locked); + errno = saved; if (ret >= 0) copy_proc_root_fd(oldfd, ret); return ret; } diff --git a/tools/nativeguest/hook/paths.c b/tools/nativeguest/hook/paths.c index 616098df04..74983a7552 100644 --- a/tools/nativeguest/hook/paths.c +++ b/tools/nativeguest/hook/paths.c @@ -234,6 +234,13 @@ static int is_mapped_guest_path(const char *path) { return 0; } +static int is_identity_bound_path(const char *path) { + if (!path || path[0] != '/') return 0; + for (int i = 0; i < g_nbinds; i++) + if (g_binds[i].identity && is_path_prefix(path, g_binds[i].dst, g_binds[i].dst_len)) return 1; + return 0; +} + // Android's own mounts and files, which must never be redirected into the rootfs. // `path` starts with '/'; a prefix can only match when its second character does. static int is_android_host_path(const char *path) { @@ -968,6 +975,20 @@ static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int return best->dst_len + rest; } +static char *guest_path_of_allocated_mount_source(char *res) { + size_t len = strlen(res); + char tmp[PATH_MAX]; + if (len >= sizeof(tmp)) return res; + memcpy(tmp, res, len + 1); + int converted = 0; + size_t n = guest_path_of_mount_source(tmp, len, sizeof(tmp), &converted); + if (!converted) return res; + char *grown = realloc(res, n + 1); + if (!grown) return res; + memcpy(grown, tmp, n + 1); + return grown; +} + static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) { if (ret <= 0) return ret; if ((size_t)ret < bufsiz) { diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 7abb578071..14ef7c6654 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -4,41 +4,6 @@ // Calls an app may not make (chown, mknod, capabilities, prctl, landlock, seccomp, namespaces, // close_range) and the generic syscall() entry point. -// The ARM translator of x86 devices and emulators (ndk_translation, houdini) keeps memory files of -// its own open in the process (ndk_translation at descriptor 3) and needs them whenever it -// translates more code: a program that closes every descriptor it did not open (sshd at start, -// closefrom(3)) made it abort later ("CHECK failed" in mmap_posix.cc). Its memory files open when -// the hook starts survive close(), close_range() and closefrom(); phones that run ARM code -// themselves have none. -#define DDNATV_MAX_KEPT_FDS 4 -static int g_kept_fds[DDNATV_MAX_KEPT_FDS]; // ascending -static int g_kept_fd_count = 0; - -static int is_kept_fd(int fd) { - for (int i = 0; i < g_kept_fd_count; i++) { - if (g_kept_fds[i] == fd) return 1; - } - return 0; -} - -// Calls fn for each part of [first, last] that leaves out the descriptors in kept (ascending); -// the first nonzero answer of fn is returned, else 0. -static int for_each_range_without(unsigned int first, unsigned int last, const int *kept, int nkept, - int (*fn)(unsigned int, unsigned int, void *), void *arg) { - unsigned int from = first; - for (int i = 0; i < nkept && from <= last; i++) { - if (kept[i] < 0 || (unsigned int)kept[i] < from || (unsigned int)kept[i] > last) continue; - unsigned int k = (unsigned int)kept[i]; - if (k > from) { - int r = fn(from, k - 1, arg); - if (r != 0) return r; - } - if (k == last) return 0; - from = k + 1; - } - return from <= last ? fn(from, last, arg) : 0; -} - #ifndef DDNATV_HOST_TEST // ndk_translation's file is "/memfd:child"; any memory file counts in a process whose executable is @@ -374,6 +339,13 @@ __asm__(".globl setrlimit64\n" ".set setrlimit64, setrlimit\n"); #endif #endif +#ifndef CLONE_PIDFD +#define CLONE_PIDFD 0x00001000 +#endif +#ifndef P_PIDFD +#define P_PIDFD 3 +#endif + #ifndef SECCOMP_SET_MODE_STRICT #define SECCOMP_SET_MODE_STRICT 0 #endif @@ -438,20 +410,67 @@ int setns(int fd, int nstype) { #ifndef CLOSE_RANGE_CLOEXEC #define CLOSE_RANGE_CLOEXEC (1U << 2) #endif +#ifndef CLOSE_RANGE_UNSHARE +#define CLOSE_RANGE_UNSHARE (1U << 1) +#endif static int close_range_all(unsigned int first, unsigned int last, int flags); +// Tests only ("IN OUT TID"): before each part it closes, once it has looked at the kept fds, thread +// TID's close_range() writes a byte to OUT and waits for one on IN, as a thread descheduled there +// would. +static void close_range_test_gate(void) { + const char *gate = getenv("DDNATV_TEST_CLOSE_RANGE_GATE"); + int in, out, tid; + if (!gate || sscanf(gate, "%d %d %d", &in, &out, &tid) != 3 || tid != (int)syscall(SYS_gettid)) return; + int saved = errno; + char c = 1; + syscall(SYS_write, out, &c, 1); + while (syscall(SYS_read, in, &c, 1) < 0 && errno == EINTR) {} + errno = saved; +} + static int close_range_part(unsigned int first, unsigned int last, void *flags) { + close_range_test_gate(); return close_range_all(first, last, *(int *)flags); } +// The system call itself on the one number no fd has (close_range_all() would emulate a missing call +// by closing fds) +static int close_range_unshare(void) { + static long (*raw_syscall)(long, ...) = NULL; + if (!raw_syscall) raw_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall"); + if (!raw_syscall) { + errno = ENOSYS; + return -1; + } + return raw_syscall(__NR_close_range, ~0U, ~0U, CLOSE_RANGE_UNSHARE) == 0 ? 0 : -1; +} + +static int close_range_kept(unsigned int first, unsigned int last, int flags) { + // The table is unshared first, once, even when every fd in the range is kept, and this thread + // goes on with its own copy of the kept list (kept_split()). Without the system call, it is + // emulated where nothing is kept, and refused otherwise. + if (flags & CLOSE_RANGE_UNSHARE) { + if (kept_split(close_range_unshare) == 0) flags &= ~CLOSE_RANGE_UNSHARE; + else if (errno != ENOSYS || kept_any() > 0) return -1; + } + // Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open + int snapshot[DDNATV_MAX_KEPT_FDS]; + const int *kept = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_fds : snapshot; + int kept_count = (flags & CLOSE_RANGE_CLOEXEC) ? g_cloexec_kept_count : kept_snapshot(snapshot); + if (kept_count == 0) return close_range_part(first, last, &flags); + return for_each_range_without(first, last, kept, kept_count, close_range_part, &flags); +} + int close_range(unsigned int first, unsigned int last, int flags) { if (!(flags & CLOSE_RANGE_CLOEXEC)) forget_proc_root_range(first, last); - // Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open - if (g_kept_fd_count > 0 && !(flags & CLOSE_RANGE_CLOEXEC)) { - return for_each_range_without(first, last, g_kept_fds, g_kept_fd_count, close_range_part, &flags); - } - return close_range_all(first, last, flags); + uint64_t ticket = kept_close_begin(); + int r = close_range_kept(first, last, flags); + int saved = errno; + kept_close_end(ticket); + errno = saved; + return r; } // glibc's closefrom() makes the close_range system call itself, past the function above @@ -529,7 +548,7 @@ static long nested_path_syscall(long number, unsigned long dirfd, unsigned long static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) { long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0); - if (rc == 0) *real = *effective = *saved = 0; + if (rc == 0 && !app_user_mode()) *real = *effective = *saved = 0; return rc; } @@ -627,6 +646,20 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_clone + if (number == __NR_clone && (arg1 & CLONE_PIDFD)) { + errno = EINVAL; + return -1; + } +#endif + +#ifdef __NR_waitid + if (number == __NR_waitid && (int)arg1 == P_PIDFD) { + errno = EINVAL; + return -1; + } +#endif + #ifdef __NR_clone3 if (number == __NR_clone3) { errno = ENOSYS; @@ -821,82 +854,82 @@ long syscall(long number, ...) { #endif #if defined(__NR_setresuid) - if (number == __NR_setresuid) return 0; + if (number == __NR_setresuid) return (long)setresuid((uid_t)arg1, (uid_t)arg2, (uid_t)arg3); #endif #if defined(__NR_setresuid32) - if (number == __NR_setresuid32) return 0; + if (number == __NR_setresuid32) return (long)setresuid((uid_t)arg1, (uid_t)arg2, (uid_t)arg3); #endif #if defined(__NR_setresgid) - if (number == __NR_setresgid) return 0; + if (number == __NR_setresgid) return (long)setresgid((gid_t)arg1, (gid_t)arg2, (gid_t)arg3); #endif #if defined(__NR_setresgid32) - if (number == __NR_setresgid32) return 0; + if (number == __NR_setresgid32) return (long)setresgid((gid_t)arg1, (gid_t)arg2, (gid_t)arg3); #endif #if defined(__NR_setuid) - if (number == __NR_setuid) return 0; + if (number == __NR_setuid) return (long)setuid((uid_t)arg1); #endif #if defined(__NR_setuid32) - if (number == __NR_setuid32) return 0; + if (number == __NR_setuid32) return (long)setuid((uid_t)arg1); #endif #if defined(__NR_setgid) - if (number == __NR_setgid) return 0; + if (number == __NR_setgid) return (long)setgid((gid_t)arg1); #endif #if defined(__NR_setgid32) - if (number == __NR_setgid32) return 0; + if (number == __NR_setgid32) return (long)setgid((gid_t)arg1); #endif #if defined(__NR_setreuid) - if (number == __NR_setreuid) return 0; + if (number == __NR_setreuid) return (long)setreuid((uid_t)arg1, (uid_t)arg2); #endif #if defined(__NR_setreuid32) - if (number == __NR_setreuid32) return 0; + if (number == __NR_setreuid32) return (long)setreuid((uid_t)arg1, (uid_t)arg2); #endif #if defined(__NR_setregid) - if (number == __NR_setregid) return 0; + if (number == __NR_setregid) return (long)setregid((gid_t)arg1, (gid_t)arg2); #endif #if defined(__NR_setregid32) - if (number == __NR_setregid32) return 0; + if (number == __NR_setregid32) return (long)setregid((gid_t)arg1, (gid_t)arg2); #endif #if defined(__NR_setgroups) - if (number == __NR_setgroups) return 0; + if (number == __NR_setgroups) return (long)setgroups((size_t)arg1, (const gid_t *)arg2); #endif #if defined(__NR_setgroups32) - if (number == __NR_setgroups32) return 0; + if (number == __NR_setgroups32) return (long)setgroups((size_t)arg1, (const gid_t *)arg2); #endif #if defined(__NR_setfsuid) - if (number == __NR_setfsuid) return 0; + if (number == __NR_setfsuid) return (long)presented_uid(); #endif #if defined(__NR_setfsuid32) - if (number == __NR_setfsuid32) return 0; + if (number == __NR_setfsuid32) return (long)presented_uid(); #endif #if defined(__NR_setfsgid) - if (number == __NR_setfsgid) return 0; + if (number == __NR_setfsgid) return (long)presented_gid(); #endif #if defined(__NR_setfsgid32) - if (number == __NR_setfsgid32) return 0; + if (number == __NR_setfsgid32) return (long)presented_gid(); #endif #if defined(__NR_getuid) - if (number == __NR_getuid) return 0; + if (number == __NR_getuid) return (long)presented_uid(); #endif #if defined(__NR_getuid32) - if (number == __NR_getuid32) return 0; + if (number == __NR_getuid32) return (long)presented_uid(); #endif #if defined(__NR_geteuid) - if (number == __NR_geteuid) return 0; + if (number == __NR_geteuid) return (long)presented_uid(); #endif #if defined(__NR_geteuid32) - if (number == __NR_geteuid32) return 0; + if (number == __NR_geteuid32) return (long)presented_uid(); #endif #if defined(__NR_getgid) - if (number == __NR_getgid) return 0; + if (number == __NR_getgid) return (long)presented_gid(); #endif #if defined(__NR_getgid32) - if (number == __NR_getgid32) return 0; + if (number == __NR_getgid32) return (long)presented_gid(); #endif #if defined(__NR_getegid) - if (number == __NR_getegid) return 0; + if (number == __NR_getegid) return (long)presented_gid(); #endif #if defined(__NR_getegid32) - if (number == __NR_getegid32) return 0; + if (number == __NR_getegid32) return (long)presented_gid(); #endif #if defined(__NR_getresuid) if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index f44604f9c8..4b7d2bbb0f 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -36,6 +36,8 @@ static void init_ddnatv_hook(void) { } } } + // The SIGSYS handler answers id calls with these and cannot look them up itself + if (app_user_mode()) load_app_ids(); ddnatv_load_binds(getenv("DDNATV_BINDS"), getenv("DDNATV_BINDS_KERNEL")); const char *mount_table = getenv("DDNATV_MOUNTINFO"); if (mount_table && mount_table[0] == '/' && strlen(mount_table) < sizeof(g_mount_table)) diff --git a/tools/nativeguest/hook/signals.c b/tools/nativeguest/hook/signals.c index 0b5765070d..4ed9522da4 100644 --- a/tools/nativeguest/hook/signals.c +++ b/tools/nativeguest/hook/signals.c @@ -33,6 +33,27 @@ static void remember_app_sigsys(const struct sigaction *act, struct sigaction *o } } +#if defined(__aarch64__) +// An id change the filter refused: root's succeed, an ordinary user's only to the ids it has (as in +// identity.c). setfsuid() and setfsgid() return the id they had. +static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_val) { + if (!app_user_mode()) return ret_val; + uint32_t a = (uint32_t)regs[0], b = (uint32_t)regs[1], c = (uint32_t)regs[2]; + switch (nr) { + case 146: return may_set_ids(0, a, UINT32_MAX, UINT32_MAX) ? 0 : -EPERM; // setuid + case 144: return may_set_ids(1, a, UINT32_MAX, UINT32_MAX) ? 0 : -EPERM; // setgid + case 145: return may_set_ids(0, a, b, UINT32_MAX) ? 0 : -EPERM; // setreuid + case 143: return may_set_ids(1, a, b, UINT32_MAX) ? 0 : -EPERM; // setregid + case 147: return may_set_ids(0, a, b, c) ? 0 : -EPERM; // setresuid + case 149: return may_set_ids(1, a, b, c) ? 0 : -EPERM; // setresgid + case 151: return (long)app_uid_now(); // setfsuid + case 152: return (long)app_gid_now(); // setfsgid + case 159: return -EPERM; // setgroups + default: return ret_val; + } +} +#endif + // Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) { if (!ctx || !info) return; @@ -57,6 +78,9 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) { int sys_nr = info->si_syscall; long ret_val = is_sigsys_synthetic_success_syscall(sys_nr) ? 0 : -ENOSYS; +#if defined(__aarch64__) + ret_val = sigsys_id_change(sys_nr, uctx->uc_mcontext.regs, ret_val); +#endif #if defined(__aarch64__) uctx->uc_mcontext.regs[0] = (uint64_t)ret_val; @@ -150,10 +174,83 @@ __attribute__((constructor(101))) static void install_sigsys_handler(void) { real_sig(SIGSYS, &sa, NULL); } +// SIGCHLD in a session with a parents file (handoff.c, DD_PARENTS): the program's action as it set it +// runs from ddnatv_sigchld_handler(), which then reaps the children no wait will come for +// (ddh_reap_unclaimed()). sigaction() shows the program its own action. A program that leaves SIGCHLD +// alone gets the handler only when DD_REAP_ADOPTED names it: with a handler, poll(), sleep() and the +// like return EINTR when a child exits, which a program that never had one may not expect. +static struct sigaction g_app_sigchld; +static int g_sigchld_managed; +static int g_sigchld_on_default; + +static void ddh_reap_unclaimed(void); +static int ddh_listed(const char *list, const char *name, char *const argv[]); +static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)); + +static void ddnatv_sigchld_handler(int sig, siginfo_t *info, void *ctx) { + struct sigaction app = g_app_sigchld; + if (app.sa_handler != SIG_DFL && app.sa_handler != SIG_IGN) { + if (app.sa_flags & SA_RESETHAND) { + // as the kernel would: the default from now on, with the handler only for a named program + g_app_sigchld.sa_handler = SIG_DFL; + g_app_sigchld.sa_flags &= ~(SA_SIGINFO | SA_RESETHAND); + int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); + int saved = errno; + if (real_sig) ddnatv_apply_sigchld(real_sig); + errno = saved; + } + if (app.sa_flags & SA_SIGINFO) app.sa_sigaction(sig, info, ctx); + else app.sa_handler(sig); + } + ddh_reap_unclaimed(); +} + +// Puts g_app_sigchld into effect: as it is where the kernel reaps every child itself (SIG_IGN, +// SA_NOCLDWAIT) or the program wants no handler and is not named, else through the handler above. +static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)) { + const struct sigaction *app = &g_app_sigchld; + int handler = app->sa_handler != SIG_DFL && app->sa_handler != SIG_IGN; + if (app->sa_handler == SIG_IGN || (app->sa_flags & SA_NOCLDWAIT) || (!handler && !g_sigchld_on_default)) + return real_sig(SIGCHLD, app, NULL); + struct sigaction k; + memset(&k, 0, sizeof(k)); + k.sa_sigaction = ddnatv_sigchld_handler; + k.sa_mask = app->sa_mask; + k.sa_flags = SA_SIGINFO | (handler ? (app->sa_flags & ~(SA_SIGINFO | SA_RESETHAND)) : (SA_RESTART | SA_NOCLDSTOP)); + return real_sig(SIGCHLD, &k, NULL); +} + +static int ddnatv_sigchld_action(int (*real_sig)(int, const struct sigaction *, struct sigaction *), + const struct sigaction *act, struct sigaction *oldact) { + struct sigaction prev = g_app_sigchld; + if (act) { + g_app_sigchld = *act; + if (ddnatv_apply_sigchld(real_sig) != 0) { + int err = errno; + g_app_sigchld = prev; + errno = err; + return -1; + } + } + if (oldact) *oldact = prev; + return 0; +} + +// From the hook's start (handoff.c), once the parents file is open +static void ddnatv_manage_sigchld(void) { + if (!getenv("DD_PARENTS")) return; + int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); + if (!real_sig || real_sig(SIGCHLD, NULL, &g_app_sigchld) != 0) return; + const char *named = getenv("DD_REAP_ADOPTED"); + g_sigchld_on_default = named && ddh_listed(named, program_invocation_short_name, NULL); + if (ddnatv_apply_sigchld(real_sig) == 0) g_sigchld_managed = 1; +} + int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) { int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); if (!real_sig) return -1; + if (signum == SIGCHLD && g_sigchld_managed) return ddnatv_sigchld_action(real_sig, act, oldact); if (signum == SIGSYS) { if (act && act->sa_sigaction == ddnatv_sigsys_handler) { return real_sig(signum, act, oldact); @@ -168,6 +265,7 @@ int rt_sigaction(int signum, const struct sigaction *act, struct sigaction *olda static int (*orig_rt_sigaction)(int, const struct sigaction *, struct sigaction *, size_t) = NULL; if (!orig_rt_sigaction) orig_rt_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *, size_t))dlsym(RTLD_NEXT, "rt_sigaction"); + if (signum == SIGCHLD && g_sigchld_managed) return sigaction(signum, act, oldact); if (signum == SIGSYS) { if (act && act->sa_sigaction == ddnatv_sigsys_handler) { return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : 0; @@ -186,6 +284,16 @@ typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler) { static sighandler_t (*orig_signal)(int, sighandler_t) = NULL; if (!orig_signal) orig_signal = (sighandler_t (*)(int, sighandler_t))dlsym(RTLD_NEXT, "signal"); + if (signum == SIGCHLD && g_sigchld_managed) { + // glibc's signal(): BSD semantics + struct sigaction act, old; + memset(&act, 0, sizeof(act)); + act.sa_handler = handler; + act.sa_flags = SA_RESTART; + sigemptyset(&act.sa_mask); + sigaddset(&act.sa_mask, SIGCHLD); + return sigaction(SIGCHLD, &act, &old) == 0 ? old.sa_handler : SIG_ERR; + } if (signum == SIGSYS) { struct sigaction act, old; memset(&act, 0, sizeof(act)); diff --git a/tools/nativeguest/hook/sockets.c b/tools/nativeguest/hook/sockets.c index b4b12f8005..7872581cda 100644 --- a/tools/nativeguest/hook/sockets.c +++ b/tools/nativeguest/hook/sockets.c @@ -234,9 +234,31 @@ ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) { return orig_sendmsg ? orig_sendmsg(sockfd, msg, flags) : -1; } +// Whether process pid runs as the app's user (DDNATV_USER=app, which env.c puts first in the +// environment of every program it starts that way) +static int peer_runs_as_app(pid_t pid) { + if (pid <= 0) return 0; + if (pid == getpid()) return app_user_mode(); + char path[48]; + snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid); + int fd = (int)call_orig_syscall(__NR_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + // Servers that pass credentials get them with every message, so only the first entry is read + static const char k_var[] = "DDNATV_USER=app"; + char buf[sizeof(k_var)]; + long n = call_orig_syscall(__NR_read, fd, (unsigned long)buf, sizeof(buf), 0, 0, 0); + call_orig_syscall(__NR_close, fd, 0, 0, 0, 0, 0); + return n == (long)sizeof(buf) && memcmp(buf, k_var, sizeof(buf)) == 0; +} + +// The app's ids are root's for a peer that runs as root, and its own for one that runs as the +// app's user, whichever this process is: a server compares them with what the peer says it is. static void present_peer_as_root(struct ucred *cred) { - if (cred->uid == (uid_t)call_orig_syscall(DDNATV_NR_REAL_GETUID, 0, 0, 0, 0, 0, 0)) cred->uid = 0; - if (cred->gid == (gid_t)call_orig_syscall(DDNATV_NR_REAL_GETGID, 0, 0, 0, 0, 0, 0)) cred->gid = 0; + uid_t app_uid = (uid_t)call_orig_syscall(DDNATV_NR_REAL_GETUID, 0, 0, 0, 0, 0, 0); + gid_t app_gid = (gid_t)call_orig_syscall(DDNATV_NR_REAL_GETGID, 0, 0, 0, 0, 0, 0); + if ((cred->uid != app_uid && cred->gid != app_gid) || peer_runs_as_app(cred->pid)) return; + if (cred->uid == app_uid) cred->uid = 0; + if (cred->gid == app_gid) cred->gid = 0; } // A server compares a peer's credentials with the user the peer claims, which is getuid()'s 0 diff --git a/tools/phantomlab/.gitignore b/tools/phantomlab/.gitignore new file mode 100644 index 0000000000..567609b123 --- /dev/null +++ b/tools/phantomlab/.gitignore @@ -0,0 +1 @@ +build/ diff --git a/tools/phantomlab/AndroidManifest.xml b/tools/phantomlab/AndroidManifest.xml new file mode 100644 index 0000000000..a554bfdda4 --- /dev/null +++ b/tools/phantomlab/AndroidManifest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/phantomlab/build.sh b/tools/phantomlab/build.sh new file mode 100644 index 0000000000..a7afcfaa9a --- /dev/null +++ b/tools/phantomlab/build.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Builds phantomlab.apk without Gradle: javac, d8, aapt2, the NDK's clang, apksigner (debug key). +# usage: tools/phantomlab/build.sh [out.apk] (ANDROID_SDK_ROOT or ANDROID_HOME must be set) +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +sdk=${ANDROID_SDK_ROOT:-${ANDROID_HOME:?set ANDROID_SDK_ROOT}} +bt=$(ls -d "$sdk"/build-tools/* | sort -V | tail -1) +platform=$(ls -d "$sdk"/platforms/android-* | sort -V | tail -1) +ndk=${ANDROID_NDK_ROOT:-$(ls -d "$sdk"/ndk/* | sort -V | tail -1)} +out=${1:-$here/build/phantomlab.apk} +work=$here/build +exe="" +case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) exe=".exe" ;; esac +bat="" +[ -n "$exe" ] && bat=".bat" + +rm -rf "$work/classes" "$work/dex" "$work/lib" "$work/unsigned.apk" +mkdir -p "$work/classes" "$work/dex" + +sources=() +while IFS= read -r -d '' f; do sources+=("$f"); done < <(find "$here/src" -name '*.java' -print0) +javac -nowarn --release 8 -cp "$platform/android.jar" -d "$work/classes" "${sources[@]}" 2>&1 | { grep -v "^warning\|^Note:" || true; } +classes=() +while IFS= read -r -d '' f; do classes+=("$f"); done < <(find "$work/classes" -name '*.class' -print0) +"$bt/d8$bat" --min-api 29 --lib "$platform/android.jar" --output "$work/dex" "${classes[@]}" + +host=$(ls -d "$ndk"/toolchains/llvm/prebuilt/* | head -1) +for abi in arm64-v8a x86_64; do + case $abi in arm64-v8a) triple=aarch64-linux-android29 ;; x86_64) triple=x86_64-linux-android29 ;; esac + mkdir -p "$work/lib/$abi" + "$host/bin/clang$exe" --target=$triple -shared -fPIC -O2 -Wall -o "$work/lib/$abi/liblab.so" "$here/jni/lab.c" -llog + "$host/bin/clang$exe" --target=$triple -fPIE -pie -O2 -Wall -o "$work/lib/$abi/libplabexe.so" "$here/jni/exe.c" +done + +"$bt/aapt2$exe" link -o "$work/unsigned.apk" -I "$platform/android.jar" --manifest "$here/AndroidManifest.xml" +python3 - "$work" <<'EOF' +import os, sys, zipfile +work = sys.argv[1] +with zipfile.ZipFile(os.path.join(work, "unsigned.apk"), "a", zipfile.ZIP_DEFLATED) as z: + z.write(os.path.join(work, "dex", "classes.dex"), "classes.dex") + for abi in os.listdir(os.path.join(work, "lib")): + for so in ("liblab.so", "libplabexe.so"): + z.write(os.path.join(work, "lib", abi, so), "lib/%s/%s" % (abi, so)) +EOF + +key=$work/debug.keystore +[ -f "$key" ] || keytool -genkeypair -keystore "$key" -storepass android -keypass android -alias lab \ + -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=phantomlab" >/dev/null 2>&1 +"$bt/zipalign$exe" -f -p 4 "$work/unsigned.apk" "$work/aligned.apk" +"$bt/apksigner$bat" sign --ks "$key" --ks-pass pass:android --out "$out" "$work/aligned.apk" +echo "$out" diff --git a/tools/phantomlab/jni/exe.c b/tools/phantomlab/jni/exe.c new file mode 100644 index 0000000000..a87d2a4ede --- /dev/null +++ b/tools/phantomlab/jni/exe.c @@ -0,0 +1,24 @@ +// libplabexe.so: an executable shipped as a "library" so the APK's lib directory holds it. +// Reports its identity and reads fd 3 when it is open, then exits with status 7. +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + char buf[128] = ""; + ssize_t n = -1; + struct pollfd p = {.fd = 3, .events = POLLIN}; + if (poll(&p, 1, 500) > 0 && (p.revents & (POLLIN | POLLHUP))) n = read(3, buf, sizeof(buf) - 1); + if (n > 0) buf[n] = 0; + char ctx[128] = ""; + int fd = open("/proc/self/attr/current", O_RDONLY); + if (fd >= 0) { + ssize_t m = read(fd, ctx, sizeof(ctx) - 1); + if (m > 0) ctx[m] = 0; + close(fd); + } + dprintf(2, "plabexe uid=%d ctx=%s fd3=%s\n", getuid(), ctx, n > 0 ? buf : "none"); + return 7; +} diff --git a/tools/phantomlab/jni/lab.c b/tools/phantomlab/jni/lab.c new file mode 100644 index 0000000000..811de3facd --- /dev/null +++ b/tools/phantomlab/jni/lab.c @@ -0,0 +1,422 @@ +// Native half of phantomlab: forks sleepers, execs in place, and probes what a process may do. +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define TAG "PLAB" + +JNIEXPORT jint JNICALL Java_com_droiddeck_phantomlab_Native_spawn(JNIEnv *env, jclass cls, jint n) { + int made = 0; + for (int i = 0; i < n; i++) { + pid_t pid = fork(); + if (pid == 0) { + for (;;) pause(); + } + if (pid > 0) made++; + } + return made; +} + +struct kept_fd { + int fd, flags; +}; + +static int keep_binder_fds(struct kept_fd *kept, int max) { + DIR *d = opendir("/proc/self/fd"); + if (!d) return 0; + int count = 0; + struct dirent *e; + char path[64], target[256]; + while ((e = readdir(d)) != NULL && count < max) { + int fd = atoi(e->d_name); + if (fd <= 2) continue; + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t len = readlink(path, target, sizeof(target) - 1); + if (len <= 0) continue; + target[len] = 0; + if (strstr(target, "binder")) { + int flags = fcntl(fd, F_GETFD); + if (flags < 0 || fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) != 0) continue; + kept[count].fd = fd; + kept[count].flags = flags; + count++; + __android_log_print(ANDROID_LOG_INFO, TAG, "keeping fd %d (%s) across exec", fd, target); + } + } + closedir(d); + return count; +} + +JNIEXPORT void JNICALL Java_com_droiddeck_phantomlab_Native_execInPlace(JNIEnv *env, jclass cls, jobjectArray jargv, jboolean keep) { + int n = (*env)->GetArrayLength(env, jargv); + char **argv = calloc(n + 1, sizeof(char *)); + for (int i = 0; i < n; i++) { + jstring s = (*env)->GetObjectArrayElement(env, jargv, i); + const char *c = (*env)->GetStringUTFChars(env, s, NULL); + argv[i] = strdup(c); + } + struct kept_fd kept[16]; + int kept_count = keep ? keep_binder_fds(kept, 16) : 0; + execv(argv[0], argv); + __android_log_print(ANDROID_LOG_ERROR, TAG, "execv %s failed: %s", argv[0], strerror(errno)); + for (int i = 0; i < kept_count; i++) fcntl(kept[i].fd, F_SETFD, kept[i].flags); +} + +static char *report; +static size_t report_len, report_cap; + +static void out(const char *fmt, ...) { + char line[1024]; + va_list ap; + va_start(ap, fmt); + int len = vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + if (len < 0) return; + if (len >= (int)sizeof(line)) len = sizeof(line) - 1; + if (report_len + len + 2 > report_cap) { + report_cap = (report_len + len + 2) * 2; + report = realloc(report, report_cap); + } + memcpy(report + report_len, line, len); + report_len += len; + report[report_len++] = '\n'; + report[report_len] = 0; +} + +static void read_small(const char *path, char *buf, size_t size) { + buf[0] = 0; + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) { + snprintf(buf, size, "<%s>", strerror(errno)); + return; + } + ssize_t n = read(fd, buf, size - 1); + close(fd); + if (n < 0) n = 0; + buf[n] = 0; + for (ssize_t i = 0; i < n; i++) if (buf[i] == '\n' || buf[i] == 0) buf[i] = ' '; +} + +#if defined(__aarch64__) +static const unsigned char ret42[] = {0x40, 0x05, 0x80, 0x52, 0xc0, 0x03, 0x5f, 0xd6}; +#else +static const unsigned char ret42[] = {0xb8, 0x2a, 0x00, 0x00, 0x00, 0xc3}; +#endif + +static int call_code(void *code) { + __builtin___clear_cache((char *)code, (char *)code + sizeof(ret42)); + return ((int (*)(void))code)(); +} + +static void probe_memfd_exec(void) { + int fd = syscall(SYS_memfd_create, "lab", 0); + if (fd < 0) { + out("memfd_exec: memfd_create %s", strerror(errno)); + return; + } + write(fd, ret42, sizeof(ret42)); + void *p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) out("memfd_exec: mmap exec %s", strerror(errno)); + else out("memfd_exec: ran, returned %d", call_code(p)); + close(fd); +} + +static void probe_anon_exec(void) { + void *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + memcpy(p, ret42, sizeof(ret42)); + if (mprotect(p, 4096, PROT_READ | PROT_EXEC) != 0) out("anon_exec: mprotect %s", strerror(errno)); + else out("anon_exec: ran, returned %d", call_code(p)); +} + +static int run_child(char *const argv[], int execfd) { + pid_t pid = fork(); + if (pid < 0) { + out("fork: %s", strerror(errno)); + return -1; + } + if (pid == 0) { + if (execfd >= 0) syscall(SYS_execveat, execfd, "", argv, environ, AT_EMPTY_PATH); + else execv(argv[0], argv); + _exit(100 + errno); + } + int status = 0; + waitpid(pid, &status, 0); + return WIFEXITED(status) ? WEXITSTATUS(status) : 1000 + WTERMSIG(status); +} + +static const char *exec_result(int st, const char *ran) { + if (st < 0) return "not run"; + return st >= 100 && st < 1000 ? strerror(st - 100) : ran; +} + +static int wait_fd(int fd, short events) { + struct pollfd p = {.fd = fd, .events = events}; + int r = poll(&p, 1, 2000); + if (r == 0) errno = ETIMEDOUT; + return r > 0 ? 0 : -1; +} + +static void probe_tcp(int i, int fd) { + struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(80)}; + inet_pton(AF_INET, "1.1.1.1", &a.sin_addr); + int fl = fcntl(fd, F_GETFL); + if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) != 0) { + out("fd%d tcp: fcntl %s", i, strerror(errno)); + return; + } + int r = connect(fd, (struct sockaddr *)&a, sizeof(a)); + if (r != 0 && errno == EINPROGRESS) { + int err = 0; + socklen_t el = sizeof(err); + if (wait_fd(fd, POLLOUT) == 0 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) == 0) { + r = err ? -1 : 0; + errno = err; + } else { + r = -1; + } + } + if (r != 0) { + out("fd%d tcp: connect %s", i, strerror(errno)); + } else { + const char *req = "HEAD / HTTP/1.0\r\nHost: 1.1.1.1\r\n\r\n"; + if (wait_fd(fd, POLLOUT) != 0 || write(fd, req, strlen(req)) < 0) { + out("fd%d tcp: connected, write %s", i, strerror(errno)); + } else { + char resp[64] = ""; + ssize_t n = wait_fd(fd, POLLIN) == 0 ? read(fd, resp, sizeof(resp) - 1) : -1; + if (n > 0) resp[n] = 0; + char *nl = strchr(resp, '\r'); + if (nl) *nl = 0; + out("fd%d tcp: connected, got \"%s\"", i, n > 0 ? resp : strerror(errno)); + } + } + fcntl(fd, F_SETFL, fl); +} + +static void probe_exec(void) { + char *argv[] = {"/system/bin/true", NULL}; + int st = run_child(argv, -1); + out("execve /system/bin/true: %s", exec_result(st, st == 0 ? "ok" : "status")); + int src = open("/system/bin/toybox", O_RDONLY); + int mfd = syscall(SYS_memfd_create, "toybox", 0); + char buf[65536]; + ssize_t n; + while (src >= 0 && (n = read(src, buf, sizeof(buf))) > 0) write(mfd, buf, n); + if (src >= 0) close(src); + char *targv[] = {"true", NULL}; + st = run_child(targv, mfd); + out("execveat memfd(toybox true): %s", exec_result(st, st == 0 ? "ok" : "status")); + close(mfd); +} + +static void probe_fd(int i, int fd) { + struct stat st; + if (fstat(fd, &st) != 0) { + out("fd%d: fstat %s", i, strerror(errno)); + return; + } + char target[256] = ""; + char path[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t len = readlink(path, target, sizeof(target) - 1); + if (len > 0) target[len] = 0; + if (S_ISSOCK(st.st_mode)) { + int type = 0, family = 0; + socklen_t sl = sizeof(type); + getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &sl); + struct sockaddr_storage ss; + socklen_t al = sizeof(ss); + getsockname(fd, (struct sockaddr *)&ss, &al); + family = ss.ss_family; + if (family == AF_INET && type == SOCK_STREAM) { + probe_tcp(i, fd); + } else if (family == AF_INET && type == SOCK_DGRAM) { + struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(53)}; + inet_pton(AF_INET, "1.1.1.1", &a.sin_addr); + int r = connect(fd, (struct sockaddr *)&a, sizeof(a)); + out("fd%d udp: connect %s", i, r == 0 ? "ok" : strerror(errno)); + } else { + char buf[64] = ""; + ssize_t r = wait_fd(fd, POLLIN) == 0 ? read(fd, buf, sizeof(buf) - 1) : -1; + if (r > 0) buf[r - 1] = 0; + out("fd%d unix(family %d): read %s", i, family, r > 0 ? buf : strerror(errno)); + } + return; + } + if (S_ISDIR(st.st_mode)) { + int f = openat(fd, "probe.txt", O_RDONLY); + out("fd%d dir %s: openat child %s", i, target, f >= 0 ? "ok" : strerror(errno)); + if (f >= 0) close(f); + return; + } + char buf[64] = ""; + ssize_t r = pread(fd, buf, sizeof(buf) - 1, 0); + if (r > 0) buf[r - 1] = 0; + out("fd%d file %s: read %s", i, target, r >= 0 ? buf : strerror(errno)); + void *p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0); + out("fd%d mmap read: %s", i, p == MAP_FAILED ? strerror(errno) : "ok"); + if (p != MAP_FAILED) munmap(p, 4096); + p = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0); + out("fd%d mmap exec: %s", i, p == MAP_FAILED ? strerror(errno) : "ok"); + if (p != MAP_FAILED) munmap(p, 4096); + char *argv[] = {"x", NULL}; + int st2 = run_child(argv, fd); + out("fd%d execveat: %s", i, exec_result(st2, "ran")); +} + +static void probe_self(void) { + char buf[512]; + out("uid=%d gid=%d pid=%d ppid=%d", getuid(), getgid(), getpid(), getppid()); + read_small("/proc/self/attr/current", buf, sizeof(buf)); + out("selinux: %s", buf); + read_small("/proc/self/cgroup", buf, sizeof(buf)); + out("cgroup: %s", buf); + int s = socket(AF_INET, SOCK_STREAM, 0); + out("socket(AF_INET): %s", s >= 0 ? "ok" : strerror(errno)); + if (s >= 0) close(s); + s = socket(AF_UNIX, SOCK_STREAM, 0); + out("socket(AF_UNIX): %s", s >= 0 ? "ok" : strerror(errno)); + if (s >= 0) close(s); + int f = open("/data/data/com.droiddeck.phantomlab/files/probe.txt", O_RDONLY); + out("open app data by path: %s", f >= 0 ? "ok" : strerror(errno)); + if (f >= 0) close(f); + const char *gpus[] = {"/dev/kgsl-3d0", "/dev/mali0", "/dev/dri/renderD128", NULL}; + for (int i = 0; gpus[i]; i++) { + if (access(gpus[i], F_OK) != 0) continue; + f = open(gpus[i], O_RDWR); + out("open %s: %s", gpus[i], f >= 0 ? "ok" : strerror(errno)); + if (f >= 0) close(f); + } +} + +static void probe_pid(const char *spec) { + int pid = atoi(spec); + char path[64], buf[256]; + snprintf(path, sizeof(path), "/proc/%d/cmdline", pid); + read_small(path, buf, sizeof(buf)); + out("read /proc/%d/cmdline: %s", pid, buf); + out("kill(%d, 0): %s", pid, kill(pid, 0) == 0 ? "ok" : strerror(errno)); + out("kill(%d, SIGCONT): %s", pid, kill(pid, SIGCONT) == 0 ? "ok" : strerror(errno)); +} + +static void try_write(const char *path, const char *value) { + int fd = open(path, O_WRONLY | O_CLOEXEC); + if (fd < 0) { + out("write %s: open %s", path, strerror(errno)); + return; + } + ssize_t n = write(fd, value, strlen(value)); + out("write %s: %s", path, n >= 0 ? "ok" : strerror(errno)); + close(fd); +} + +// Every way a process could leave the cgroup Android counts it in. +static void probe_escape(void) { + char own[256], pid[32], path[300]; + read_small("/proc/self/cgroup", own, sizeof(own)); + char *v2 = strstr(own, "0::"); + char dir[200] = ""; + if (v2) sscanf(v2 + 3, "%199s", dir); + snprintf(pid, sizeof(pid), "%d", getpid()); + try_write("/sys/fs/cgroup/cgroup.procs", pid); + char parent[200]; + snprintf(parent, sizeof(parent), "%s", dir); + char *slash = strrchr(parent, '/'); + if (slash) *slash = 0; + snprintf(path, sizeof(path), "/sys/fs/cgroup%s/cgroup.procs", parent); + try_write(path, pid); + snprintf(path, sizeof(path), "/sys/fs/cgroup%s/lab", dir); + out("mkdir %s: %s", path, mkdir(path, 0755) == 0 ? "ok" : strerror(errno)); + int r = syscall(SYS_unshare, 0x10000000 /* CLONE_NEWUSER */); + out("unshare(CLONE_NEWUSER): %s", r == 0 ? "ok" : strerror(errno)); + r = syscall(SYS_unshare, 0x02000000 /* CLONE_NEWCGROUP */); + out("unshare(CLONE_NEWCGROUP): %s", r == 0 ? "ok" : strerror(errno)); + int cg = open("/sys/fs/cgroup", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (cg < 0) { + out("open /sys/fs/cgroup: %s", strerror(errno)); + } else { + struct { + unsigned long long flags, pidfd, child_tid, parent_tid, exit_signal, stack, stack_size, tls, set_tid, + set_tid_size, cgroup; + } args = {.flags = 0x200000000ULL /* CLONE_INTO_CGROUP */, .exit_signal = SIGCHLD, .cgroup = (unsigned)cg}; + long child = syscall(435 /* clone3 */, &args, sizeof(args)); + if (child == 0) _exit(0); + if (child > 0) waitpid(child, NULL, 0); + out("clone3(CLONE_INTO_CGROUP, root): %s", child > 0 ? "ok" : strerror(errno)); + close(cg); + } +} + +// Runs path with fd as its fd 3 and its stderr captured. +static void probe_libexec(const char *path, int fd) { + int pipefd[2]; + if (pipe(pipefd) != 0) { + out("exec %s: pipe %s", path, strerror(errno)); + return; + } + pid_t pid = fork(); + if (pid < 0) { + out("exec %s: fork %s", path, strerror(errno)); + close(pipefd[0]); + close(pipefd[1]); + return; + } + if (pid == 0) { + dup2(pipefd[1], 2); + if (fd >= 0) dup2(fd, 3); + char *argv[] = {(char *)path, NULL}; + execv(path, argv); + dprintf(2, "execv: %s", strerror(errno)); + _exit(127); + } + close(pipefd[1]); + char buf[512] = ""; + ssize_t n = read(pipefd[0], buf, sizeof(buf) - 1); + if (n > 0) buf[n] = 0; + char *nl = strchr(buf, '\n'); + if (nl) *nl = 0; + close(pipefd[0]); + int status = 0; + waitpid(pid, &status, 0); + out("exec %s: status %d, said \"%s\"", path, WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status), buf); +} + +JNIEXPORT jstring JNICALL Java_com_droiddeck_phantomlab_Native_probe(JNIEnv *env, jclass cls, jstring jwhat, jintArray jfds) { + report_len = 0; + if (report) report[0] = 0; + const char *what = jwhat ? (*env)->GetStringUTFChars(env, jwhat, NULL) : "self"; + int n = (*env)->GetArrayLength(env, jfds); + jint *fds = (*env)->GetIntArrayElements(env, jfds, NULL); + char spec[1024]; + snprintf(spec, sizeof(spec), "%s", what); + char *save = NULL; + for (char *tok = strtok_r(spec, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) { + if (!strcmp(tok, "self")) probe_self(); + else if (!strcmp(tok, "memfd_exec")) probe_memfd_exec(); + else if (!strcmp(tok, "anon_exec")) probe_anon_exec(); + else if (!strcmp(tok, "exec")) probe_exec(); + else if (!strcmp(tok, "fds")) for (int i = 0; i < n; i++) probe_fd(i, fds[i]); + else if (!strncmp(tok, "pid=", 4)) probe_pid(tok + 4); + else if (!strcmp(tok, "escape")) probe_escape(); + else if (!strncmp(tok, "libexec=", 8)) probe_libexec(tok + 8, n > 0 ? fds[0] : -1); + } + (*env)->ReleaseIntArrayElements(env, jfds, fds, 0); + return (*env)->NewStringUTF(env, report ? report : ""); +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Iso.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Iso.java new file mode 100644 index 0000000000..1b10f9e777 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Iso.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class Iso extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/IsoPlain.java b/tools/phantomlab/src/com/droiddeck/phantomlab/IsoPlain.java new file mode 100644 index 0000000000..f0ecde6e3a --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/IsoPlain.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class IsoPlain extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java b/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java new file mode 100644 index 0000000000..8987b6cb08 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/LabService.java @@ -0,0 +1,91 @@ +package com.droiddeck.phantomlab; + +import android.app.Service; +import android.content.Intent; +import android.os.Binder; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import android.os.Parcel; +import android.os.ParcelFileDescriptor; +import android.os.Process; +import android.util.Log; + +import java.io.IOException; + +public class LabService extends Service { + static final int SPAWN = 1; + static final int PROBE = 2; + static final int EXEC = 3; + static final int WHO = 4; + + private final Handler handler = new Handler(Looper.getMainLooper()); + + private final Binder binder = new Binder() { + @Override + protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) { + switch (code) { + case SPAWN: { + int n = data.readInt(); + reply.writeInt(Native.spawn(n)); + return true; + } + case PROBE: { + String what = data.readString().replace("libexec", + "libexec=" + getApplicationInfo().nativeLibraryDir + "/libplabexe.so"); + ParcelFileDescriptor[] pfds = readFds(data); + try { + int[] fds = new int[pfds.length]; + for (int i = 0; i < fds.length; i++) fds[i] = pfds[i] == null ? -1 : pfds[i].getFd(); + reply.writeString(Native.probe(what, fds)); + } finally { + closeAll(pfds); + } + return true; + } + case EXEC: { + final String[] argv = data.createStringArray(); + final boolean keep = data.readInt() != 0; + Log.i(Main.TAG, "pid " + Process.myPid() + " execs " + String.join(" ", argv) + " keepBinder=" + keep); + handler.postDelayed(() -> Native.execInPlace(argv, keep), 500); + reply.writeInt(Process.myPid()); + return true; + } + case WHO: + reply.writeString("pid=" + Process.myPid() + " uid=" + Process.myUid() + + " isolated=" + Process.isIsolated()); + return true; + default: + return false; + } + } + }; + + private static ParcelFileDescriptor[] readFds(Parcel data) { + ParcelFileDescriptor[] pfds = new ParcelFileDescriptor[data.readInt()]; + try { + for (int i = 0; i < pfds.length; i++) pfds[i] = data.readFileDescriptor(); + } catch (RuntimeException e) { + closeAll(pfds); + throw e; + } + return pfds; + } + + private static void closeAll(ParcelFileDescriptor[] pfds) { + for (ParcelFileDescriptor pfd : pfds) { + if (pfd == null) continue; + try { + pfd.close(); + } catch (IOException e) { + Log.w(Main.TAG, "close fd failed " + e); + } + } + } + + @Override + public IBinder onBind(Intent intent) { + Log.i(Main.TAG, getClass().getSimpleName() + " bound in pid " + Process.myPid() + " uid " + Process.myUid()); + return binder; + } +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java new file mode 100644 index 0000000000..c65950fa67 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Main.java @@ -0,0 +1,333 @@ +package com.droiddeck.phantomlab; + +import android.app.Activity; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.Bundle; +import android.os.IBinder; +import android.os.Parcel; +import android.os.ParcelFileDescriptor; +import android.os.Process; +import android.os.RemoteException; +import android.system.ErrnoException; +import android.system.Os; +import android.system.OsConstants; +import android.util.Log; +import android.widget.TextView; + +import java.io.Closeable; +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Drive with: am start -n com.droiddeck.phantomlab/.Main --es cmd spawn --es target iso --ei n 40 + * Results go to logcat under the PLAB tag. + */ +public class Main extends Activity { + static final String TAG = "PLAB"; + + private static final Map binders = new HashMap<>(); + private static final Map> pending = new HashMap<>(); + private static final Map connections = new HashMap<>(); + private static final ExecutorService worker = Executors.newSingleThreadExecutor(); + private TextView text; + + private interface Op { + void run(IBinder binder) throws Exception; + } + + private final class Task { + final String target; + final String name; + final Op op; + final Closeable owned; + + Task(String target, String name, Op op, Closeable owned) { + this.target = target; + this.name = name; + this.op = op; + this.owned = owned; + } + + void run(IBinder binder) { + worker.execute(() -> { + try { + op.run(binder); + } catch (Exception e) { + log(target + " " + name + " failed " + e); + } finally { + release(); + } + }); + } + + void cancel() { + log(target + " " + name + " cancelled"); + release(); + } + + private void release() { + if (owned == null) return; + try { + owned.close(); + } catch (IOException e) { + log(target + " " + name + " close failed " + e); + } + } + } + + private static final class ProbeFds implements Closeable { + final List sent = new ArrayList<>(); + final List owned = new ArrayList<>(); + + @Override + public void close() throws IOException { + IOException failure = null; + for (ParcelFileDescriptor p : sent) { + try { + p.close(); + } catch (IOException e) { + failure = e; + } + } + for (FileDescriptor fd : owned) { + try { + Os.close(fd); + } catch (ErrnoException e) { + failure = new IOException(e); + } + } + sent.clear(); + owned.clear(); + if (failure != null) throw failure; + } + } + + @Override + protected void onCreate(Bundle state) { + super.onCreate(state); + text = new TextView(this); + setContentView(text); + log("main pid " + Process.myPid() + " uid " + Process.myUid()); + handle(getIntent()); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + handle(intent); + } + + private void log(String s) { + Log.i(TAG, s); + runOnUiThread(() -> text.append(s + "\n")); + } + + private static Class serviceClass(String target) { + String base = target.contains(":") ? target.substring(0, target.indexOf(':')) : target; + switch (base) { + case "iso": return Iso.class; + case "isoplain": return IsoPlain.class; + case "proc": return Proc.class; + default: + if (base.startsWith("w")) { + try { + return Class.forName("com.droiddeck.phantomlab.W" + base.substring(1)); + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException(target); + } + } + throw new IllegalArgumentException(target); + } + } + + private void withBinder(String target, String name, Op op, Closeable owned) { + Task task = new Task(target, name, op, owned); + IBinder binder = binders.get(target); + if (binder != null) { + task.run(binder); + return; + } + List q = pending.get(target); + if (q == null) { + q = new ArrayList<>(); + pending.put(target, q); + } + q.add(task); + if (!connections.containsKey(target)) bind(target); + } + + private void bind(String target) { + ServiceConnection conn = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + log("connected " + target); + binders.put(target, service); + List ops = pending.remove(target); + if (ops != null) for (Task t : ops) t.run(service); + } + + @Override + public void onServiceDisconnected(ComponentName name) { + log("DISCONNECTED " + target); + binders.remove(target); + } + + @Override + public void onBindingDied(ComponentName name) { + log("BINDING DIED " + target); + if (connections.get(target) != this) return; + List ops = pending.remove(target); + unbind(target); + if (ops != null) { + pending.put(target, ops); + bind(target); + } + } + }; + connections.put(target, conn); + boolean ok = false; + try { + Intent intent = new Intent(this, serviceClass(target)); + int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT; + if (target.contains(":")) { + ok = getApplicationContext().bindIsolatedService(intent, flags, target.replace(':', '_'), getMainExecutor(), conn); + } else { + ok = getApplicationContext().bindService(intent, conn, flags); + } + } finally { + log("bind " + target + " -> " + ok); + if (!ok) unbind(target); + } + } + + private void unbind(String target) { + ServiceConnection c = connections.remove(target); + binders.remove(target); + List q = pending.remove(target); + if (q != null) for (Task t : q) t.cancel(); + if (c == null) return; + try { + getApplicationContext().unbindService(c); + } catch (IllegalArgumentException e) { + log("unbind " + target + " " + e); + } + } + + private static Parcel call(IBinder binder, int code, Parcel data) throws RemoteException { + Parcel reply = Parcel.obtain(); + binder.transact(code, data, reply, 0); + return reply; + } + + private void handle(Intent intent) { + String cmd = intent.getStringExtra("cmd"); + if (cmd == null) return; + String target = intent.getStringExtra("target"); + try { + switch (cmd) { + case "spawn": { + int n = intent.getIntExtra("n", 10); + if ("main".equals(target)) { + log("main spawned " + Native.spawn(n)); + return; + } + withBinder(target, "spawn", b -> { + Parcel d = Parcel.obtain(); + d.writeInt(n); + log(target + " spawned " + call(b, LabService.SPAWN, d).readInt()); + }, null); + return; + } + case "who": + withBinder(target, "who", b -> log(target + " " + call(b, LabService.WHO, Parcel.obtain()).readString()), null); + return; + case "exec": { + String[] argv = intent.getStringExtra("argv").split("\\|"); + boolean keepBinder = intent.getIntExtra("keep", 1) != 0; + withBinder(target, "exec", b -> { + Parcel d = Parcel.obtain(); + d.writeStringArray(argv); + d.writeInt(keepBinder ? 1 : 0); + log(target + " exec in pid " + call(b, LabService.EXEC, d).readInt()); + }, null); + return; + } + case "probe": { + String what = intent.getStringExtra("what"); + ProbeFds fds = probeFds(intent.getStringExtra("fds")); + withBinder(target, "probe", b -> { + Parcel d = Parcel.obtain(); + d.writeString(what); + d.writeInt(fds.sent.size()); + for (ParcelFileDescriptor p : fds.sent) d.writeFileDescriptor(p.getFileDescriptor()); + for (String line : call(b, LabService.PROBE, d).readString().split("\n")) log(target + " probe " + line); + }, fds); + return; + } + case "unbind": { + unbind(target); + log("unbound " + target); + return; + } + default: + log("unknown cmd " + cmd); + } + } catch (Exception e) { + log(cmd + " failed " + e); + } + } + + /** fds: comma separated list of tcp, udp, file:, unix, memfd. */ + private ProbeFds probeFds(String spec) throws Exception { + ProbeFds fds = new ProbeFds(); + if (spec == null || spec.isEmpty()) return fds; + try { + for (String s : spec.split(",")) { + if (s.equals("tcp") || s.equals("udp")) { + FileDescriptor fd = Os.socket(OsConstants.AF_INET, + s.equals("tcp") ? OsConstants.SOCK_STREAM : OsConstants.SOCK_DGRAM, 0); + fds.owned.add(fd); + fds.sent.add(ParcelFileDescriptor.dup(fd)); + } else if (s.equals("unix")) { + FileDescriptor a = new FileDescriptor(); + FileDescriptor b = new FileDescriptor(); + Os.socketpair(OsConstants.AF_UNIX, OsConstants.SOCK_STREAM, 0, a, b); + fds.owned.add(a); + fds.owned.add(b); + Os.write(a, "hello from main\n".getBytes(), 0, 16); + fds.sent.add(ParcelFileDescriptor.dup(b)); + } else if (s.startsWith("file:")) { + File f = new File(getFilesDir(), s.substring(5)); + if (!f.exists()) { + try (FileOutputStream o = new FileOutputStream(f)) { + o.write("data file contents\n".getBytes()); + } + } + fds.sent.add(ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_WRITE)); + } else if (s.startsWith("path:")) { + fds.sent.add(ParcelFileDescriptor.open(new File(s.substring(5)), ParcelFileDescriptor.MODE_READ_ONLY)); + } else if (s.equals("dir")) { + fds.sent.add(ParcelFileDescriptor.open(getFilesDir(), ParcelFileDescriptor.MODE_READ_ONLY)); + } + } + } catch (Exception e) { + try { + fds.close(); + } catch (IOException ignored) { + } + throw e; + } + return fds; + } +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Native.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Native.java new file mode 100644 index 0000000000..be733615fc --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Native.java @@ -0,0 +1,16 @@ +package com.droiddeck.phantomlab; + +final class Native { + static { + System.loadLibrary("lab"); + } + + /** Forks n children that sleep until killed; returns how many were started. */ + static native int spawn(int n); + + /** execve(argv) in this process; with keepBinder, the binder fds stay open across it. */ + static native void execInPlace(String[] argv, boolean keepBinder); + + /** Runs the capability probes named in what, using the given fds; returns a report. */ + static native String probe(String what, int[] fds); +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Preload.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Preload.java new file mode 100644 index 0000000000..2bd3e4145f --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Preload.java @@ -0,0 +1,10 @@ +package com.droiddeck.phantomlab; + +import android.app.ZygotePreload; +import android.content.pm.ApplicationInfo; + +public class Preload implements ZygotePreload { + @Override + public void doPreload(ApplicationInfo appInfo) { + } +} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/Proc.java b/tools/phantomlab/src/com/droiddeck/phantomlab/Proc.java new file mode 100644 index 0000000000..7bd3578bc8 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/Proc.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class Proc extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W0.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W0.java new file mode 100644 index 0000000000..05fad74dcd --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W0.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W0 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W1.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W1.java new file mode 100644 index 0000000000..8c6e6bf414 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W1.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W1 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W2.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W2.java new file mode 100644 index 0000000000..49e1917e28 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W2.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W2 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W3.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W3.java new file mode 100644 index 0000000000..c9f3aa59c1 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W3.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W3 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W4.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W4.java new file mode 100644 index 0000000000..bfcf489921 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W4.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W4 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W5.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W5.java new file mode 100644 index 0000000000..cf9898db66 --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W5.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W5 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W6.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W6.java new file mode 100644 index 0000000000..85999fab6c --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W6.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W6 extends LabService {} diff --git a/tools/phantomlab/src/com/droiddeck/phantomlab/W7.java b/tools/phantomlab/src/com/droiddeck/phantomlab/W7.java new file mode 100644 index 0000000000..c9b7dfbe2a --- /dev/null +++ b/tools/phantomlab/src/com/droiddeck/phantomlab/W7.java @@ -0,0 +1,3 @@ +package com.droiddeck.phantomlab; + +public class W7 extends LabService {} diff --git a/tools/prepare_windows_runtime.py b/tools/prepare_windows_runtime.py index 886deb2a0e..be08f48296 100644 --- a/tools/prepare_windows_runtime.py +++ b/tools/prepare_windows_runtime.py @@ -10,6 +10,7 @@ import argparse import hashlib import io import json +import os from pathlib import Path, PurePosixPath import shutil import struct @@ -49,8 +50,14 @@ LOCAL_ANDROID_SOURCES = {'app/src/main/cpp/CMakeLists.txt', 'app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c', 'app/src/main/cpp/waylandcomp/src/spatialpose.c', 'app/src/main/cpp/waylandcomp/CMakeLists.txt'} -LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat', - 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr'} +LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-session', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input'} +IME_SOURCES = {'tools/ime/packages.json', 'tools/ime/prepare.py', 'tools/ime/smoke.py'} +IME_MANIFEST = 'usr/local/share/droiddeck/ime-files.json' +IME_PACKAGES = 'build/windows-setup/ime-packages' VR_PREFIX = 'assets/linuxfs/usr/local/lib/droiddeck-vr/' CHECK_PATHS = list(dict.fromkeys(runtime.SOURCE_PATHS + [ 'app/src/main/cpp', 'app/src/main/jniLibs', 'app/src/main/rust/stores', 'tools/vr'])) @@ -82,20 +89,23 @@ def check_sources(): if git('merge-tree', '--write-tree', DONOR_PR_SOURCE, DONOR_MAIN_SOURCE).decode().splitlines()[0] != DONOR_TREE: raise ValueError('The donor CI merge does not match the audited source tree') helper_sources = {path.relative_to(ROOT).as_posix() for path in source_assets()} - reviewed = LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | (LOCAL_SESSION_HELPERS & helper_sources) + reviewed = (LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | IME_SOURCES | + (LOCAL_SESSION_HELPERS & helper_sources)) unexpected = {p for p in changed(AUDITED_SOURCE, 'HEAD') - reviewed if not vr_build.is_source(p)} if unexpected: raise ValueError('Sources changed since the component audit:\n' + '\n'.join(sorted(unexpected))) local = changed('HEAD') untracked = set(filter(None, git('ls-files', '--others', '--exclude-standard', '-z', '--', *CHECK_PATHS).decode().split('\0'))) - unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES) + unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES - IME_SOURCES) if not vr_build.is_source(p)} if unexpected: raise ValueError('Unreviewed runtime/native/Rust changes:\n' + '\n'.join(sorted(unexpected))) classifications = {} for path in sorted(changed(DONOR_TREE, 'HEAD') | local | untracked): - if vr_build.is_source(path): + if path in IME_SOURCES: + action = 'regenerated from checksum-pinned RPMs; never reused from donor' + elif vr_build.is_source(path): action = 'VR component rebuilt from current source and verified; never imported from donor' elif path in LOCAL_ANDROID_SOURCES: action = 'Android native source compiled by Gradle; not imported from donor' @@ -161,6 +171,92 @@ def read_gamescope(path): return files, pins +def find_docker(): + docker = shutil.which('docker') + if docker: + return docker + desktop = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Docker/Docker/resources/bin/docker.exe' + if desktop.is_file(): + return str(desktop) + raise ValueError('Docker is required to prepare IME files on Windows; install Docker Desktop or add docker to PATH') + + +def prepare_ime(image): + workspace = ROOT / 'build/windows-setup' + workspace.mkdir(parents=True, exist_ok=True) + packages = ROOT / IME_PACKAGES + packages.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix='droiddeck-ime-', dir=workspace) as folder: + temporary = Path(folder) + linuxfs = temporary / 'linuxfs' + linuxfs.mkdir() + script = ROOT / 'tools/ime/prepare.py' + if sys.platform == 'win32': + docker = find_docker() + inspect_cmd = [docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image] + inspected = subprocess.run(inspect_cmd, capture_output=True, text=True, check=False) + fields = inspected.stdout.strip().split() if inspected.returncode == 0 else [] + image_id = fields[0] if len(fields) == 2 and fields[0] and fields[1] == 'linux/amd64' else '' + if not image_id and image == vr_build.IMAGE: + dockerfile = (ROOT / 'tools/local-cross.Dockerfile').read_bytes().replace(b'\r\n', b'\n') + try: + subprocess.run([docker, 'build', '--platform', 'linux/amd64', '--tag', image, + '--file', '-', str(temporary)], input=dockerfile, check=True) + except subprocess.CalledProcessError as error: + raise ValueError('IME preparation failed to build default compiler Docker image ' + image + + '; inspect the Docker build output above, resolve the build error, and rerun preparation') from error + inspected = subprocess.run(inspect_cmd, capture_output=True, text=True, check=False) + fields = inspected.stdout.strip().split() if inspected.returncode == 0 else [] + image_id = fields[0] if len(fields) == 2 and fields[0] and fields[1] == 'linux/amd64' else '' + if not image_id: + detail = inspected.stdout.strip() if inspected.returncode == 0 else inspected.stderr.strip() + detail = detail or 'no image id or platform returned' + raise ValueError('IME preparation requires the existing Docker image ' + image + + ' for linux/amd64; build or load it first (inspect result: ' + detail + ')') + snapshot = temporary / 'src' + (snapshot / 'tools/ime').mkdir(parents=True) + shutil.copy2(script, snapshot / 'tools/ime/prepare.py') + shutil.copy2(ROOT / 'tools/ime/packages.json', snapshot / 'tools/ime/packages.json') + command = [docker, 'run', '--rm', '--platform', 'linux/amd64', + '-v', str(snapshot) + ':/src:ro', + '-v', str(packages) + ':/cache', + '-v', str(linuxfs) + ':/out', + image_id, 'sh', '-c', + 'for tool in rpm2cpio cpio; do command -v "$tool" >/dev/null 2>&1 || { ' + 'echo "missing $tool; rebuild compiler image using tools/local-cross.Dockerfile" >&2; exit 1; }; done; ' + 'exec python3 /src/tools/ime/prepare.py --packages /cache --download --output /out'] + else: + command = [sys.executable, str(script), '--packages', str(packages), '--download', + '--output', str(linuxfs)] + try: + subprocess.run(command, check=True) + except subprocess.CalledProcessError as error: + if sys.platform == 'win32': + raise ValueError('IME preparation failed; ensure Docker is running and image ' + image + + ' is available') from error + raise + manifest_path = linuxfs / IME_MANIFEST + if not manifest_path.is_file(): + raise ValueError('IME preparation did not produce ' + IME_MANIFEST) + manifest = json.loads(manifest_path.read_text(encoding='utf-8')) + if manifest.get('version') != 1 or not isinstance(manifest.get('files'), dict): + raise ValueError('Unexpected IME manifest format') + files = {} + for relative, entry in sorted(manifest['files'].items()): + if not isinstance(entry, dict): + raise ValueError('Unexpected IME manifest entry: ' + str(relative)) + validate_relative(relative) + path = linuxfs / relative + if not path.is_file(): + raise ValueError('IME manifest references a missing file: ' + relative) + data = path.read_bytes() + if hashlib.sha256(data).hexdigest() != entry.get('sha256'): + raise ValueError('IME file checksum mismatch: ' + relative) + files[relative] = data + files[IME_MANIFEST] = manifest_path.read_bytes() + return files, manifest + + def validate_rebuilt(path, machine): data = path.read_bytes() if len(data) < 20 or data[:4] != b'\x7fELF' or data[5] != 1 or struct.unpack(' #include #include @@ -25,12 +26,19 @@ std::map buffers; std::map allocations; std::map buffer_memory; std::map> descriptors; +std::map set_pools; +std::map pool_capacities; std::map pipelines; std::map image_ids; std::map buffer_ids; std::vector dispatches; +std::vector external_views; uintptr_t serial = 100; -unsigned buffer_creates, set_creates; +unsigned buffer_creates, set_creates, pipeline_creates, idle_calls, image_creates, fail_image_at; +bool gpu_pending; +VkResult idle_result = VK_SUCCESS, reset_result = VK_SUCCESS; +const ddfg::DeviceDispatch *engine_dispatch; +const ddfg::InstanceDispatch *engine_instance; VkPipeline bound_pipeline; VkDescriptorSet bound_set; uint64_t command_hash = 14695981039346656037ull; @@ -61,6 +69,7 @@ template void VKAPI_CALL destroy(VkDevice, T, const VkAllocationCallbac VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo *info, const VkAllocationCallbacks *, VkImage *out) { + if (++image_creates == fail_image_at) return VK_ERROR_OUT_OF_DEVICE_MEMORY; *out = handle(); images[*out] = {info->extent, info->format, info->usage}; return VK_SUCCESS; @@ -73,9 +82,11 @@ VkResult VKAPI_CALL create_view(VkDevice, const VkImageViewCreateInfo *info, return VK_SUCCESS; } void VKAPI_CALL destroy_image(VkDevice, VkImage image, const VkAllocationCallbacks *) { + assert(!gpu_pending); assert(images.erase(image) == 1); } void VKAPI_CALL destroy_view(VkDevice, VkImageView view, const VkAllocationCallbacks *) { + assert(!gpu_pending); assert(views.erase(view) == 1); } VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info, @@ -86,6 +97,7 @@ VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info, return VK_SUCCESS; } void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks *) { + assert(!gpu_pending); assert(buffers.erase(buffer) == 1); buffer_memory.erase(buffer); } @@ -104,6 +116,7 @@ VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo *info, return VK_SUCCESS; } void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks *) { + assert(!gpu_pending); assert(allocations.erase(memory) == 1); } VkResult VKAPI_CALL bind_image(VkDevice, VkImage image, VkDeviceMemory memory, VkDeviceSize) { @@ -123,8 +136,14 @@ VkResult VKAPI_CALL map_memory(VkDevice, VkDeviceMemory memory, VkDeviceSize off *out = allocation.data.get(); return VK_SUCCESS; } -void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) { assert(allocations.count(memory)); } -VkResult VKAPI_CALL idle(VkDevice) { return VK_SUCCESS; } +void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) { + assert(!gpu_pending && allocations.count(memory)); +} +VkResult VKAPI_CALL idle(VkDevice) { + idle_calls++; + if (idle_result == VK_SUCCESS) gpu_pending = false; + return idle_result; +} void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties *out) { *out = {}; out->memoryTypeCount = 1; @@ -132,15 +151,42 @@ void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProper VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; } VkResult VKAPI_CALL allocate_sets(VkDevice, const VkDescriptorSetAllocateInfo *info, VkDescriptorSet *out) { + const auto used = std::count_if(set_pools.begin(), set_pools.end(), [&](const auto &entry) { + return entry.second == info->descriptorPool; + }); + if (used + info->descriptorSetCount > pool_capacities.at(info->descriptorPool)) + return VK_ERROR_OUT_OF_POOL_MEMORY; for (uint32_t i = 0; i < info->descriptorSetCount; i++) { out[i] = handle(); descriptors[out[i]] = {}; + set_pools[out[i]] = info->descriptorPool; set_creates++; } return VK_SUCCESS; } -VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool, VkDescriptorPoolResetFlags) { - descriptors.clear(); +VkResult VKAPI_CALL create_pool(VkDevice, const VkDescriptorPoolCreateInfo *info, + const VkAllocationCallbacks *, VkDescriptorPool *out) { + *out = handle(); + pool_capacities[*out] = info->maxSets; + return VK_SUCCESS; +} +void drop_sets(VkDescriptorPool pool) { + assert(!gpu_pending); + for (auto it = set_pools.begin(); it != set_pools.end();) { + if (it->second == pool) { + descriptors.erase(it->first); + it = set_pools.erase(it); + } else ++it; + } +} +void VKAPI_CALL destroy_pool(VkDevice, VkDescriptorPool pool, const VkAllocationCallbacks *) { + drop_sets(pool); + assert(pool_capacities.erase(pool) == 1); +} +VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool pool, VkDescriptorPoolResetFlags) { + assert(!gpu_pending); + if (reset_result != VK_SUCCESS) return reset_result; + drop_sets(pool); return VK_SUCCESS; } void VKAPI_CALL update_sets(VkDevice, uint32_t count, const VkWriteDescriptorSet *writes, @@ -164,12 +210,15 @@ VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, uint32_t count, const VkComputePipelineCreateInfo *, const VkAllocationCallbacks *, VkPipeline *out) { for (uint32_t i = 0; i < count; i++) { - const auto index = static_cast(pipelines.size()); + const auto index = pipeline_creates++ % 10; out[i] = handle(); pipelines[out[i]] = index; } return VK_SUCCESS; } +void VKAPI_CALL destroy_pipeline(VkDevice, VkPipeline pipeline, const VkAllocationCallbacks *) { + assert(!gpu_pending && pipelines.erase(pipeline) == 1); +} void VKAPI_CALL bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline pipeline) { assert(pipelines.count(pipeline)); bound_pipeline = pipeline; @@ -248,10 +297,20 @@ VkImageView external_image(uint32_t width, uint32_t height) { images[image] = {{width, height, 1}, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT}; views[view] = image; + external_views.push_back(view); return view; } +void clear_external_images() { + for (auto view : external_views) { + images.erase(views.at(view)); + views.erase(view); + } + external_views.clear(); +} + void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsigned generations) { + gpu_pending = false; const auto previous = external_image(width, height), current = external_image(width, height); const auto first = dispatches.size(); for (unsigned i = 0; i < generations; i++) @@ -275,14 +334,29 @@ void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsi const auto &actual = dispatches[first + i], &want = expected[i]; assert(actual.pipeline == want.pipeline && actual.x == want.x && actual.y == want.y && actual.z == want.z); } - for (auto it = views.begin(); it != views.end();) { - if (images.at(it->second).format == VK_FORMAT_R8G8B8A8_UNORM) { - images.erase(it->second); - it = views.erase(it); - } else ++it; - } + clear_external_images(); + gpu_pending = true; } +void check_empty() { + assert(images.empty() && views.empty() && buffers.empty() && allocations.empty()); + assert(descriptors.empty() && set_pools.empty() && pool_capacities.empty() && pipelines.empty()); +} + +void check_working_set(const ddfg::FrameGen &fg) { + assert(images.size() == static_cast(32 - 2 * fg.flowFinest())); + assert(buffers.size() == static_cast(18 - fg.flowFinest())); + assert(descriptors.size() == static_cast(54 - 4 * fg.flowFinest())); + assert(allocations.size() == images.size() + buffers.size()); +} + +} + +struct VkTable {}; +bool ddfgVkdInit(const VkTable &, ddfg::DeviceDispatch &dd, ddfg::InstanceDispatch &id) { + dd = *engine_dispatch; + id = *engine_instance; + return true; } int main(int argc, char **argv) { @@ -312,25 +386,145 @@ int main(int argc, char **argv) { dd.DestroyDescriptorSetLayout = destroy; dd.CreatePipelineLayout = create; dd.DestroyPipelineLayout = destroy; - dd.CreateDescriptorPool = create; - dd.DestroyDescriptorPool = destroy; dd.ResetDescriptorPool = reset_pool; + dd.CreateDescriptorPool = create_pool; + dd.DestroyDescriptorPool = destroy_pool; dd.ResetDescriptorPool = reset_pool; dd.AllocateDescriptorSets = allocate_sets; dd.UpdateDescriptorSets = update_sets; - dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy; + dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy_pipeline; dd.CmdBindPipeline = bind_pipeline; dd.CmdBindDescriptorSets = bind_sets; dd.CmdDispatch = dispatch; dd.CmdPipelineBarrier = barrier; dd.CmdClearColorImage = clear_image; dd.CmdCopyImage = copy_image; - ddfg::FrameGen fg; - assert(fg.init(&dd, &id, reinterpret_cast(1), reinterpret_cast(2), - 0, reinterpret_cast(3))); + engine_dispatch = ⅆ + engine_instance = &id; ddfg::Config cfg; cfg.enabled = true; cfg.model = model; cfg.perfPreset = preset; cfg.flowScale = 0.6f; - fg.configure(cfg); - assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + auto initialize = [&](ddfg::FrameGen &fg) { + assert(fg.init(&dd, &id, reinterpret_cast(1), reinterpret_cast(2), + 0, reinterpret_cast(3))); + fg.configure(cfg); + assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + }; + if (mode == "steady" || mode == "automatic") { + const auto waits = idle_calls; + { + ddfg::FrameGen fg; + initialize(fg); + for (unsigned repeat = 0; repeat < repeats; repeat++) { + record(fg, model, width, height, generations); + assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + assert(idle_calls == waits); + check_working_set(fg); + } + if (mode == "steady") { + fg.destroy(); + fg.destroy(); + assert(idle_calls == waits + 1); + } + } + check_empty(); + assert(idle_calls == waits + 1); + std::puts("PASS lifecycle=steady-and-idempotent-destruction"); + return 0; + } + if (mode == "restart" || mode == "instances") { + for (unsigned repeat = 0; repeat < repeats; repeat++) { + ddfg::FrameGen first; + initialize(first); + record(first, model, width, height, generations); + check_working_set(first); + if (mode == "instances") { + gpu_pending = false; + ddfg::FrameGen second; + initialize(second); + record(second, model, width, height, generations); + first.destroy(); + record(second, model, width, height, generations); + check_working_set(second); + second.destroy(); + } else first.destroy(); + check_empty(); + } + std::puts("PASS lifecycle=restart-and-instance-isolation"); + return 0; + } + if (mode == "engine" || mode == "engine-failure") { + { + ddfg::Engine engine; + assert(engine.init(VkTable{}, reinterpret_cast(1), + reinterpret_cast(2), 0, reinterpret_cast(3))); + engine.configure(generations + 1, model, preset, 0.6f); + assert(engine.prepare(width, height, VK_FORMAT_R8G8B8A8_UNORM)); + for (unsigned frame = 0; frame < 3; frame++) { + gpu_pending = false; + const auto source = external_image(width, height); + const auto output = external_image(width, height); + const auto count = engine.plan(generations); + engine.process(reinterpret_cast(1), views.at(source), width, height, count); + for (unsigned generation = 0; generation < count; generation++) + engine.generateInto(reinterpret_cast(1), generation, count, + views.at(output), output, width, height); + clear_external_images(); + gpu_pending = true; + } + if (mode == "engine-failure") { + idle_result = VK_ERROR_OUT_OF_DEVICE_MEMORY; + assert(!engine.prepare(width + 17, height + 9, VK_FORMAT_R8G8B8A8_UNORM)); + assert(engine.unavailable() && !engine.valid()); + } + } + if (mode == "engine") check_empty(); + else assert(gpu_pending && !images.empty() && !buffers.empty() && !descriptors.empty()); + std::puts("PASS lifecycle=engine-ownership"); + return 0; + } + if (mode == "idle-failure" || mode == "destroy-failure" || mode == "reset-failure" || mode == "partial") { + { + ddfg::FrameGen fg; + initialize(fg); + record(fg, model, width, height, generations); + const auto prior_buffers = buffers.size(), prior_images = images.size(), prior_sets = descriptors.size(); + if (mode == "partial") { + fail_image_at = image_creates + 2; + assert(!fg.onResize({width + 17, height + 9}, VK_FORMAT_R8G8B8A8_UNORM)); + assert(!fg.valid()); + } else { + if (mode == "reset-failure") reset_result = VK_ERROR_OUT_OF_HOST_MEMORY; + else idle_result = VK_ERROR_OUT_OF_DEVICE_MEMORY; + if (mode == "destroy-failure") fg.destroy(); + else assert(!fg.onResize({width + 17, height + 9}, VK_FORMAT_R8G8B8A8_UNORM)); + assert(!fg.valid()); + assert(buffers.size() == prior_buffers && images.size() == prior_images && + descriptors.size() == prior_sets); + const auto prior_dispatches = dispatches.size(); + const auto prior_waits = idle_calls; + fg.record(reinterpret_cast(1), VK_NULL_HANDLE, VK_NULL_HANDLE, VK_NULL_HANDLE, 0.5f); + assert(dispatches.size() == prior_dispatches); + if (mode != "reset-failure") { + assert(!fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + cfg.perfPreset = (preset + 1) % 3; + fg.configure(cfg); + if (mode == "destroy-failure") { + idle_result = VK_SUCCESS; + assert(fg.destroy()); + } else { + fg.destroy(); + assert(idle_calls == prior_waits + 1); + } + } + } + } + if (mode == "reset-failure" || mode == "partial" || mode == "destroy-failure") check_empty(); + else assert(gpu_pending && !images.empty() && !buffers.empty() && !descriptors.empty()); + std::puts("PASS lifecycle=failure-containment"); + return 0; + } + ddfg::FrameGen fg; + initialize(fg); assert(mode == "resources" || mode == "record" || mode == "resize" || mode == "preset"); for (unsigned repeat = 0; repeat < repeats; repeat++) { const auto old_buffers = buffer_creates, old_sets = set_creates; if (mode != "record") check_images(width, height, fg.flowFinest()); record(fg, model, width, height, generations); if (mode != "record") { + check_working_set(fg); assert(buffer_creates - old_buffers == static_cast(15 - fg.flowFinest())); assert(set_creates - old_sets == static_cast(54 - 4 * fg.flowFinest())); } @@ -356,4 +550,5 @@ int main(int argc, char **argv) { dispatches.size(), static_cast(command_hash)); fg.destroy(); assert(images.empty() && views.empty()); + if (mode != "record") check_empty(); } diff --git a/tools/tests/effects_source_cache_harness.c b/tools/tests/effects_source_cache_harness.c index f947b230b0..da9615d1c6 100644 --- a/tools/tests/effects_source_cache_harness.c +++ b/tools/tests/effects_source_cache_harness.c @@ -51,6 +51,73 @@ static VkResult VKAPI_CALL allocate_set(VkDevice dev, const VkDescriptorSetAlloc *out = (VkDescriptorSet)(uintptr_t)(200 + ++sets); return VK_SUCCESS; } + +static VkImageLayout restored_layout; +static VkPipelineStageFlags restored_stage; +static void VKAPI_CALL pipeline_barrier(VkCommandBuffer cmd, VkPipelineStageFlags src, VkPipelineStageFlags dst, + VkDependencyFlags flags, uint32_t nm, const VkMemoryBarrier *m, uint32_t nb, + const VkBufferMemoryBarrier *b, uint32_t ni, const VkImageMemoryBarrier *images) { + for (uint32_t k = 0; k < ni; k++) { + if (images[k].image == (VkImage)(uintptr_t)10 && images[k].newLayout == VK_IMAGE_LAYOUT_GENERAL) { + restored_layout = images[k].oldLayout; + restored_stage = src; + } + } +} +static void VKAPI_CALL begin_pass(VkCommandBuffer c, const VkRenderPassBeginInfo *i, VkSubpassContents s) {} +static void VKAPI_CALL viewport(VkCommandBuffer c, uint32_t f, uint32_t n, const VkViewport *v) {} +static void VKAPI_CALL scissor(VkCommandBuffer c, uint32_t f, uint32_t n, const VkRect2D *v) {} +static void VKAPI_CALL bind_pipeline(VkCommandBuffer c, VkPipelineBindPoint b, VkPipeline p) {} +static void VKAPI_CALL bind_sets(VkCommandBuffer c, VkPipelineBindPoint b, VkPipelineLayout l, uint32_t f, + uint32_t n, const VkDescriptorSet *s, uint32_t nd, const uint32_t *d) {} +static void VKAPI_CALL push(VkCommandBuffer c, VkPipelineLayout l, VkShaderStageFlags s, uint32_t o, + uint32_t n, const void *v) {} +static void VKAPI_CALL draw(VkCommandBuffer c, uint32_t n, uint32_t i, uint32_t f, uint32_t fi) {} +static void VKAPI_CALL end_pass(VkCommandBuffer c) {} +static void VKAPI_CALL blit(VkCommandBuffer c, VkImage a, VkImageLayout al, VkImage b, VkImageLayout bl, + uint32_t n, const VkImageBlit *r, VkFilter f) {} + +static void check_generated_settings_and_layout(void) { + g_vk.CmdPipelineBarrier = pipeline_barrier; + g_vk.CmdBeginRenderPass = begin_pass; + g_vk.CmdSetViewport = viewport; g_vk.CmdSetScissor = scissor; + g_vk.CmdBindPipeline = bind_pipeline; g_vk.CmdBindDescriptorSets = bind_sets; + g_vk.CmdPushConstants = push; g_vk.CmdDraw = draw; g_vk.CmdEndRenderPass = end_pass; + g_vk.CmdBlitImage = blit; + g_rp = (VkRenderPass)(uintptr_t)5; + g_pipe[P_SGSR] = (VkPipeline)(uintptr_t)6; + g_pipe[P_COLOR] = (VkPipeline)(uintptr_t)7; + g_ready = 1; + for (int k = 0; k < 2; k++) { + struct fx_target *t = &g_contexts[1].targets[k]; + t->img = (VkImage)(uintptr_t)(30 + k); t->w = 1920; t->h = 1080; + } + vkp_effects_set_scaling(3); + assert(vkp_effects_prepare_generated()); + vkp_effects_set_scaling(0); + vkp_effects_set_cas(1, 75); + vkp_effects_sync(); + assert(g_cur.scaling == 0 && cas_active(&g_cur)); + assert(g_generated_settings.scaling == 3 && !effect_count(&g_generated_settings)); + int w, h; + VkImage input = (VkImage)(uintptr_t)10; + assert(vkp_effects_run_before_generated(VK_NULL_HANDLE, input, 1280, 720, &w, &h) == input); + assert(w == 1280 && h == 720); + assert(vkp_effects_run_generated(VK_NULL_HANDLE, input, 1280, 720, 1920, 1080, 0, &w, &h) != input); + assert(w == 1920 && h == 1080); + assert(restored_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + assert(restored_stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); + g_generated_settings.scaling = 0; + g_generated_settings.color_on = 1; + assert(vkp_effects_run_generated(VK_NULL_HANDLE, input, 1280, 720, 1920, 1080, 0, &w, &h) != input); + assert(restored_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + assert(restored_stage == VK_PIPELINE_STAGE_TRANSFER_BIT); + g_ready = -1; + assert(vkp_effects_run_generated(VK_NULL_HANDLE, input, 1280, 720, 1920, 1080, 0, &w, &h) == input); + assert(w == 1280 && h == 720); + assert(restored_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + assert(g_context == 0); +} static void VKAPI_CALL update_set(VkDevice dev, uint32_t count, const VkWriteDescriptorSet *writes, uint32_t copies, const VkCopyDescriptorSet *copy) { (void)dev; (void)copies; (void)copy; @@ -84,7 +151,20 @@ int main(int argc, char **argv) { VkImage source = (VkImage)(uintptr_t)10; assert(scene_ensure(source, 1280, 720) == 0); VkImageView original = bound_view; - if (!strcmp(argv[1], "recycled")) { + if (!strcmp(argv[1], "generated-layout")) { + check_generated_settings_and_layout(); + } else if (!strcmp(argv[1], "generated")) { + for (int k = 1; k < FX_CONTEXTS; k++) { + g_context = k; + assert(scene_ensure((VkImage)(uintptr_t)(10 + k), 1280, 720) == 0); + } + assert(sets == FX_CONTEXTS && !freed_sets); + vkp_effects_release_generated_sources(); + assert(g_context == 0 && freed_sets == FX_CONTEXTS - 1); + assert(g_scene.img == source && g_scene.view == original); + vkp_effects_release_generated_sources(); + assert(freed_sets == FX_CONTEXTS - 1); + } else if (!strcmp(argv[1], "recycled")) { vkp_effects_forget_image(source); assert(freed_sets == 1 && freed_views == 1); assert(scene_ensure(source, 1280, 720) == 0); diff --git a/tools/tests/frame_worker_peer_live_test.c b/tools/tests/frame_worker_peer_live_test.c new file mode 100644 index 0000000000..87e6ee300e --- /dev/null +++ b/tools/tests/frame_worker_peer_live_test.c @@ -0,0 +1,51 @@ +#define _GNU_SOURCE +#include "frame_worker_peer.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +static uint64_t start_ticks(pid_t id) { + char proc[64], line[4096]; snprintf(proc,sizeof(proc),"/proc/%d/stat",id); + FILE *f=fopen(proc,"r");assert(f);assert(fgets(line,sizeof(line),f));fclose(f); + uint64_t ticks=0; + assert(dd_worker_parse_start(line,&ticks)==DD_WORKER_STAT_OK); + return ticks; +} +static bool check_maps(const struct dd_worker_grant *g,pid_t id,uint64_t ticks) { + char proc[64],line[4096];snprintf(proc,sizeof(proc),"/proc/%d/maps",id); + FILE *f=fopen(proc,"r");assert(f);bool found=false; + while(fgets(line,sizeof(line),f)) if(dd_worker_grant_matches(g,4,getuid(),id,ticks,4,line)){ found=true;break;} + fclose(f);return found; +} +int main(void){ + char p[]="/tmp/dd-live-map.XXXXXX";int fd=mkstemp(p);assert(fd>=0); + assert(ftruncate(fd,4096)==0);struct stat st;assert(fstat(fd,&st)==0); + int a[2],b[2];assert(pipe(a)==0&&pipe(b)==0);pid_t id=fork();assert(id>=0); + if(id==0){ + close(a[0]);close(b[1]); + void *m=mmap(NULL,4096,PROT_READ|PROT_EXEC,MAP_PRIVATE,fd,0);assert(m!=MAP_FAILED); + assert(write(a[1],"y",1)==1); + char c;assert(read(b[0],&c,1)==1);assert(mprotect(m,4096,PROT_READ)==0); + assert(write(a[1],"y",1)==1);assert(read(b[0],&c,1)==1);_exit(0); + } + close(a[1]);close(b[0]);char c;assert(read(a[0],&c,1)==1); + int pfd=syscall(SYS_pidfd_open,id,0);assert(pfd>=0); + struct pollfd pfd_poll={.fd=pfd,.events=POLLIN};assert(poll(&pfd_poll,1,0)==0); + uint64_t start=start_ticks(id);assert(start); + struct dd_worker_grant g={.owner=4,.uid=getuid(),.pid=id,.dev_major=major(st.st_dev),.dev_minor=minor(st.st_dev),.ino=st.st_ino,.start_ticks=start,.expires=10,.canonical_file=p,.app_launch_verified=true,.final_go=true}; + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED,0,start+1)); + assert(!check_maps(&g,id,start+1)); // A forged self receipt fails against live post-exec ticks. + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK,start,start)); + assert(check_maps(&g,id,start)); + g.final_go=false;assert(!check_maps(&g,id,start));g.final_go=true; + assert(write(b[1],"n",1)==1);assert(read(a[0],&c,1)==1);assert(!check_maps(&g,id,start)); + assert(write(b[1],"n",1)==1);assert(poll(&pfd_poll,1,2000)==1); + assert(pfd_poll.revents&POLLIN);int status;assert(waitpid(id,&status,0)==id&&WIFEXITED(status)&&WEXITSTATUS(status)==0); + close(fd); close(pfd);unlink(p); puts("Live executable map, start-time reuse rejection, no-GO revocation, non-executable map rejection, and pidfd exit readiness passed."); +} diff --git a/tools/tests/frame_worker_peer_test.c b/tools/tests/frame_worker_peer_test.c new file mode 100644 index 0000000000..a8401aae0d --- /dev/null +++ b/tools/tests/frame_worker_peer_test.c @@ -0,0 +1,48 @@ +#include "frame_worker_peer.h" +#include + +static const char file[]="/app/private/linuxfs/opt/droiddeck-agent/bin/gamescope"; +static const char good[]="1000-2000 r-xp 00001000 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope\n"; +int main(void) { + uint64_t ticks = 0; + assert(dd_worker_parse_start("650 (with ) parens) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 251191 123\n", &ticks) == DD_WORKER_STAT_OK); + assert(ticks == 251191); + assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 0 123\n", &ticks) == DD_WORKER_STAT_ZERO); + assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18446744073709551616 123\n", &ticks) == DD_WORKER_STAT_PARSE); + assert(dd_worker_parse_start("650 (x) S 1 2 3", &ticks) == DD_WORKER_STAT_PARSE); + assert(dd_worker_open_failure(EACCES) == DD_WORKER_STAT_DENIED); + assert(dd_worker_open_failure(EPERM) == DD_WORKER_STAT_DENIED); + assert(dd_worker_open_failure(ENOENT) == DD_WORKER_STAT_HIDDEN); + assert(dd_worker_open_failure(ESRCH) == DD_WORKER_STAT_HIDDEN); + assert(dd_worker_open_failure(EMFILE) == DD_WORKER_STAT_OPEN); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251191, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251192, 251191)); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 251191)); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_HIDDEN, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 0)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OPEN, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_READ, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_PARSE, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_ZERO, 0, 251191)); + struct dd_worker_grant g={.owner=3,.uid=10197,.pid=650,.dev_major=254,.dev_minor=21, + .start_ticks=251191,.ino=5502,.expires=1000,.canonical_file=file,.app_launch_verified=true,.final_go=true}; + assert(dd_worker_grant_matches(&g,3,10197,650,251191,999,good)); + assert(!dd_worker_grant_matches(&g,3,10197,650,251191,1000,good)); + assert(!dd_worker_grant_matches(&g,4,10197,650,251191,999,good)); + assert(!dd_worker_grant_matches(&g,3,10198,650,251191,999,good)); + assert(!dd_worker_grant_matches(&g,3,10197,651,251191,999,good)); + assert(!dd_worker_grant_matches(&g,3,10197,650,251192,999,good)); + assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,NULL)); + const char *invalid[]={ + "1000-2000 r--p 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope", + "1000-2000 r-xp 0 fe:15 5503 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope", + "1000-2000 r-xp 0 fe:16 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope", + "1000-2000 r-xp 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope (deleted)", + "1000-2000 r-xp 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope.bak", + "1000-2000 r-xp 0 fe:15 5502 /system/lib64/libddexec.so", "", NULL}; + for (int i=0;invalid[i];i++) assert(!dd_worker_map_matches(&g,invalid[i])); + g.final_go=false; + assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,good)); + g.final_go=true; g.app_launch_verified=false; + assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,good)); +} diff --git a/tools/tests/subsurface_release_harness.c b/tools/tests/subsurface_release_harness.c index f162e53ce9..74eb818a50 100644 --- a/tools/tests/subsurface_release_harness.c +++ b/tools/tests/subsurface_release_harness.c @@ -26,6 +26,8 @@ struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, v struct wl_resource { struct wl_list listeners; int acquired, releases, errors; }; struct dmabuf_buffer { int unused; }; enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE }; +/* These release fixtures exercise legacy attachments, which own no acquire FD. */ +#define dd_frame_acquire_clear(slot) ((void)0) struct surface { struct wl_list link; struct wl_resource *dmabuf; diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index 06fdc779c4..c06924e42f 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -295,6 +295,37 @@ class DriveTest(Temp): self.assertEqual(BNET["install_path"](self.root, str(self.card)), "D:\\") self.assertEqual(sorted(os.listdir(self.devices)), ["d:"]) + def test_a_folder_chosen_in_battlenet_on_the_library_drive_is_kept(self): + path = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"]) + BNET["write_config"](self.root) + self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library") + (self.card / "Battle.net").mkdir() + config = json.loads(path.read_text()) + config["Client"]["Install"]["DefaultInstallPath"] = "D:\\Battle.net" + path.write_text(json.dumps(config)) + self.assertIsNone(BNET["write_config"](self.root, str(self.library))) + self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Battle.net") + + def test_a_chosen_folder_inside_the_native_rootfs_is_not_kept_whatever_its_spacing(self): + BNET["write_config"](self.root, str(self.library)) + rootfs = self.card / "files/linuxfs" + (rootfs / "Games").mkdir(parents=True) + with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}): + for current in ("D:\\files\\linuxfs\\Games", " D:\\files\\linuxfs\\Games"): + self.assertFalse(BNET["chosen_folder"](self.root, current, str(self.library))) + + def test_a_folder_on_another_drive_or_missing_moves_to_the_library(self): + path = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"]) + BNET["write_config"](self.root, str(self.library)) + internal = self.tmp / "root/Games/Stores/Battle.net" + internal.mkdir(parents=True) + for current in ("Z:" + str(internal), "D:\\Gone"): + config = json.loads(path.read_text()) + config["Client"]["Install"]["DefaultInstallPath"] = current + path.write_text(json.dumps(config)) + self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library") + self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Games\\Battle.net") + def test_drives_in_use_and_the_ones_proton_owns_are_left_alone(self): self.devices.mkdir(parents=True) os.symlink("/somewhere/else", self.devices / "d:") diff --git a/tools/tests/test_bionic_paths.py b/tools/tests/test_bionic_paths.py index 55c371b303..e4931b48ae 100644 --- a/tools/tests/test_bionic_paths.py +++ b/tools/tests/test_bionic_paths.py @@ -2,6 +2,7 @@ import importlib.machinery import importlib.util import os import re +import runpy import shutil import subprocess import tempfile @@ -74,6 +75,18 @@ class ToolArguments(unittest.TestCase): self.assertEqual(['BANNER_AUDIO_DIRECT_MIC=1', 'BANNER_AUDIO_DIRECT_MS=60'], result.stdout.split()) + def test_original_xbox_switches_reach_wine(self): + game_env = runpy.run_path(str(BIN / 'droiddeck-game-env')) + switches = dict(game_env['XBOX_BACK_COMPAT_ENV'], VKD3D_PACKED_422_SWIZZLE='rbg1') + text = LAUNCH.read_text() + block = text[text.index('KEEP="'):text.index('export PATH=/system/bin')] + env = dict(switches, PATH=os.environ['PATH'], DROIDDECK_BIONIC_KEEP='PATH', OTHER='x') + result = subprocess.run(['sh', '-c', block + 'env\n'], env=env, text=True, capture_output=True, check=True) + kept = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line) + self.assertEqual(switches, {name: kept.get(name) for name in switches}) + self.assertNotIn('OTHER', kept) + + class SessionLogs(unittest.TestCase): SESSION = '/data/user/0/com.droiddeck.launcher/files/logs/2026-11-22-09-steam' diff --git a/tools/tests/test_ci_checks.py b/tools/tests/test_ci_checks.py index a5982366ac..8e3b7e9880 100644 --- a/tools/tests/test_ci_checks.py +++ b/tools/tests/test_ci_checks.py @@ -25,7 +25,7 @@ class CiChecksTest(unittest.TestCase): self.assertIn("gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit])", gradle) def test_robolectric_cache_saves_and_restores_the_same_absolute_path(self): - steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps'] + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] caches = [step['with'] for step in steps if step.get('uses', '').startswith('actions/cache')] for cache in caches: for path in cache['path'].split('\n'): @@ -34,13 +34,17 @@ class CiChecksTest(unittest.TestCase): self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2) def test_unit_test_retry_requires_maven_exception(self): - steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps'] + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] run = next(step['run'] for step in steps if step.get('id') == 'unit-tests') line = next(line for line in run.splitlines() if 'grep -Eq' in line) pattern = shlex.split(line)[shlex.split(line).index('-Eq') + 1] for log, expected in ( ("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo.maven.apache.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0), ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo.maven.apache.org/maven2/a.jar", 0), + ("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo1.maven.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0), + ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo1.maven.org/maven2/a.pom.sha512", 0), + ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://example.org/a.jar", 1), + ("Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: https://repo1.maven.org/maven2/a.jar", 1), ("SomeTest > test FAILED: Too Many Requests", 1), ("Caused by: java.lang.AssertionError: HTTP 429", 1), ): @@ -59,15 +63,125 @@ class CiChecksTest(unittest.TestCase): self.assertEqual(result.strip(), '2') def test_build_and_tests_use_identical_generated_metadata(self): - jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] - steps = {step.get('id'): step for step in jobs['build']['steps']} - self.assertEqual(steps['build']['env'], steps['unit-tests']['env']) - self.assertIn('DROIDDECK_BUILD_LABEL', steps['unit-tests']['env']) - self.assertIn('SGDB_API_KEY', steps['unit-tests']['env']) + build = {step.get('id'): step for step in + yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']} + tests = {step.get('id'): step for step in + yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']} + self.assertEqual(build['build']['env'], tests['unit-tests']['env']) + self.assertIn('DROIDDECK_BUILD_LABEL', tests['unit-tests']['env']) + self.assertIn('SGDB_API_KEY', tests['unit-tests']['env']) + self.assertEqual(build['build-label'], tests['build-label']) gradle = (ROOT / 'app/build.gradle').read_text() self.assertIn("outputs.doNotCacheIf('CI executes the test suite on every run') { true }", gradle) self.assertIn('outputs.upToDateWhen { false }', gradle) + def test_unit_tests_switch_mirrors_only_for_robolectric_rate_limits(self): + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] + script = next(step['run'] for step in steps if step.get('id') == 'unit-tests') + central = 'https://repo.maven.apache.org/maven2/' + native = f'{central}org/robolectric/nativeruntime-dist-compat/1.0.18/nativeruntime-dist-compat-1.0.18.jar' + sdk = 'https://repo1.maven.org/maven2/org/robolectric/android-all-instrumented/sdk.jar.sha512' + gradle_error = 'org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException' + get_error = f"Could not GET '{native}'. Received status code 429 from server: Too Many Requests" + mirror = '-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2' + # These two resolvers report the status and URL in opposite orders. + cases = [ + ('ok', 0, 0, 0, 1), + (f'Could not GET {native}. Received status code 429', 1, 0, 0, 2), + (f'Server returned HTTP response code: 429 for URL: {sdk}', 1, 9, 9, 2), + (f' Caused by: {gradle_error}: {get_error}', 1, 0, 0, 2), + (f' Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: {sdk}', 1, 0, 0, 2), + (f'Failed to get resource: GET. [HTTP HTTP/1.1 429 Too Many Requests: {native})]\n' + 'java.lang.AssertionError: expected a visible window', 7, 0, 7, 1), + ('AssertionError: expected 429', 7, 0, 7, 1), + (f'AssertionError: expected status code 429 for URL: {sdk}', 7, 0, 7, 1), + (f'Caused by: java.lang.AssertionError: {get_error}', 7, 0, 7, 1), + (f'Could not GET {central}other/group/lib.jar. Received status code 429', 8, 0, 8, 1), + ] + for message, first, retry, expected, attempts in cases: + with self.subTest(message=message), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + gradle = root / 'gradlew' + gradle.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> calls\n' + 'case "$*" in *-ProbolectricMavenMirror=*) exit "$RETRY";; esac\n' + 'echo "$MESSAGE"\nexit "$FIRST"\n') + gradle.chmod(0o755) + sleep = root / 'sleep' + sleep.write_text('#!/bin/sh\necho "sleep $*" >> calls\n') + sleep.chmod(0o755) + env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], + NDK_VERSION='test', MESSAGE=message, FIRST=str(first), RETRY=str(retry)) + result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env, capture_output=True, timeout=15) + self.assertEqual(result.returncode, expected, result.stdout) + calls = (root / 'calls').read_text().splitlines() + self.assertEqual(len(calls), attempts) + self.assertNotIn(mirror, calls[0]) + if attempts == 2: + self.assertEqual(calls[1].split(), [*calls[0].split(), mirror]) + + def test_unit_tests_back_off_on_maven_central_rate_limits(self): + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] + script = next(step['run'] for step in steps if step.get('id') == 'unit-tests') + rate_limit = ( + "Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: " + "Could not GET 'https://repo.maven.apache.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar'. " + "Received status code 429 from server: Too Many Requests" + ) + for exit_codes, expected_status, expected_events in ( + ([7, 0], 0, ['gradle', 'sleep 60', 'gradle']), + ([7, 9, 23, 0], 23, ['gradle', 'sleep 60', 'gradle', 'sleep 180', 'gradle']), + ): + with self.subTest(exit_codes=exit_codes), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'statuses').write_text(''.join(f'{code}\n' for code in exit_codes)) + gradle = root / 'gradlew' + gradle.write_text('#!/bin/sh\n' + 'echo gradle >> events\n' + 'echo "$*" >> gradle-args\n' + 'attempt=$(wc -l < gradle-args)\n' + 'status=$(sed -n "${attempt}p" statuses)\n' + 'if [ "$status" != 0 ]; then echo "$MAVEN_ERROR"; fi\n' + 'exit "${status:-99}"\n') + gradle.chmod(0o755) + sleep = root / 'sleep' + sleep.write_text('#!/bin/sh\necho "sleep $*" >> events\n') + sleep.chmod(0o755) + env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], + NDK_VERSION='test', MAVEN_ERROR=rate_limit) + result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env, + capture_output=True, text=True, timeout=15) + self.assertEqual(result.returncode, expected_status, result.stdout + result.stderr) + self.assertEqual((root / 'events').read_text().splitlines(), expected_events) + self.assertNotIn('-ProbolectricMavenMirror=', (root / 'gradle-args').read_text()) + + def test_unit_tests_do_not_hold_up_the_apk(self): + build = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text()) + for step in build['jobs']['build']['steps']: + self.assertNotIn('UnitTest', step.get('run', '')) + tests = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text()) + for event in ('push', 'pull_request'): + self.assertEqual(tests[True][event], build[True][event]) + authorship = yaml.safe_load((ROOT / '.github/workflows/authorship.yml').read_text()) + self.assertEqual(set(authorship[True]['workflow_run']['workflows']), {build['name'], tests['name']}) + self.assertIn('workflow_run.head_sha', authorship['concurrency']['group']) + self.assertFalse(authorship['concurrency']['cancel-in-progress']) + self.assertIn('unit-tests.yml', (ROOT / '.github/workflows/release.yml').read_text()) + run = next(step['run'] for step in tests['jobs']['unit-tests']['steps'] if step.get('id') == 'unit-tests') + self.assertIn('-PunitTestsOnly=true', run) + + def test_apk_and_unit_tests_pin_the_same_pr_event_base(self): + for filename, job, name in ( + ("build.yml", "source", "Pin and merge the APK source"), + ("unit-tests.yml", "unit-tests", "Merge the pinned APK base"), + ): + with self.subTest(workflow=filename): + workflow = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text()) + step = next(step for step in workflow["jobs"][job]["steps"] if step.get("name") == name) + self.assertEqual(step["env"]["PR_BASE_SHA"], "${{ github.event.pull_request.base.sha }}") + self.assertIn('git fetch --no-tags origin "$PR_BASE_SHA"', step["run"]) + self.assertIn("git merge --no-ff --no-edit FETCH_HEAD", step["run"]) + self.assertIn("github.event.pull_request.base.sha", workflow["run-name"]) + def test_independent_jobs_wait_only_for_the_pinned_source(self): jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] for name in ('xbox', 'python-tests', 'components-runner'): diff --git a/tools/tests/test_commit_waits_for_client_writes.py b/tools/tests/test_commit_waits_for_client_writes.py new file mode 100644 index 0000000000..2f31b9aff8 --- /dev/null +++ b/tools/tests/test_commit_waits_for_client_writes.py @@ -0,0 +1,300 @@ +"""A commit whose dma-buf the client's GPU is still writing is held until the buffer polls readable. + +The compiled functions come from compositor.c; libwayland's lists and event loop, poll and the clock are faked. +""" +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +SOURCE = Path(__file__).resolve().parents[2] / 'app/src/main/cpp/waylandcomp/src/compositor.c' + + +def function(text, name): + match = re.search(r'^(?:static )?[^\n;]+\b' + name + r'\([^;]*?\)\s*\{', text, re.M) + if not match: + raise AssertionError('Production function not found: ' + name) + pos = text.index('{', match.start()) + depth, end = 1, pos + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[match.start():end] + + +def block(text, start): + begin = text.index(start) + return text[begin:text.index('\n};\n', begin) + 4] + + +HARNESS = r''' +#include +#include +#include +#include +#include +#include +#define DAMAGE_RECTS 4 +#define POLLIN 1 +#define F_DUPFD_CLOEXEC 1030 +#define WL_EVENT_READABLE 1 +struct pollfd { int fd; short events, revents; }; +struct wl_list { struct wl_list *prev, *next; }; +struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); }; +static void wl_list_init(struct wl_list *l) { l->prev = l->next = l; } +static void wl_list_remove(struct wl_list *l) { l->prev->next = l->next; l->next->prev = l->prev; l->prev = l->next = NULL; } +static void wl_list_insert(struct wl_list *list, struct wl_list *elm) { + elm->prev = list; elm->next = list->next; list->next = elm; elm->next->prev = elm; +} +static void wl_list_insert_list(struct wl_list *list, struct wl_list *other) { + if (other->next == other) return; + other->next->prev = list; other->prev->next = list->next; list->next->prev = other->prev; list->next = other->next; +} +static int wl_list_length(const struct wl_list *l) { int n = 0; for (struct wl_list *e = l->next; e != l; e = e->next) n++; return n; } +#define wl_container_of(ptr, sample, member) (__typeof__(sample))((char *)(ptr) - offsetof(__typeof__(*sample), member)) + +struct dmabuf_buffer { int fd[4]; int n_planes; int ahb; }; +struct wl_resource { struct wl_list link; struct wl_listener *listener; struct dmabuf_buffer *db; int released, destroyed; }; +static struct wl_resource *from_link(struct wl_list *l) { return wl_container_of(l, (struct wl_resource *)0, link); } +#define wl_resource_for_each_safe(r, t, list) \ + for (r = from_link((list)->next), t = from_link(r->link.next); &r->link != (list); r = t, t = from_link(t->link.next)) +static void wl_resource_destroy(struct wl_resource *r) { wl_list_remove(&r->link); r->destroyed = 1; } +static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) { r->listener = l; wl_list_init(&l->link); } +static void client_destroys(struct wl_resource *r) { + if (r->listener) { struct wl_listener *l = r->listener; r->listener = NULL; l->notify(l, r); } +} + +static int ready[64], dup_of[64], next_dup = 40, closed[64]; +static int poll(struct pollfd *p, unsigned n, int timeout) { + if (n != 1 || timeout != 0 || p->events != POLLIN) { puts("FAIL poll args"); exit(1); } + return ready[p->fd] ? 1 : 0; +} +static int fcntl(int fd, int cmd, int arg) { (void)cmd; (void)arg; dup_of[next_dup] = fd; return next_dup++; } +static int close(int fd) { closed[fd]++; return 0; } +struct dd_frame_acquire { int fd_plus_one; }; +static void dd_frame_acquire_clear(struct dd_frame_acquire *f) { + if (f->fd_plus_one) close(f->fd_plus_one - 1); + f->fd_plus_one = 0; +} + +struct wl_event_source { int fd; int (*fd_cb)(int, uint32_t, void *); int (*timer_cb)(void *); void *data; int armed_ms, removed; }; +struct wl_event_loop; +struct wl_display; +static struct wl_display *g_display; +static struct wl_event_source sources[32]; +static int n_sources; +static struct wl_event_loop *wl_display_get_event_loop(struct wl_display *d) { (void)d; return NULL; } +static struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, uint32_t mask, + int (*cb)(int, uint32_t, void *), void *data) { + (void)l; (void)mask; struct wl_event_source *s = &sources[n_sources++]; memset(s, 0, sizeof(*s)); + s->fd = fd; s->fd_cb = cb; s->data = data; return s; +} +static struct wl_event_source *wl_event_loop_add_timer(struct wl_event_loop *l, int (*cb)(void *), void *data) { + (void)l; struct wl_event_source *s = &sources[n_sources++]; memset(s, 0, sizeof(*s)); + s->fd = -1; s->timer_cb = cb; s->data = data; return s; +} +static int wl_event_source_timer_update(struct wl_event_source *s, int ms) { s->armed_ms = ms; return 0; } +static int wl_event_source_remove(struct wl_event_source *s) { s->removed = 1; return 0; } +static void dispatch(int timers_expire) { + for (int i = 0; i < n_sources; i++) { + struct wl_event_source *s = &sources[i]; + if (s->removed) continue; + if (s->fd_cb && ready[dup_of[s->fd]]) s->fd_cb(s->fd, WL_EVENT_READABLE, s->data); + else if (s->timer_cb && s->armed_ms && timers_expire) { s->armed_ms = 0; s->timer_cb(s->data); } + } +} + +static int64_t clock_ns; +static int64_t now_ns(void) { return clock_ns; } +static struct { unsigned replaced; } g_pace; +static struct { unsigned commit_waits, commit_wait_limits; int64_t commit_wait_ns, commit_wait_max_ns; } g_perf; +static int logged; +static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; logged++; } +static void send_buffer_release(struct wl_resource *r) { r->released++; } +static unsigned feedback_discard_all(struct wl_list *list) { + unsigned n = 0; struct wl_resource *r, *t; wl_resource_for_each_safe(r, t, list) { wl_resource_destroy(r); n++; } return n; +} +static struct dmabuf_buffer *get_dmabuf(struct wl_resource *r) { return r ? r->db : NULL; } +static int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b) { return b->ahb; } +static int64_t rect_area(const int32_t *r, int bw, int bh) { (void)bw; (void)bh; return (int64_t)r[2] * r[3]; } + +struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; }; +struct surface { + struct wl_resource *resource, *xdg_toplevel; + int toplevel_committed; + struct wl_resource *pending_buffer; + struct dd_frame_acquire pending_frame_acquire; + struct wl_listener pending_buffer_destroy; + int pending_attach, pending_src_set, pending_dst_set, pending_opaque_set; + float pending_src[4]; + int pending_dst[2], pending_opaque[4]; + struct damage_list pending_damage_buf, pending_damage_local; + struct wl_list pending_frames, pending_feedback; + struct surface_state *waiting; + struct wl_event_source *waiting_source, *waiting_timer; + int waiting_fd; + int64_t waiting_since_ns; +}; +static void send_toplevel_configure(struct surface *s) { (void)s; } +struct wl_client; +static struct surface surf; + +STATE_STRUCT + +static int applies, applied_attach, applied_frames, applied_opaque, applied_damage; +static struct wl_resource *applied_buffer; +static void surface_state_apply(struct surface *s, struct surface_state *st); + +FUNCTIONS + +static void surface_state_apply(struct surface *s, struct surface_state *st) { + (void)s; + dd_frame_acquire_clear(&st->frame_acquire); + applies++; + applied_attach = st->attach; + applied_buffer = st->attach ? st->buffer : NULL; + applied_frames = wl_list_length(&st->frames); + applied_opaque = st->opaque_set ? st->opaque[2] : -1; + applied_damage = st->damage_buf.n; + if (st->attach) { wl_list_remove(&st->buffer_destroy.link); wl_list_init(&st->buffer_destroy.link); } + struct wl_resource *r, *t; + wl_resource_for_each_safe(r, t, &st->frames) wl_resource_destroy(r); + feedback_discard_all(&st->feedback); +} + +static struct wl_resource frame_res[16]; +static int n_frames; +static void attach(struct wl_resource *b) { + if (surf.pending_buffer) wl_list_remove(&surf.pending_buffer_destroy.link); + wl_list_init(&surf.pending_buffer_destroy.link); + surf.pending_buffer = b; surf.pending_attach = 1; +} +static void frame(void) { struct wl_resource *f = &frame_res[n_frames++]; wl_list_insert(surf.pending_frames.prev, &f->link); } +static void damage(int w) { surf.pending_damage_buf.r[surf.pending_damage_buf.n][2] = w; + surf.pending_damage_buf.r[surf.pending_damage_buf.n][3] = 1; surf.pending_damage_buf.n++; } +static void commit(void) { surface_commit(NULL, NULL); } +#define CHECK(c, what) do { if (!(c)) { printf("FAIL %s (line %d)\n", what, __LINE__); return 1; } } while (0) + +int main(void) { + wl_list_init(&surf.pending_frames); wl_list_init(&surf.pending_feedback); + wl_list_init(&surf.pending_buffer_destroy.link); + surf.waiting_fd = -1; + struct dmabuf_buffer d1 = {{10, -1}, 1, 0}, d2 = {{11, -1}, 1, 0}, d3 = {{12, -1}, 1, 0}, dz = {{13, -1}, 1, 1}; + struct wl_resource b1 = {.db = &d1}, b2 = {.db = &d2}, b3 = {.db = &d3}, bz = {.db = &dz}; + + ready[10] = 1; + attach(&b1); frame(); commit(); + CHECK(applies == 1 && applied_buffer == &b1 && applied_frames == 1 && !surf.waiting && n_sources == 0, "ready buffer"); + + ready[11] = 0; + clock_ns = 1000000; + attach(&b2); frame(); damage(5); commit(); + CHECK(applies == 1 && surf.waiting && surf.waiting_fd >= 40 && dup_of[surf.waiting_fd] == 11, "held"); + CHECK(sources[0].armed_ms == 0 && sources[1].armed_ms == 1000, "waits on the buffer with a 1 s limit"); + dispatch(0); + CHECK(applies == 1, "nothing before the writes end"); + clock_ns = 4000000; + ready[11] = 1; + dispatch(0); + CHECK(applies == 2 && applied_buffer == &b2 && applied_frames == 1 && applied_damage == 1 && !surf.waiting, "applied once ready"); + CHECK(closed[40] == 1 && sources[0].removed && sources[1].removed, "wait cleaned up"); + CHECK(g_perf.commit_waits == 1 && g_perf.commit_wait_max_ns == 3000000, "wait counted"); + + ready[11] = 0; ready[12] = 0; + attach(&b2); frame(); damage(7); commit(); + attach(&b3); frame(); damage(9); commit(); + CHECK(applies == 2 && b2.released == 1 && dup_of[surf.waiting_fd] == 12, "replaced while waiting"); + ready[12] = 1; + dispatch(0); + CHECK(applies == 3 && applied_buffer == &b3 && applied_frames == 2 && applied_damage == 2, "newest shown with both callbacks"); + CHECK(g_perf.commit_waits == 2, "merged wait counted once"); + + ready[11] = 0; + attach(&b2); commit(); + surf.pending_opaque[2] = 640; surf.pending_opaque_set = 1; frame(); commit(); + CHECK(applies == 3 && b2.released == 1 && dup_of[surf.waiting_fd] == 11, "the waiting buffer is not released"); + ready[11] = 1; + dispatch(0); + CHECK(applies == 4 && applied_buffer == &b2 && applied_opaque == 640 && applied_frames == 1, "buffer kept, opaque applied"); + + g_zero_copy_shown = &surf; + attach(&bz); commit(); + CHECK(applies == 5 && applied_buffer == &bz && !surf.waiting && g_unwaited == &surf, "zero-copy buffer"); + g_zero_copy_shown = NULL; + ready[13] = 0; + attach(&bz); commit(); + CHECK(applies == 5 && surf.waiting, "a droiddeck-ahb buffer not shown zero-copy waits"); + ready[13] = 1; + dispatch(0); + CHECK(applies == 6 && !g_unwaited, "waited buffer clears the mark"); + ready[13] = 0; + + ready[10] = 0; + attach(&b1); frame(); commit(); + client_destroys(&b1); + ready[10] = 1; + dispatch(0); + CHECK(applies == 7 && !applied_attach && applied_frames == 1, "destroyed buffer dropped from the commit"); + + ready[11] = 0; + attach(&b2); commit(); + dispatch(1); + CHECK(applies == 8 && applied_buffer == &b2 && g_perf.commit_wait_limits == 1 && logged == 1 && !surf.waiting, "limit"); + + ready[11] = 0; ready[12] = 0; + clock_ns = 10000000000; + attach(&b2); commit(); + CHECK(applies == 8 && sources[n_sources - 1].armed_ms == 1000, "held again"); + clock_ns += 600000000; + attach(&b3); commit(); + CHECK(applies == 8 && surf.waiting && sources[n_sources - 1].armed_ms == 400, "a newer commit keeps the first deadline"); + clock_ns += 500000000; + attach(&b2); commit(); + CHECK(applies == 9 && applied_buffer == &b2 && g_perf.commit_wait_limits == 2 && !surf.waiting, "commits past the deadline are applied at once"); + puts("PASS"); + return 0; +} +''' + + +class CommitWaitsForClientWritesTest(unittest.TestCase): + def test_commits_wait_for_the_clients_gpu_writes(self): + compiler = shutil.which(os.environ.get('CC', 'cc')) + if not compiler: + self.skipTest('A host C compiler is required') + source = SOURCE.read_text() + functions = '\n'.join(re.search(pattern, source, re.M).group(0) for pattern in + (r'^#define COMMIT_WAIT_LIMIT_MS .*$', r'^static struct surface \*g_zero_copy_shown, \*g_unwaited;$')) + '\n' + '\n'.join( + function(source, name) for name in + ('note_damage', 'on_state_buffer_destroyed', 'surface_state_take', 'state_unfinished_fd', + 'surface_state_discard', 'surface_state_merge', 'surface_wait_stop', 'surface_wait_end', 'on_commit_ready', + 'on_commit_wait_limit', 'surface_wait_start', 'surface_commit')) + probe = HARNESS.replace('STATE_STRUCT', block(source, 'struct surface_state {')).replace('FUNCTIONS', functions) + probe = probe.replace('struct surface *s = wl_resource_get_user_data(r);', 'struct surface *s = &surf; (void)r;') + with tempfile.TemporaryDirectory(prefix='droiddeck-commit-wait-') as temp: + folder = Path(temp) + (folder / 'probe.c').write_text(probe) + built = subprocess.run([compiler, '-std=gnu11', '-Wall', '-Wextra', '-Wno-unused-parameter', '-Wno-unused-function', + str(folder / 'probe.c'), '-o', str(folder / 'probe')], + capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + run = subprocess.run([str(folder / 'probe')], capture_output=True, text=True, timeout=10) + self.assertEqual(run.returncode, 0, run.stdout + run.stderr) + self.assertEqual(run.stdout.strip(), 'PASS') + + def test_scenes_settle_an_unwaited_buffer_before_copying_it(self): + body = function(SOURCE.read_text(), 'render_scene').splitlines() + copies = [i for i, line in enumerate(body) if 'vkp_render(w, h, dl.d, dl.n)' in line] + self.assertGreaterEqual(len(copies), 4) + for i in copies: + self.assertTrue(any('settle_unwaited();' in line for line in body[max(0, i - 3):i]), body[i]) + text = '\n'.join(body) + self.assertIn('if (hdr_route == 1 || hdr_route == 2) settle_unwaited();', text) + self.assertIn('settle_unwaited();\n render_stream();', text) + self.assertIn('if (r == 0 && !fg_pass) g_zero_copy_shown = ls;\n else settle_unwaited();', text) + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_ddfg_flow_levels.py b/tools/tests/test_ddfg_flow_levels.py index d5efd6355d..eb5f5a0186 100644 --- a/tools/tests/test_ddfg_flow_levels.py +++ b/tools/tests/test_ddfg_flow_levels.py @@ -40,6 +40,7 @@ class DdfgFlowLevelsTest(unittest.TestCase): "-Wno-missing-field-initializers", "-Wno-misleading-indentation", "-I" + str(work / "include"), "-I" + str(CHAIN), str(ROOT / "tools/tests/ddfg_flow_levels_harness.cpp"), str(CHAIN / "framegen.cpp"), + str(CHAIN / "ddfg_engine.cpp"), "-o", str(cls.binary), ], capture_output=True, text=True, timeout=120) if build.returncode: @@ -97,6 +98,38 @@ class DdfgFlowLevelsTest(unittest.TestCase): with self.subTest(model=model): self.run_case("preset", model=model, generations=3, repeats=4) + def test_many_resizes_do_not_accumulate_scratch_resources(self): + for model in (3, 4): + for preset in range(3): + with self.subTest(model=model, preset=preset): + self.run_case("resize", model=model, preset=preset, generations=3, repeats=16) + + def test_same_size_engine_restarts_use_fresh_scratch(self): + self.run_case("restart", generations=3, repeats=8) + + def test_instances_do_not_share_or_destroy_each_others_scratch(self): + self.run_case("instances", generations=3, repeats=3) + + def test_engine_teardown_waits_before_destroying_its_input_ring(self): + self.run_case("engine", generations=3) + + def test_failed_gpu_wait_stops_recording_and_retains_resources(self): + for mode in ("idle-failure", "destroy-failure", "engine-failure"): + with self.subTest(mode=mode): + self.run_case(mode, generations=3) + + def test_descriptor_pool_reset_failure_does_not_free_live_scratch(self): + self.run_case("reset-failure", generations=3) + + def test_partial_resize_allocation_is_cleaned_up(self): + self.run_case("partial", generations=3) + + def test_steady_frames_and_same_size_prepare_add_no_gpu_waits(self): + self.run_case("steady", generations=3, repeats=10) + + def test_scope_exit_releases_resources_without_an_explicit_destroy(self): + self.run_case("automatic", generations=3, repeats=3) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_desktop_return_gaming.py b/tools/tests/test_desktop_return_gaming.py new file mode 100644 index 0000000000..d059205b5f --- /dev/null +++ b/tools/tests/test_desktop_return_gaming.py @@ -0,0 +1,75 @@ +import os +import re +import shlex +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DESKTOP = ROOT / "tools/linuxfs/desktop" +SCRIPT = (DESKTOP / "droiddeck-desktop").read_text() +ENTRY = (DESKTOP / "droiddeck-return-gaming.desktop").read_text() + + +class DesktopReturnGamingTest(unittest.TestCase): + def session(self, logout, rc=0, bottom=False): + with tempfile.TemporaryDirectory() as tmp: + run = Path(tmp, "run") + launched = Path(tmp, "launched") + exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1) + inner = shlex.split(exec_line)[2].replace("dbus-send", "true") + plasma = Path(tmp, "plasma") + plasma.write_text("#!/bin/sh\n%s\nexit %d\n" % (inner if logout == "return" else ":", rc)) + plasma.chmod(0o755) + steam = Path(tmp, "steam-launch") + steam.write_text('#!/bin/sh\necho "$*" > %s\n' % launched) + steam.chmod(0o755) + tail = SCRIPT[SCRIPT.index("return_gaming="):] + tail = tail.replace("dbus-run-session -- startplasma-wayland", str(plasma)) + tail = tail.replace("/usr/local/bin/droiddeck-pipewire stop", ":") + tail = tail.replace("/usr/local/bin/droiddeck-steam-launch", str(steam)) + tail = tail.replace("sleep 30", ":") + tail = tail.replace("/run/droiddeck", str(run)) + plasma.write_text(plasma.read_text().replace("/run/droiddeck", str(run))) + env = {k: v for k, v in os.environ.items() if k != "DD_BOTTOM_DESKTOP"} + if bottom: + env["DD_BOTTOM_DESKTOP"] = "1" + run.mkdir() + (run / "return-gaming").write_text("") + status = subprocess.run(["sh", "-c", tail], env=env, capture_output=True, text=True).returncode + return status, launched.read_text().strip() if launched.exists() else None, (run / "return-gaming").exists() + + def test_return_to_gaming_mode_opens_steam(self): + self.assertEqual(self.session("return"), (0, "bigpicture", False)) + + def test_log_out_goes_back_without_steam_even_after_an_earlier_request(self): + self.assertEqual(self.session("logout"), (0, None, False)) + + def test_a_failed_session_and_the_bottom_desktop_never_open_steam(self): + self.assertEqual(self.session("return", rc=1)[:2], (1, None)) + self.assertEqual(self.session("return", bottom=True)[:2], (0, None)) + + def test_the_logout_request_outlives_starting_the_shutdown_service(self): + exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1) + call = shlex.split(shlex.split(exec_line)[2].split(";")[-1]) + self.assertEqual(call[0], "dbus-send") + self.assertIn("--print-reply", call) + + def test_a_rejected_logout_request_forgets_the_return_to_gaming_mode(self): + exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1) + with tempfile.TemporaryDirectory() as tmp: + inner = shlex.split(exec_line)[2].replace("/run/droiddeck", tmp) + for sender, kept in (("true", True), ("false", False)): + subprocess.run(["sh", "-c", inner.replace("dbus-send", sender, 1)], check=False) + self.assertEqual(Path(tmp, "return-gaming").exists(), kept) + + def test_the_app_ships_the_shortcut_with_the_script(self): + source = (ROOT / "app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt").read_text() + self.assertIn('"usr/share/applications/droiddeck-return-gaming.desktop" to ' + '"usr/share/applications/droiddeck-return-gaming.desktop"', source) + self.assertIn("droiddeck-return-gaming.desktop", (ROOT / "tools/release/check_session_assets.py").read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index 72931860b7..0e055df0a2 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -247,6 +247,15 @@ class AgentTest(unittest.TestCase): {"window": 13, "map": "viewable", "class": "steam_app_550", "pid": None}] self.assertEqual(self.tag(wins), (False, [])) + def test_a_proton_window_run_in_a_worker_takes_its_process_app_id(self): + # a store game's Wine process handed to a worker: its parent is zygote, not the reaper + self.fake_proc(50, 1, "SplinterCell.exe", {"SteamAppId": "2565121641", "SteamGameId": "11017113558390407168"}) + self.fake_proc(20, 1, "reaper", {}) + self.fake_proc(21, 20, "Bully.exe", {"SteamAppId": "12200"}) + wins = [{"window": 14, "map": "viewable", "class": "steam_app_2565121641", "pid": 50}, + {"window": 15, "map": "viewable", "class": "steam_app_12200", "pid": 21}] + self.assertEqual(self.tag(wins), (True, ["2565121641"])) + def test_the_x86_client_still_tags_its_game_classes(self): win = {"window": 13, "map": "viewable", "class": "steam_app_550", "pid": None} self.assertEqual(self.tag([win], arch="x86_64"), (True, ["550"])) diff --git a/tools/tests/test_droiddeckctl.py b/tools/tests/test_droiddeckctl.py index 59f187a7f5..8a15ec92a3 100644 --- a/tools/tests/test_droiddeckctl.py +++ b/tools/tests/test_droiddeckctl.py @@ -59,7 +59,10 @@ FAKE_ADB = textwrap.dedent('''\ print(config.get("dumpsys_input", "")) elif args[:3] == ["shell", "uinput", "-"]: entry["stdin"] = sys.stdin.read() - if "uinput_stdout" in config: + if config.get("uinput_numeric_only") and '"UI_SET_EVBIT"' in entry["stdin"]: + print("Error reading in object, ignoring.") + entry["denied"] = True + elif "uinput_stdout" in config: print(config["uinput_stdout"]) else: for line in entry["stdin"].splitlines(): diff --git a/tools/tests/test_droiddeckctl_gamepad.py b/tools/tests/test_droiddeckctl_gamepad.py index 201a92e599..fbb0fcb71b 100644 --- a/tools/tests/test_droiddeckctl_gamepad.py +++ b/tools/tests/test_droiddeckctl_gamepad.py @@ -86,6 +86,46 @@ class GamepadTest(FakeAdbTest): code, out = self.gamepad("a") self.assertEqual((3, "UINPUT_FAILED"), (code, out["error"]["code"])) + def test_android_13_gets_numeric_codes_and_no_sync(self): + self.configure({}, uinput_probe="sdk=33") + code, out = self.gamepad("guide", "down", "--hold", "50", "--gap", "100") + self.assertEqual((0, True), (code, out["ok"])) + commands = self.script() + register = commands[0] + bits = {c["type"]: c["data"] for c in register["configuration"]} + self.assertEqual([1, 3], bits[100]) + self.assertIn(316, bits[101]) + self.assertEqual({0, 1, 3, 4, 16, 17}, set(bits[103])) + self.assertEqual(set(bits[103]), {a["code"] for a in register["abs_info"]}) + injected = [c["events"] for c in commands if c["command"] == "inject"] + self.assertEqual([[1, 316, 1, 0, 0, 0], [1, 316, 0, 0, 0, 0], [3, 17, 1, 0, 0, 0], [3, 17, 0, 0, 0, 0]], injected) + self.assertEqual([], [c for c in commands if c["command"] == "sync"]) + self.assertFalse(any(isinstance(v, str) for c in commands for v in c.get("events", []))) + + def test_android_13_uinput_that_rejects_the_script_fails(self): + self.configure({}, uinput_probe="sdk=33", uinput_stdout="Error reading in object, ignoring.") + code, out = self.gamepad("a") + self.assertEqual((3, "UINPUT_FAILED"), (code, out["error"]["code"])) + self.assertIn("Error reading in object", out["error"]["message"]) + + def test_android_14_before_qpr2_is_retried_with_numeric_codes(self): + self.configure({}, uinput_probe="sdk=34", uinput_numeric_only=True) + code, out = self.gamepad("guide") + self.assertEqual((0, True), (code, out["ok"])) + named, numeric = [c for c in self.calls() if c["args"][:3] == ["shell", "uinput", "-"]] + self.assertIn('"UI_SET_EVBIT"', named["stdin"]) + commands = [json.loads(line) for line in numeric["stdin"].splitlines()] + self.assertEqual(100, commands[0]["configuration"][0]["type"]) + self.assertEqual([], [c for c in commands if c["command"] == "sync"]) + + def test_android_14_keeps_named_codes_and_sync(self): + self.configure({}, uinput_probe="sdk=34") + code, _ = self.gamepad("a") + self.assertEqual(0, code) + commands = self.script() + self.assertEqual("UI_SET_EVBIT", commands[0]["configuration"][0]["type"]) + self.assertEqual("sync", commands[-1]["command"]) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_droiddeckctl_pen.py b/tools/tests/test_droiddeckctl_pen.py index a4dcf5cc54..90ace8fe01 100644 --- a/tools/tests/test_droiddeckctl_pen.py +++ b/tools/tests/test_droiddeckctl_pen.py @@ -225,6 +225,30 @@ class PenUinputTest(FakeAdbTest): self.assertIn(message, out["error"]["message"]) self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]]) + def test_android_13_gets_numeric_codes_and_no_sync(self): + self.configure({}, dumpsys_input=dumpsys_input(), uinput_probe="sdk=33") + code, out = self.pen("tap", "0.5", "0.5") + self.assertEqual((0, True), (code, out["ok"])) + commands = self.script() + bits = {c["type"]: c["data"] for c in commands[0]["configuration"]} + # Android 13 has no virtual bus. + self.assertEqual("usb", commands[0]["bus"]) + self.assertEqual({100: [1, 3], 101: [320, 321, 330, 331, 332], 103: [0, 1, 24, 25, 26, 27], 110: [1]}, bits) + self.assertEqual({0, 1, 24, 25, 26, 27}, {a["code"] for a in commands[0]["abs_info"]}) + self.assertEqual([], [c for c in commands if c["command"] == "sync"]) + self.assertFalse(any(isinstance(v, str) for c in commands for v in c.get("events", []))) + + def test_android_14_before_qpr2_is_retried_with_numeric_codes_on_the_usb_bus(self): + self.configure({}, dumpsys_input=dumpsys_input(), uinput_probe="sdk=34", uinput_numeric_only=True) + code, out = self.pen("tap", "0.5", "0.5") + self.assertEqual((0, True), (code, out["ok"])) + named, numeric = [c for c in self.calls() if c["args"][:3] == ["shell", "uinput", "-"]] + register = named["stdin"].splitlines()[0] + # Its codes are read before the virtual bus, which an older `uinput` rejects without the retry message. + self.assertLess(register.index('"configuration"'), register.index('"bus": "virtual"')) + commands = [json.loads(line) for line in numeric["stdin"].splitlines()] + self.assertEqual(("usb", 100), (commands[0]["bus"], commands[0]["configuration"][0]["type"])) + def test_uinput_that_stops_early_fails(self): self.configure({}, dumpsys_input=dumpsys_input(), uinput_stdout="") code, out = self.pen("tap", "0.5", "0.5") diff --git a/tools/tests/test_effects_lazy_pipelines.py b/tools/tests/test_effects_lazy_pipelines.py new file mode 100644 index 0000000000..9f2782989d --- /dev/null +++ b/tools/tests/test_effects_lazy_pipelines.py @@ -0,0 +1,68 @@ +import pathlib +import unittest + + +ROOT = pathlib.Path(__file__).resolve().parents[2] +SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/effects_chain.c" + + +def function_body(source: str, signature: str) -> str: + start = source.index(signature) + opening = source.index("{", start) + depth = 0 + for pos in range(opening, len(source)): + if source[pos] == "{": + depth += 1 + elif source[pos] == "}": + depth -= 1 + if depth == 0: + return source[opening + 1:pos] + raise AssertionError(f"unterminated function: {signature}") + + +class LazyEffectPipelineSourceTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.source = SOURCE.read_text(encoding="utf-8") + + def test_shared_setup_does_not_create_graphics_pipelines(self): + body = function_body(self.source, "static int objects_ensure(void)") + self.assertNotIn("post_pipeline_for_renderpass(", body) + self.assertNotIn("shader(upscale_vert_code", body) + self.assertIn("effect pipelines are created when needed", body) + + def test_pipelines_are_prepared_before_effect_chain_resources_and_draws(self): + body = function_body(self.source, "static VkImage effects_run(") + prepare = body.index("pipelines_ensure(spatial, s)") + scene = body.index("scene_ensure(scene, scene_w, scene_h)") + self.assertLess(prepare, scene) + self.assertIn("objects_ensure() == 0 && pipelines_ensure(spatial, s) == 0", body) + + def test_lazy_path_covers_active_upscalers_and_effects(self): + body = function_body(self.source, "static int pipelines_ensure(") + for required in ( + "spatial == 3", "spatial == 8", "spatial == 4 || spatial == 5", + "spatial == 6", "spatial == 7", "cas_active(s)", + "s->color_on", "s->aa_mode == 1 || s->aa_mode == 2", + "s->aa_mode == 2", "s->toon", "s->hdr_on", "s->ntsc", + "s->crt", "deband_active(s)", + ): + with self.subTest(required=required): + self.assertIn(required, body) + + def test_existing_fallback_pipelines_are_prepared(self): + body = function_body(self.source, "static int pipelines_ensure(") + self.assertIn("s->aa_mode == 1 || s->aa_mode == 2", body) + self.assertIn("else if (g_upscale_half) MK(1, P_SGSR, sgsr_half_code", body) + self.assertIn("if (!g_nis_fast) MK(1, P_NIS, nis_code", body) + + def test_failed_preparation_uses_whole_chain_fallback(self): + body = function_body(self.source, "static int pipelines_ensure(") + self.assertIn("return chain_failed();", body) + failure = function_body(self.source, "static int chain_failed(void)") + self.assertIn("objects_destroy();", failure) + self.assertIn("g_ready = -1;", failure) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_effects_source_cache.py b/tools/tests/test_effects_source_cache.py index d42045b1cf..163bef4bb6 100644 --- a/tools/tests/test_effects_source_cache.py +++ b/tools/tests/test_effects_source_cache.py @@ -57,6 +57,12 @@ class EffectsSourceCacheTest(unittest.TestCase): def test_resize_replaces_the_cached_view_and_descriptor(self): self.check_cache('resize') + def test_generated_frames_keep_separate_descriptors_until_completion(self): + self.check_cache('generated') + + def test_generated_settings_snapshot_and_source_layout_restoration(self): + self.check_cache('generated-layout') + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_effects_source_resolution.py b/tools/tests/test_effects_source_resolution.py index 0862114a48..38ca6f9f3c 100644 --- a/tools/tests/test_effects_source_resolution.py +++ b/tools/tests/test_effects_source_resolution.py @@ -31,7 +31,7 @@ class EffectsSourceResolutionTest(unittest.TestCase): 'static int draw_to_scene_blit(', 'static int effects_source_draw(', 'static void effects_source_note(', 'static void effects_overlay_draws(', - 'static int render_impl(', 'static int pass_begin_impl(')) + 'static int render_impl(', 'static int pass_begin_impl(', 'static int pass_finish(', 'int vkp_pass_copy_generated(')) functions = (re.search(r'static int spatial_mode\([^\n]+', effects).group() + '\n' + re.search(r'static int cas_active\([^\n]+', effects).group() + '\n' + function(effects, 'int vkp_effects_upscaling(') + @@ -106,6 +106,12 @@ class EffectsSourceResolutionTest(unittest.TestCase): def test_frame_generation_keeps_upscaling_and_sharpening_at_panel_size(self): self.check_case('framegen-sharpening') + def test_frame_generation_runs_spatial_post_upscale(self): + self.check_case('framegen-upscale') + + def test_display_layer_interpolates_before_the_spatial_upscale(self): + self.check_case('framegen-layer-upscale') + TYPES = r''' #include @@ -113,6 +119,7 @@ TYPES = r''' #include #include #include +#include typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter, VkBuffer; typedef int VkImageLayout, VkPipelineStageFlags, VkImageUsageFlags; typedef uint64_t VkDeviceSize; @@ -157,7 +164,7 @@ typedef struct { #define HDR_FMT 101 #define FG_HDR_FMT 102 #define VK_FORMAT_R8G8B8A8_UNORM SCENE_FMT -#define VKP_FG_MAX_GENERATIONS 2 +#define VKP_FG_MAX_GENERATIONS 3 #define HDRC_OUT_PQ 1 #define HDRC_OUT_SDR 2 #define droiddeck_log(...) ((void)0) @@ -176,6 +183,8 @@ typedef struct AHardwareBuffer AHardwareBuffer; STUBS = r''' +static void zfg_discard_history_update(void) {} +static void zfg_commit_history_update(void) {} static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { (void)cmd; (void)draws; (void)count; } static int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { return dmabuf && !staged; } static void quarantine_pending_work(VkResult result, const char *where) { (void)result; (void)where; } @@ -204,14 +213,14 @@ static int g_dev_state = 1, g_window = 1, g_swapchain, g_swap_extra; static int g_colorspace_ext, g_swap_hdr_unavailable, g_swap_is_hdr, g_swap_hdr_want; static int g_plain_frame, g_first_frame_done, g_base_black; static int g_qfam, g_queue, g_dev, g_fence, g_swap_fmt = SCENE_FMT; -static int g_cmds[3], g_acqs[3], g_rnds[3] = {11, 12, 13}, g_rnd_count = 3, images[1] = {2}, *g_images = images; +static int g_cmds[4], g_acqs[4], g_rnds[4] = {11, 12, 13, 14}, g_rnd_count = 4, images[1] = {2}, *g_images = images; static uint32_t g_swap_md_identity; static VkExtent2D g_extent = {1920, 1080}; static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map; static struct { VkImage img; int w, h; } g_scene; struct vkp_img_slot { VkImage img; int w, h; }; static struct vkp_img_slot g_hdrscene, g_fgscene; -static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; +static struct { int active, rw, rh, ow, oh, post_upscale, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf; static int effects_active = 1, framegen, cardboard; struct fx_settings { int scaling, cas_on, cas_pct; }; @@ -277,8 +286,47 @@ static VkImage vkp_effects_run(int cmd, int source, int w, int h, int ow, int oh if (fail_effects) { *rw = w; *rh = h; return source; } *rw = ow; *rh = oh; return 4; } -static int vkp_framegen_run(int cmd, int result, int depth, int w, int h, int format, int *generated) { return 0; } +static int vkp_effects_prepare_generated(void) { + return g_cur.scaling >= 3 && g_cur.scaling <= 8 && g_cur.scaling != 6 && !postprocessing; +} +static VkImage vkp_effects_run_before_generated(int cmd, int source, int w, int h, int *rw, int *rh) { + return vkp_effects_run(cmd, source, w, h, w, h, rw, rh); +} +static int generations, post_count, fg_w, fg_h; +static int post_sources[4], screen_widths[4], screen_heights[4], screen_images[4]; +static int vkp_framegen_run(int cmd, int result, int depth, int w, int h, int format, int *generated) { + fg_w = w; fg_h = h; + for (int i = 0; i < generations; i++) generated[i] = 20 + i; + return generations; +} +static void vkp_effects_release_generated_sources(void) {} +static void vkp_framegen_set_layer_timing(int layer) {} +static int g_wait_sem, blit_count, blit_src_w[4], blit_src_h[4], blit_dst_w[4], blit_dst_h[4]; +static VkImage blit_src_images[4], blit_dst_images[4]; +static VkImageLayout blit_layouts[4]; +static int take_wait_fd(int fd) { return fd < 0 ? 0 : fd; } +static void blit_to_layer(int cmd, VkImage src, VkImageLayout layout, struct vkp_image *dst, + const VkImageBlit *blit, VkFilter filter) { + assert(blit_count < 4); + blit_src_images[blit_count] = src; blit_dst_images[blit_count] = dst->image; + blit_layouts[blit_count] = layout; + blit_src_w[blit_count] = blit->srcOffsets[1].x; blit_src_h[blit_count] = blit->srcOffsets[1].y; + blit_dst_w[blit_count] = blit->dstOffsets[1].x; blit_dst_h[blit_count] = blit->dstOffsets[1].y; + blit_count++; +} +static void vkp_framegen_completed(void) {} +static VkImage vkp_effects_run_generated(int cmd, int source, int w, int h, int ow, int oh, + int slot, int *rw, int *rh) { + assert(slot == post_count && slot < 4); + assert(w == fg_w && h == fg_h); + post_sources[post_count++] = source; + *rw = fail_effects ? w : ow; *rh = fail_effects ? h : oh; + return fail_effects ? source : 40 + slot; +} static void record_screen_blit(int cmd, int result, int w, int h, int sw, int sh, int image, int filter, int cb) { + assert(screen_count < 4); + screen_widths[screen_count] = w; screen_heights[screen_count] = h; + screen_images[screen_count] = result; screen_count++; logical_w = sw; logical_h = sh; } static void device_lost(const char *reason) {} @@ -302,6 +350,7 @@ static void reset(void) { effects_active = 1; g_cur = (struct fx_settings){4}; framegen = cardboard = fail_scene = fail_effects = postprocessing = g_plain_frame = 0; g_pass.active = 0; g_extent = (VkExtent2D){1920, 1080}; + generations = post_count = fg_w = fg_h = 0; image.w = 1280; image.h = 720; } static void check_helper(void) { @@ -575,24 +624,96 @@ static void check_allocation(void) { assert(recorded_blits[1].dstOffsets[1].x == 1920 && recorded_blits[1].dstOffsets[1].y == 1080); assert(target_w == 1920 && target_h == 1080); } -static void check_framegen_output(int scaling, int cas, int grading, int panel) { +static void check_framegen_output(int scaling, int cas, int grading, int panel, int post_upscale) { reset(); framegen = 1; postprocessing = grading; g_cur = (struct fx_settings){scaling, cas, cas ? 60 : 0}; g_extent = (VkExtent2D){2880, 1620}; struct vkp_draw draw = fullscreen(); run_path(0, &draw, 1, NULL); assert(effects_count == 1); - assert(output_w == (panel ? 2880 : 1920) && output_h == (panel ? 1620 : 1080)); + if (post_upscale) { + assert(output_w == 1280 && output_h == 720); + assert(screen_count == 1); + assert(screen_widths[0] == 2880 && screen_heights[0] == 1620); + } else { + assert(output_w == (panel ? 2880 : 1920) && output_h == (panel ? 1620 : 1080)); + } } static void check_framegen_sharpening(void) { - check_framegen_output(4, 0, 0, 1); - check_framegen_output(3, 0, 0, 1); - check_framegen_output(8, 0, 0, 1); - check_framegen_output(0, 1, 1, 1); - check_framegen_output(1, 1, 1, 1); - check_framegen_output(0, 0, 1, 0); - check_framegen_output(6, 0, 0, 0); - check_framegen_output(2, 0, 1, 0); + check_framegen_output(4, 0, 0, 1, 1); + check_framegen_output(3, 0, 0, 1, 1); + check_framegen_output(8, 0, 0, 1, 1); + check_framegen_output(0, 1, 1, 1, 0); + check_framegen_output(1, 1, 1, 1, 0); + check_framegen_output(0, 0, 1, 0, 0); + check_framegen_output(6, 0, 0, 0, 0); + check_framegen_output(2, 0, 1, 0, 0); +} +static void check_framegen_upscale(void) { + for (int count = 0; count <= VKP_FG_MAX_GENERATIONS; count++) { + reset(); framegen = 1; generations = count; + struct vkp_draw draw = fullscreen(); + run_path(0, &draw, 1, NULL); + assert(fg_w == 1280 && fg_h == 720); + assert(post_count == count + 1 && screen_count == count + 1); + for (int k = 0; k < screen_count; k++) { + assert(screen_widths[k] == 1920 && screen_heights[k] == 1080); + assert(post_sources[k] == (k < count ? 20 + k : 4)); + assert(screen_images[k] == 40 + k); + } + } + for (int mode = 0; mode <= 8; mode++) { + reset(); framegen = 1; g_cur.scaling = mode; + struct vkp_draw draw = fullscreen(); + run_path(0, &draw, 1, NULL); + assert(post_count == (mode >= 3 && mode != 6)); + } + reset(); framegen = 1; fail_effects = 1; + struct vkp_draw draw = fullscreen(); + run_path(0, &draw, 1, NULL); + assert(post_count == 1 && screen_widths[0] == 1280 && screen_heights[0] == 720); + assert(screen_images[0] == 1); + reset(); framegen = 1; postprocessing = 1; + run_path(0, &draw, 1, NULL); assert(post_count == 0); + reset(); framegen = 1; cardboard = 1; + run_path(0, &draw, 1, NULL); assert(post_count == 0); + reset(); framegen = 1; + struct vkp_hdr_frame hdr = {0}; + run_path(0, &draw, 1, &hdr); assert(post_count == 0); +} +static void check_framegen_layer_upscale(void) { + reset(); framegen = 1; generations = 2; + struct vkp_draw draw = fullscreen(); + int rw = 0, rh = 0; + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 1, &rw, &rh) == 0); + assert(effects_count == 1 && output_w == 1280 && output_h == 720); + assert(fg_w == 1280 && fg_h == 720); + assert(g_pass.post_upscale && g_pass.rw == 1280 && g_pass.rh == 720); + assert(rw == 1920 && rh == 1080); + struct vkp_image generated_dst[2] = {{.image = 50, .w = 1920, .h = 1080, .blit_dst = 1}, {.image = 51, .w = 1920, .h = 1080, .blit_dst = 1}}; + struct vkp_image real_dst = {.image = 52, .w = 1920, .h = 1080, .blit_dst = 1}; + struct vkp_image *generated_ptrs[2] = {&generated_dst[0], &generated_dst[1]}; + g_pass.gens[0] = 20; g_pass.gens[1] = 21; g_pass.result = 4; g_pass.ngen = 2; + assert(vkp_pass_copy_generated(generated_ptrs, 2, &real_dst, -1) == 0); + assert(post_count == 3 && blit_count == 3); + assert(post_sources[0] == 20 && post_sources[1] == 21 && post_sources[2] == 4); + for (int i = 0; i < 3; i++) { + assert(blit_src_images[i] == 40 + i); + assert(blit_dst_images[i] == 50 + i); + assert(blit_layouts[i] == VK_IMAGE_LAYOUT_GENERAL); + } + for (int i = 0; i < 3; i++) { + assert(blit_src_w[i] == 1920 && blit_src_h[i] == 1080); + assert(blit_dst_w[i] == 1920 && blit_dst_h[i] == 1080); + } + reset(); framegen = 1; postprocessing = 1; + draw = fullscreen(); + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 1, &rw, &rh) == 0); + assert(!g_pass.post_upscale && rw == g_pass.rw && rh == g_pass.rh); + reset(); framegen = 1; + draw = fullscreen(); + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 0, &rw, &rh) == 0); + assert(!g_pass.post_upscale); } int main(int argc, char **argv) { assert(argc == 2); reset(); @@ -610,6 +731,8 @@ int main(int argc, char **argv) { else if (!strcmp(argv[1], "overlay-barriers")) check_overlay_barriers(); else if (!strcmp(argv[1], "postprocessing")) check_postprocessing(); else if (!strcmp(argv[1], "framegen-sharpening")) check_framegen_sharpening(); + else if (!strcmp(argv[1], "framegen-upscale")) check_framegen_upscale(); + else if (!strcmp(argv[1], "framegen-layer-upscale")) check_framegen_layer_upscale(); else assert(0); puts("PASS"); } diff --git a/tools/tests/test_fakeinput_bionic.py b/tools/tests/test_fakeinput_bionic.py new file mode 100644 index 0000000000..68f06430a3 --- /dev/null +++ b/tools/tests/test_fakeinput_bionic.py @@ -0,0 +1,30 @@ +from pathlib import Path +import re +import unittest + +SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp" + + +def code_only(text): + """The source without its comments and string literals.""" + text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S) + text = re.sub(r"//[^\n]*", " ", text) + return re.sub(r'"(?:\\.|[^"\\\n])*"', '""', text) + + +class FakeinputBionicTest(unittest.TestCase): + # DroidDeck-Bionic preloads this library into its Wine processes (tools/bionic-runtime/build.sh). bionic + # exports no __chk_fail: a library that names it there cannot be loaded, so no Wine program starts + # ("cannot locate symbol "__chk_fail""). + def test_glibcs_fortify_failure_is_named_only_off_bionic(self): + code = code_only(SOURCE.read_text()) + guarded = re.compile(r"#if defined\(__BIONIC__\)\n(?P.*?)#else\n(?P.*?)#endif\n", re.S) + blocks = [m for m in guarded.finditer(code) if "__chk_fail" in m.group("glibc")] + self.assertTrue(blocks, "the glibc-only __chk_fail is behind #if defined(__BIONIC__) ... #else") + for block in blocks: + self.assertNotIn("__chk_fail", block.group("bionic")) + self.assertNotIn("__chk_fail", guarded.sub("", code)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fakeinput_ring.py b/tools/tests/test_fakeinput_ring.py index b032f8ea76..c3d625fbc7 100644 --- a/tools/tests/test_fakeinput_ring.py +++ b/tools/tests/test_fakeinput_ring.py @@ -29,14 +29,21 @@ PAD_TYPE_STEAM = 1 READER = r""" #include #include +#include #include #include #include +ssize_t __read_chk(int fd, void *buffer, size_t size, size_t buffer_size); +int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fds_size); + static int vector_count; +static int fortified; static ssize_t controller_read(int fd, void *buffer, size_t size) { + if (fortified) + return __read_chk(fd, buffer, size, size); if (!vector_count) return read(fd, buffer, size); struct iovec vectors[3] = { @@ -53,7 +60,8 @@ static ssize_t controller_read(int fd, void *buffer, size_t size) int main(int argc, char **argv) { - vector_count = argc > 1 ? (argv[1][0] == '1' ? 1 : 3) : 0; + fortified = argc > 1 && argv[1][0] == 'f'; + vector_count = argc > 1 && !fortified ? (argv[1][0] == '1' ? 1 : 3) : 0; struct input_event events[64]; int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK); if (fd < 0) { @@ -62,11 +70,17 @@ int main(int argc, char **argv) } while (controller_read(fd, events, sizeof(events)) > 0) ; + struct pollfd idle = {fd, POLLIN, 0}; + if (fortified && __poll_chk(&idle, 1, 0, sizeof(idle)) != 0) + return 3; puts("ready"); fflush(stdout); char go; if (read(0, &go, 1) != 1) return 1; + struct pollfd ready = {fd, POLLIN, 0}; + if (fortified && (__poll_chk(&ready, 1, 1000, sizeof(ready)) != 1 || !(ready.revents & POLLIN))) + return 2; ssize_t got = controller_read(fd, events, sizeof(events)); for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++) printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type, @@ -345,7 +359,7 @@ class FakeinputRingTest(unittest.TestCase): subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True) return library, binary - def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER): + def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER, fortified=False): if not virtual: program = program.replace("event16", "event0") library, reader = self.build(bits, program, "reader") @@ -359,7 +373,7 @@ class FakeinputRingTest(unittest.TestCase): overlay_library = self.tmp / "overlay.so" subprocess.run(["gcc", bits, "-shared", "-fPIC", "-o", str(overlay_library), str(source)], check=True) env["LD_PRELOAD"] = str(overlay_library) + ":" + str(library) - command = [str(reader)] + ([str(vectors)] if vectors else []) + command = [str(reader)] + (["fortified"] if fortified else [str(vectors)] if vectors else []) process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True) self.addCleanup(process.kill) self.assertEqual(process.stdout.readline(), "ready\n") @@ -381,6 +395,10 @@ class FakeinputRingTest(unittest.TestCase): self.assertEqual(self.read_through("-m64"), "1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n") + def test_a_fortified_guest_polls_and_reads_the_ring(self): + self.assertEqual(self.read_through("-m64", virtual=False, fortified=True), + "1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n") + def test_readv_reads_events_instead_of_the_backing_file(self): self.assertEqual(self.read_through("-m64", vectors=1), "1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n") diff --git a/tools/tests/test_fex_guest_stack_reserve.py b/tools/tests/test_fex_guest_stack_reserve.py new file mode 100644 index 0000000000..d965aa6ba6 --- /dev/null +++ b/tools/tests/test_fex_guest_stack_reserve.py @@ -0,0 +1,73 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch" +LOADER = "Source/Tools/FEXInterpreter/ELFCodeLoader.h" +MIN_GAP = 128 * 1024 * 1024 +STACK = 128 * 1024 * 1024 +PAGE = 4096 + + +def lines(sign): + return [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith(sign) and not line.startswith(sign * 3)] + + +def reservation(top, rlimit): + top = (top + PAGE - 1) & ~(PAGE - 1) + gap = min(max(rlimit, MIN_GAP), max(top // 6 * 5, MIN_GAP)) + 256 * PAGE + return (top - gap if top > gap else 0, top) + + +def place(hint, low, high): + if hint < high and hint + STACK > low and low > STACK: + hint = (low - STACK) & ~(PAGE - 1) + return hint + + +class FexGuestStackReserveTest(unittest.TestCase): + def test_only_the_elf_loader_changes(self): + self.assertEqual([LOADER], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + def test_nothing_is_removed(self): + self.assertEqual([], lines("-")) + + def test_the_reserve_starts_at_the_end_of_the_host_environment(self): + added = lines("+") + self.assertIn("uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast(__builtin_frame_address(0));", added) + self.assertIn("uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast(Limit.rlim_cur) : MinGap;", added) + self.assertIn("Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize;", added) + + def test_every_stack_hint_is_checked_against_the_reserve(self): + text = PATCH.read_text() + self.assertLess(text.index("HostStackReservation(PageSize);"), text.index("do {")) + self.assertLess(text.index("do {"), text.index("StackHint = (HostStackLow - FULL_STACK_SIZE)")) + self.assertLess(text.index("StackHint = (HostStackLow - FULL_STACK_SIZE)"), text.index("// Allocate the base of the full 128MB stack range.")) + + def test_a_guest_stack_overlapping_the_reserve_moves_below_it(self): + host_env_end = 0x7FFC391000 + low, high = reservation(host_env_end, 8 * 1024 * 1024) + hint = place((1 << 39) - STACK, low, high) + self.assertLessEqual(hint + STACK, low) + self.assertGreaterEqual(host_env_end - (hint + STACK), MIN_GAP) + + def test_a_guest_stack_clear_of_the_reserve_stays_put(self): + low, high = reservation(0x7FC491C000, 8 * 1024 * 1024) + hint = (1 << 39) - STACK + self.assertEqual(hint, place(hint, low, high)) + + def test_a_larger_stack_limit_widens_the_reserve(self): + low, _ = reservation(0x7FFC391000, 512 * 1024 * 1024) + self.assertEqual(0x7FFC391000 - 512 * 1024 * 1024 - 256 * PAGE, low) + + def test_an_unlimited_stack_limit_keeps_room_for_the_guest(self): + low, _ = reservation(0x7FFC391000, (1 << 64) - 1) + self.assertGreater(low, STACK) + + def test_no_comments_are_added(self): + self.assertFalse([line for line in lines("+") if line.startswith(("//", "/*"))]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_frame_acquire_peer_gate.py b/tools/tests/test_frame_acquire_peer_gate.py new file mode 100644 index 0000000000..e39b41469b --- /dev/null +++ b/tools/tests/test_frame_acquire_peer_gate.py @@ -0,0 +1,81 @@ +"""Focused worker-grant contract; no Android or guest boot required.""" +import os +import sys +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT=Path(__file__).resolve().parents[2] +SRC=ROOT/'app/src/main/cpp/waylandcomp/src' +JAVA=ROOT/'app/src/main/java/com/droiddeck/launcher' + + +class FrameAcquirePeerGateTest(unittest.TestCase): + def test_app_issued_identity_and_executable_mapping(self): + with tempfile.TemporaryDirectory() as tmp: + image=Path(tmp)/'probe' + subprocess.run([os.environ.get('CC','cc'), '-std=c11','-Wall','-Wextra','-Werror', + '-I',str(SRC),str(Path(__file__).with_name('frame_worker_peer_test.c')), + '-o',str(image)],check=True) + subprocess.run([str(image)],check=True,timeout=10) + + @unittest.skipUnless(sys.platform.startswith("linux"), "Requires Linux procfs and pidfd") + def test_live_worker_mapping_starttime_and_revocation(self): + with tempfile.TemporaryDirectory() as tmp: + image = Path(tmp) / "probe" + subprocess.run([os.environ.get("CC", "cc"), "-std=c11", "-Wall", "-Wextra", "-Werror", + "-I", str(SRC), str(Path(__file__).with_name("frame_worker_peer_live_test.c")), + "-o", str(image)], check=True) + subprocess.run([str(image)], check=True, timeout=10) + + def test_publish_before_worker_go_and_require_map_at_bind(self): + workers=(JAVA/'runtime/GuestWorkers.kt').read_text() + broker=workers.split("private fun start(",1)[1].split("private fun takeWarm",1)[0] + check=broker.index("if (stopping() || !confirmed())") + publish=broker.index("FrameAcquireWorkerProbe.publish",check) + self.assertLess(publish,broker.index("Os.write(go[1]",check)) + self.assertIn("if (slot.service === service) startTicks else 0L",broker) + self.assertIn("val size = reply.dataAvail()",broker) + self.assertIn("if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)",broker) + service=workers.split("override fun onTransact",1)[1].split("Handler(",1)[0] + self.assertIn("data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG",service) + self.assertIn("Binder.getCallingUid() == Process.myUid()",service) + self.assertIn("data.dataAvail() == Int.SIZE_BYTES",service) + self.assertIn("reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))",service) + self.assertIn('if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke',workers) + comp=(SRC/'compositor.c').read_text() + bind=comp.split('static void bind_frame_acquire',1)[1].split('#endif',1)[0] + self.assertIn('frame_acquire_peer_allowed(client, true, true)',bind) + self.assertIn('poll(&alive, 1, 0) == 0',comp) + + + def test_admission_diagnostics_are_coarse_bounded_and_probe_only(self): + kt=(JAVA/'runtime/FrameAcquireWorkerProbe.kt').read_text() + comp=(SRC/'compositor.c').read_text() + jni=(SRC/'waylandcomp_jni.c').read_text() + prepare=kt.split('fun prepare(',1)[1].split('fun arm(',1)[0] + match=kt.split('fun match(',1)[1].split('fun publish(',1)[0] + self.assertIn('!WaylandCompositor.frameWorkerProbeEnabled()',prepare) + self.assertIn('context.assets.open("linuxfs" + PATH)',prepare) + self.assertIn('context.assets.open("linuxfs" + SESSION_SCRIPT)',prepare) + svc=(JAVA/'session/SessionService.kt').read_text() + self.assertIn('SessionPrefs.producerAcquireFences(this)',svc) + self.assertIn('nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment',svc) + prefs=(JAVA/'session/SessionPrefs.kt').read_text() + self.assertIn('getBoolean("producerAcquireFences", false)',prefs) + self.assertLess(match.index('?: return null'),match.index('breadcrumb(')) + self.assertIn('"--version" !in argv',match) + self.assertIn('if (reported.add(stage))',kt) + self.assertIn('"worker_admission=" + reason.name',kt) + for name in ('MATCH_ACK','MATCH_OWNER','MATCH_EXPIRED','MATCH_PATH','MATCH_ROOT', + 'MATCH_ARGV','MATCH_FILE','MATCH_DIGEST','QUALIFIED','PUBLISH_TICKET', + 'PUBLISH_RESTAT','PUBLISH_NATIVE','PUBLISH_RECEIPT','RESERVED'): + self.assertIn('Reason.'+name,kt) + self.assertIn(' return JNI_FALSE;\n#endif',jni.split('frameWorkerProbeEnabled(',1)[1]) + self.assertIn('if (!frame_worker_map_reported)',comp) + for name in ('NATIVE_FILE','NATIVE_PIDFD','NATIVE_STAT_OPEN_DENIED','NATIVE_STAT_OPEN_HIDDEN', + 'NATIVE_STAT_OPEN_OTHER','NATIVE_STAT_READ','NATIVE_STAT_PARSE','NATIVE_STAT_ZERO', + 'NATIVE_STAT_MISMATCH','NATIVE_PIDFD_NOT_LIVE','NATIVE_ALREADY_RESERVED', + 'MAP_STARTTIME','MAP_OPEN','MAP_IDENTITY'): + self.assertIn('"worker_admission='+name+'"',comp) diff --git a/tools/tests/test_frame_acquire_protocol.py b/tools/tests/test_frame_acquire_protocol.py new file mode 100644 index 0000000000..a17fa02f78 --- /dev/null +++ b/tools/tests/test_frame_acquire_protocol.py @@ -0,0 +1,166 @@ +"""Exercise production receiver and attachment replacement with Unix FD passing. + +This Linux fixture stubs Wayland resources and only the success/status values of +SYNC_IOC_FILE_INFO. It does not claim a Vulkan or SurfaceFlinger hardware test. +""" +import os +from pathlib import Path +import platform +import subprocess +import tempfile +import unittest + +from test_vk_pending_completion import function + +SRC = Path(__file__).resolve().parents[2] / 'app/src/main/cpp/waylandcomp/src' +HEAD = r''' +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +static int query_status, query_result; +static unsigned query_count; +static int test_ioctl(int fd, unsigned long request, void *arg) { + assert(fd >= 0 && request == SYNC_IOC_FILE_INFO); + struct sync_file_info *info = arg; + assert(!info->flags && !info->sync_fence_info); + query_count++; + info->status = query_status; + info->num_fences = 1; + return query_result; +} +#define ioctl test_ioctl +#include "frame_acquire.h" +#undef ioctl +#include "wayland-util.h" +void wl_list_init(struct wl_list *list) { list->prev = list->next = list; } +void wl_list_remove(struct wl_list *list) { (void)list; } +struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); }; +struct wl_client { int identity; }; +struct wl_resource { struct wl_client *owner; void *data; int type; unsigned error; }; +struct surface { + struct wl_resource *pending_buffer; + struct wl_listener pending_buffer_destroy; + struct dd_frame_acquire pending_frame_acquire; + int pending_attach; +}; +static int wl_surface_interface, surface_impl; +static int peer_allowed=1; +static int frame_acquire_peer_allowed(const struct wl_client *c, bool verify_exec, bool bind) { (void)c; (void)verify_exec; (void)bind; return peer_allowed; } +static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return r->owner; } +static void *wl_resource_get_user_data(struct wl_resource *r) { return r->data; } +static int wl_resource_instance_of(struct wl_resource *r, const void *iface, const void *impl) { + assert(iface == &wl_surface_interface && impl == &surface_impl); + return r->type == 1; +} +static int get_dmabuf(struct wl_resource *r) { return r->type == 2; } +static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) { (void)r; (void)l; } +static void wl_resource_post_error(struct wl_resource *r, unsigned err, const char *why) { + assert(why && !r->error); + r->error = err+1; +} +''' +TAIL = r''' +/* Real descriptor transfer and sender close; before dispatch, receiver owns it. */ +static int tx(int fd) { + int conn[2]; char byte = 'F'; + assert(socketpair(AF_UNIX, SOCK_DGRAM, 0, conn) == 0); + union { struct cmsghdr a; char bytes[CMSG_SPACE(sizeof(fd))]; } control = {0}; + struct iovec payload = {.iov_base=&byte, .iov_len=1}; + struct msghdr msg = {.msg_iov=&payload, .msg_iovlen=1, .msg_control=control.bytes, + .msg_controllen=sizeof(control.bytes)}; + struct cmsghdr *h = CMSG_FIRSTHDR(&msg); + h->cmsg_len=CMSG_LEN(sizeof(fd)); h->cmsg_level=SOL_SOCKET; h->cmsg_type=SCM_RIGHTS; + memcpy(CMSG_DATA(h), &fd, sizeof(fd)); + assert(sendmsg(conn[0], &msg, 0) == 1); + assert(close(fd) == 0); + memset(&control, 0, sizeof(control)); + assert(recvmsg(conn[1], &msg, MSG_CMSG_CLOEXEC) == 1); + assert(!(msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) && byte == 'F'); + h=CMSG_FIRSTHDR(&msg); + assert(h && h->cmsg_len==CMSG_LEN(sizeof(fd)) && h->cmsg_level==SOL_SOCKET && h->cmsg_type==SCM_RIGHTS); + memcpy(&fd, CMSG_DATA(h), sizeof(fd)); + close(conn[0]); close(conn[1]); + return fd; +} +static int transmit_fd(void) { + int p[2]; assert(pipe(p) == 0); close(p[1]); return tx(p[0]); +} +static void closed(int fd) { + assert(fcntl(fd, F_GETFD) == -1 && errno == EBADF); +} +int main(void) { + struct wl_client client={1}, unrelated={2}; + struct surface s={0}; + struct wl_resource manager={.owner=&client}, surf={.owner=&client,.data=&s,.type=1}; + struct wl_resource buf={.owner=&client,.type=2}, other={.owner=&client,.type=2}; + struct wl_resource wrong_owner={.owner=&unrelated,.type=2}, not_dmabuf={.owner=&client,.type=3}; + int fd=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,fd); + assert(manager.error == 1 && !query_count); closed(fd); + + surface_attach(&client,&surf,&buf,0,0); + struct wl_resource *bad[] = {&other, &wrong_owner, ¬_dmabuf, NULL}; + for (unsigned i=0; i=0 && display_fd!=fd && (fcntl(display_fd,F_GETFD)&FD_CLOEXEC)); + close(display_fd); + int duplicate=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,duplicate); + assert(manager.error==2 && query_count==1); closed(duplicate); + + /* The same Wayland buffer, attached a second time, is a different write. */ + surface_attach(&client,&surf,&buf,0,0); + assert(dd_frame_acquire_dup(&s.pending_frame_acquire)==-1); closed(fd); + for (int status=0; status>=-2; status--) { + manager.error=0; query_status=status; + if (status==-2) query_result=-1; /* non-sync file ioctl failure */ + fd=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,fd); + assert(manager.error == 3 && !s.pending_frame_acquire.fd_plus_one); closed(fd); + } + manager.error=0; query_result=0; query_status=1; + fd=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,fd); + assert(!manager.error); + on_pending_buffer_destroyed(&s.pending_buffer_destroy,NULL); + assert(!s.pending_buffer && !s.pending_frame_acquire.fd_plus_one); closed(fd); + peer_allowed=0; manager.error=0; + surface_attach(&client,&surf,&buf,0,0); + fd=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,fd); + assert(manager.error==4&&!s.pending_frame_acquire.fd_plus_one);closed(fd); + return 0; +} +''' + + +@unittest.skipUnless(platform.system() == 'Linux', 'Linux sync_file UAPI') +class FrameAcquireProtocolTest(unittest.TestCase): + def test_production_receiver_rejects_invalid_and_keeps_exact_attachment(self): + comp = (SRC / 'compositor.c').read_text() + protocol = (SRC.parent / 'generated/droiddeck-frame-acquire-v1-server-protocol.h').read_text() + errors = protocol.split('enum droiddeck_frame_acquire_v1_error {', 1)[1].split('};', 1)[0] + actual = '\n'.join(function(comp, name) for name in ( + 'on_pending_buffer_destroyed', 'surface_attach', 'frame_acquire_set')) + with tempfile.TemporaryDirectory(prefix='droiddeck-frame-acquire-') as tmp: + probe = Path(tmp) / 'probe.c' + exe = Path(tmp) / 'probe' + probe.write_text(HEAD + '\nenum droiddeck_frame_acquire_v1_error {' + errors + '};\n' + actual + TAIL) + subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu11', '-Wall', '-Wextra', + '-Werror', '-Wno-unused-parameter', '-UNDEBUG', '-fsanitize=address,undefined', + '-I', str(SRC), '-I', str(SRC.parent / 'prebuilt/include'), + str(probe), '-o', str(exe)], check=True) + subprocess.run([str(exe)], check=True, timeout=10) diff --git a/tools/tests/test_framegen_ring_lifetime.py b/tools/tests/test_framegen_ring_lifetime.py new file mode 100644 index 0000000000..082edc32ba --- /dev/null +++ b/tools/tests/test_framegen_ring_lifetime.py @@ -0,0 +1,61 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from test_vk_pending_completion import function + + +class FramegenRingLifetimeTest(unittest.TestCase): + def test_ring_forgets_effect_sources_before_releasing_images(self): + compiler = shutil.which(os.environ.get('CC', 'cc')) + if not compiler: + self.skipTest('A host C compiler is required') + root = Path(__file__).resolve().parents[2] + source = (root / 'app/src/main/cpp/waylandcomp/src/framegen_bridge.c').read_text() + code = r''' +#include +#include +#include +#include +static int g_dev, g_engine_ok = 1, idle, forgotten[4], images, views, memory, engine; +static uint32_t g_ring_n = 3; +static struct { int img, view, mem; } g_ring[3]; +static void wait_idle(int d) { idle++; } +static void vkp_effects_forget_image(int image) { assert(idle == 1); forgotten[image]++; } +static void destroy_image(int d, int image, const void *a) { + assert(forgotten[image] == 1); images++; +} +static void destroy_view(int d, int view, const void *a) { assert(idle == 1); views++; } +static void free_memory(int d, int mem, const void *a) { assert(images > memory); memory++; } +static void fge_forget_targets(void) { assert(images == 3); engine++; } +static void vkp_framegen_set_layer_timing(int layer) { (void)layer; } +static void vkp_framegen_completed(void) {} +static struct { + void (*DeviceWaitIdle)(int); + void (*DestroyImage)(int, int, const void *); + void (*DestroyImageView)(int, int, const void *); + void (*FreeMemory)(int, int, const void *); +} vk = {wait_idle, destroy_image, destroy_view, free_memory}; +''' + code += function(source, 'destroy_ring') + code += r''' +int main(void) { + for (int i = 0; i < 3; i++) g_ring[i].img = g_ring[i].view = g_ring[i].mem = i + 1; + destroy_ring(); + assert(g_ring_n == 0 && images == 3 && views == 3 && memory == 3 && engine == 1); + for (int i = 0; i < 3; i++) assert(!g_ring[i].img && !g_ring[i].view && !g_ring[i].mem); + destroy_ring(); + assert(idle == 1 && engine == 1); +} +''' + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + probe = folder / 'ring.c' + binary = folder / 'ring' + probe.write_text(code) + subprocess.run([compiler, '-std=c11', str(probe), '-o', str(binary)], check=True, + capture_output=True, text=True) + subprocess.run([str(binary)], check=True, capture_output=True, timeout=10) diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index 1136d86f52..93977654d7 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -122,6 +122,16 @@ class UpscalerSettingsTest(unittest.TestCase): shutil.rmtree(prefix) +class ProducerAcquireGameEnvironmentTest(unittest.TestCase): + def test_prefixed_opt_in_enters_only_the_game_environment(self): + key = "DROIDDECK_GAME_FRAME_ACQUIRE" + scope = MODULE["GAME_PREFIX"] + key + self.assertEqual({}, MODULE["game_gpu"]({scope: "1"}, keep=True)) + self.assertEqual({key: "1"}, MODULE["game_gpu"]({scope: "1"})) + self.assertEqual({}, MODULE["game_gpu"]({key: "1", scope: ""})) + self.assertEqual({}, MODULE["game_gpu"]({})) + + class SupergiantDotnetReporterTest(unittest.TestCase): def test_allows_the_builtin_mscoree_for_supergiant_reporter(self): game = mock.Mock(files={"basecampbugreporter.native.dll"}) @@ -1680,6 +1690,48 @@ class GameEnvironmentTest(unittest.TestCase): (other / "Other.exe").touch() self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], [])) + def test_original_xbox_games_get_the_emulator_fixes_instead_of_the_dotnet_preset(self): + expected = {"FEX_TSOENABLED": "1", "FEX_VECTORTSOENABLED": "0", "FEX_MEMCPYSETTSOENABLED": "0", + "FEX_HALFBARRIERTSOENABLED": "1", "FEX_X87REDUCEDPRECISION": "1", "WINE_SPECIAL_APC_INTERRUPT": "1", + "FEX_SYNCX87CONTEXT": "1", "FEX_LOOPSUSPENDCHECK": "1", "FEX_SAFEIMAGEMAP": "1", + "WINE_MF_DISPLAY_APERTURE": "1", "WINE_PRECISE_SLEEP": "1", "VKD3D_INTEROP_PRESENT": "1", + "VKD3D_PACKED_422": "1"} + + def package(folder, identity): + (folder / "EmuMenu").mkdir(parents=True) + for name in ("Emu.exe", "EmuMenu/EmuMenu.exe", "EmuMenu/coreclr.dll"): + (folder / name).touch() + (folder / "MicrosoftGame.config").write_text( + '' + '' % identity) + + with tempfile.TemporaryDirectory() as tmp: + game = Path(tmp) / "Fuzion Frenzy" + package(game, "Xbox360BackwardCompatibil.PrimaryFuzionFrenzyFuzio") + for exe in (game / "Emu.exe", game / "EmuMenu/EmuMenu.exe"): + env, extra, notes = MODULE["engine_fixes"](str(exe), [], "2773102903") + self.assertEqual((env, extra), (expected, [])) + self.assertEqual(len(notes), 1) + self.assertTrue(notes[0].startswith("Original Xbox game")) + config = {"version": 1, "games": {"2773102903": {"FEX_X87REDUCEDPRECISION": "0", "VKD3D_PACKED_422": None}}} + result = MODULE["apply_config"]({}, config, "2773102903", env) + self.assertEqual(result["FEX_X87REDUCEDPRECISION"], "0") + self.assertNotIn("VKD3D_PACKED_422", result) + self.assertEqual(result["WINE_SPECIAL_APC_INTERRUPT"], "1") + store = Path(tmp) / "Psychonauts" + package(store, "Microsoft.PsychonautsforWindows10") + env, extra, notes = MODULE["engine_fixes"](str(store / "Emu.exe"), []) + self.assertEqual(env, MODULE["DOTNET_FEX"]) + self.assertEqual(notes, [".NET runtime: FEX with full TSO"]) + (store / "MicrosoftGame.config").write_text(" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct wl_buffer {}; +static struct { void debugf(const char *, ...) {} void errorf(const char *, ...) { ++oh_no; } int oh_no = 0; } xdg_log; +namespace droiddeck::frame_trace { enum class Event { OutputRelease }; inline void Record(Event) {} } + +namespace gamescope +{ + PICK + + class IWaitable + { + public: + virtual ~IWaitable() {} + virtual int GetFD() { return -1; } + virtual void OnPollOut() {} + virtual void OnPollHangUp() {} + }; + + template + class CAsyncWaiter + { + public: + CAsyncWaiter( const char * ) {} + bool AddWaitable( IWaitable *p, uint32_t ) { waiting.push_back( p ); return true; } + void RemoveWaitable( IWaitable *p ) { std::erase( waiting, p ); } + std::vector waiting; + }; + + class CWaylandBackend; + + class CBaseBackendFb + { + public: + uint32_t IncRef() { return refs++; } + uint32_t DecRef() { return --refs; } + bool ShowsClientBuffer() const { return client; } + uint32_t refs = 1; + bool client = false; + }; + + class CWaylandFb final : public CBaseBackendFb + { + public: + CWaylandFb( int nDmabufFd ) : m_pHostBuffer{ &m_Buffer }, m_nDmabufFd{ nDmabufFd } {} + void OnCompositorAcquire(); + void OnCompositorRelease(); + void OnScanoutDone( uint64_t ulAcquireSerial ); + void Wayland_Buffer_Release( wl_buffer *pBuffer ); + wl_buffer m_Buffer; + wl_buffer *m_pHostBuffer; + int m_nDmabufFd = -1; + std::mutex m_AcquireMutex; + uint64_t m_ulAcquireSerial = 0; + bool m_bCompositorAcquired = false; + }; + + SCANOUT + + METHODS +} +''' + +MAIN = r''' +using namespace gamescope; + +static CAsyncWaiter<> &waiter() { return CWaylandScanoutRelease::Waiter(); } + +struct Display { + int fds[2]; + Display() { assert( pipe2( fds, O_NONBLOCK ) == 0 ); } + ~Display() { close( fds[0] ); close( fds[1] ); } + void scanning() { char b[4096] = {}; while ( write( fds[1], b, sizeof( b ) ) > 0 ) {} } + void done() { char b[4096]; while ( read( fds[0], b, sizeof( b ) ) > 0 ) {} } + int fd() { return fds[1]; } +}; + +static void fire() { + assert( waiter().waiting.size() == 1 ); + waiter().waiting.front()->OnPollOut(); + assert( waiter().waiting.empty() ); +} + +int main( int argc, char **argv ) { + std::string which = argv[1]; + Display d; + CWaylandFb fb{ fcntl( d.fd(), F_DUPFD_CLOEXEC, 0 ) }; + if ( which == "client-scanning" ) { + fb.client = true; + fb.OnCompositorAcquire(); + assert( fb.refs == 2 ); + d.scanning(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 3 && fb.m_bCompositorAcquired ); + d.done(); + fire(); + assert( fb.refs == 1 && !fb.m_bCompositorAcquired && xdg_log.oh_no == 0 ); + } else if ( which == "stale-wait-keeps-buffer" ) { + fb.client = true; + fb.OnCompositorAcquire(); + d.scanning(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + fb.OnCompositorAcquire(); + d.done(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 2 && !fb.m_bCompositorAcquired ); + fire(); + assert( fb.refs == 1 && xdg_log.oh_no == 0 ); + } else if ( which == "client-idle" ) { + fb.client = true; + fb.OnCompositorAcquire(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 1 && waiter().waiting.empty() ); + } else if ( which == "composite-scanning" ) { + fb.OnCompositorAcquire(); + d.scanning(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 1 && waiter().waiting.empty() ); + } else if ( which == "shown-again" ) { + fb.client = true; + fb.OnCompositorAcquire(); + d.scanning(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + fb.OnCompositorAcquire(); + d.done(); + fire(); + assert( fb.refs == 2 && fb.m_bCompositorAcquired ); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 1 && !fb.m_bCompositorAcquired && xdg_log.oh_no == 0 ); + } else if ( which == "no-dmabuf" ) { + CWaylandFb plain{ -1 }; + plain.client = true; + plain.OnCompositorAcquire(); + plain.Wayland_Buffer_Release( plain.m_pHostBuffer ); + assert( plain.refs == 1 && waiter().waiting.empty() ); + } else { + return 2; + } + return 0; +} +''' + + +class ForwardedBufferScanoutTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cxx = shutil.which(os.environ.get("CXX", "c++")) + if not cxx: + raise AssertionError("C++ compiler required") + pick = post_image(PICK, "src/output_image_pick.hpp") + pick = pick[pick.index("struct OutputImagePick"):pick.rindex("}")] + wayland = post_image(FORWARD, "src/Backends/WaylandBackend.cpp") + scanout = block(wayland, " class CWaylandScanoutRelease", "\n };\n") + methods = "\n".join(block(wayland, " void CWaylandFb::" + name) for name in + ("OnCompositorAcquire()", "OnCompositorRelease()", "OnScanoutDone(", "Wayland_Buffer_Release(")) + source = PREAMBLE.replace("PICK", pick).replace("SCANOUT", scanout).replace("METHODS", methods) + MAIN + cls.tmp = tempfile.TemporaryDirectory(prefix="droiddeck-forwarded-scanout-") + cls.addClassCleanup(cls.tmp.cleanup) + probe = Path(cls.tmp.name) / "probe.cpp" + probe.write_text(source) + cls.binary = probe.with_suffix("") + built = subprocess.run([cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-UNDEBUG", + "-include", "string", str(probe), "-o", str(cls.binary)], capture_output=True, text=True) + if built.returncode: + raise AssertionError(built.stdout + built.stderr) + + def scenario(self, name): + result = subprocess.run([str(self.binary), name], capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_forwarded_buffer_is_held_until_scanout_ends(self): + self.scenario("client-scanning") + + def test_idle_forwarded_buffer_is_released_at_once(self): + self.scenario("client-idle") + + def test_composite_output_image_keeps_the_release_at_latch(self): + self.scenario("composite-scanning") + + def test_buffer_shown_again_waits_for_its_next_release(self): + self.scenario("shown-again") + + def test_pending_wait_keeps_the_buffer_after_a_later_release(self): + self.scenario("stale-wait-keeps-buffer") + + def test_buffer_without_dmabuf_is_released_at_once(self): + self.scenario("no-dmabuf") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_ime_prepare.py b/tools/tests/test_ime_prepare.py new file mode 100644 index 0000000000..e3bf3a1f59 --- /dev/null +++ b/tools/tests/test_ime_prepare.py @@ -0,0 +1,134 @@ +'''Regression tests for tools/ime/prepare.py RPM extraction.''' + +import contextlib +import importlib.util +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import tempfile +import unittest +from unittest import mock + + +MODULE_PATH = Path(__file__).resolve().parents[1] / 'ime' / 'prepare.py' +SPEC = importlib.util.spec_from_file_location('ime_prepare', MODULE_PATH) +PREPARE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(PREPARE) +NUL = bytes(1) + + +def _newc(files): + archive = bytearray() + for inode, (name, data) in enumerate(files.items(), start=1): + encoded = name.encode('utf-8') + name_size = len(encoded) + 1 + header = '070701' + ''.join(f'{value:08x}' for value in ( + inode, 0o100644, 0, 0, 1, 0, len(data), 0, 0, 0, 0, name_size, 0)) + archive += header.encode('ascii') + archive += encoded + NUL + archive += NUL * (-(110 + name_size) % 4) + archive += data + archive += NUL * (-len(data) % 4) + trailer = b'TRAILER!!!' + NUL + header = '070701' + ''.join(f'{value:08x}' for value in ( + 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, len(trailer), 0)) + archive += header.encode('ascii') + archive += trailer + archive += NUL * (-(110 + len(trailer)) % 4) + return bytes(archive) + + +class ExtractTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + + def _write_executable(self, path, text): + path.write_text(text, encoding='utf-8') + path.chmod(0o755) + + def _tools(self, base, cpio, payload=None, exit_code=1): + tools = base / 'bin' + tools.mkdir(parents=True) + fixture = base / 'payload.cpio' + if payload is None: + script = f'''#!/bin/sh +echo rpm2cpio failed >&2 +exit {exit_code} +''' + else: + fixture.write_bytes(payload) + script = f'''#!/bin/sh +exec cat {shlex.quote(str(fixture))} +''' + self._write_executable(tools / 'rpm2cpio', script) + self._write_executable(tools / 'cpio', f'''#!/bin/sh +exec {shlex.quote(str(cpio))} "$@" +''') + return tools + + @contextlib.contextmanager + def _path(self, tools): + with mock.patch.dict(os.environ, + {'PATH': str(tools) + os.pathsep + os.environ.get('PATH', '')}): + yield + + def _cpio_candidates(self): + candidates = [] + for command in ('cpio', 'bsdcpio'): + path = shutil.which(command) + if path: + candidates.append((command, Path(path))) + return candidates + + def test_extract_normal_payload_with_available_cpio(self): + candidates = self._cpio_candidates() + if not candidates: + self.skipTest('no cpio implementation is available') + payload = _newc({'usr/share/demo.txt': b'hello'}) + for command, cpio in candidates: + with self.subTest(cpio=command): + base = self.root / ('normal-' + command) + base.mkdir() + tools = self._tools(base, cpio, payload) + destination = base / 'destination' + with self._path(tools): + PREPARE.extract('demo', base / 'demo.rpm', destination) + self.assertEqual((destination / 'usr/share/demo.txt').read_bytes(), b'hello') + + def test_extract_rejects_unsafe_paths_before_writing(self): + candidates = self._cpio_candidates() + if not candidates: + self.skipTest('no cpio implementation is available') + cpio = candidates[0][1] + for label in ('absolute', 'parent'): + with self.subTest(case=label): + base = self.root / ('unsafe-' + label) + base.mkdir() + outside = base / (label + '-escaped.txt') + name = str(outside) if label == 'absolute' else '../' + outside.name + tools = self._tools(base, cpio, _newc({'payload/safe.txt': b'safe', name: b'bad'})) + destination = base / 'destination' + with self._path(tools), self.assertRaises(ValueError) as caught: + PREPARE.extract('unsafe', base / 'unsafe.rpm', destination) + self.assertIn('unsafe path', str(caught.exception)) + self.assertFalse((destination / 'payload/safe.txt').exists()) + self.assertFalse(outside.exists()) + + def test_extract_propagates_rpm2cpio_failure(self): + candidates = self._cpio_candidates() + if not candidates: + self.skipTest('no cpio implementation is available') + base = self.root / 'failed' + base.mkdir() + tools = self._tools(base, candidates[0][1], exit_code=7) + with self._path(tools), self.assertRaises(subprocess.CalledProcessError) as caught: + PREPARE.extract('broken', base / 'broken.rpm', base / 'destination') + self.assertEqual(caught.exception.returncode, 7) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_inputudev_preload.py b/tools/tests/test_inputudev_preload.py index 0c4020ab8a..0195e6ff1e 100644 --- a/tools/tests/test_inputudev_preload.py +++ b/tools/tests/test_inputudev_preload.py @@ -707,36 +707,15 @@ class InputUdevPreloadTest(unittest.TestCase): def identity(self, pads=None, **extra): return self.run_program("identity", pads=pads, extra=extra) - @classmethod - def id_list(cls, name, text): - path = cls.dir / name - path.write_text(text) - return "@" + str(path) - - def test_a_pad_wine_also_reads_through_sdl_is_described_as_the_pad_sdl_sees(self): - xbox = ["pad PRODUCT=3/45e/28e/110", "parent PRODUCT=3/45e/28e/110"] - for extra in ({}, {"FAKE_EVDEV_UINPUT": "1"}, {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x045e/0x028e"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "0"}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-other.txt", "0x28de/0x1142\n")}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "@" + str(self.dir / "missing.txt")}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": self.id_list("except-ring.txt", "0x045E/0x028E\n")}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x45e/0x28e"}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": ""}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028f"}): - with self.subTest(**extra): - self.assertEqual(self.identity(**extra), xbox) - - def test_a_pad_sdl_skips_keeps_the_steam_input_identity(self): + def test_a_ring_pad_keeps_the_steam_input_identity_whatever_sdl_is_told(self): steam = ["pad PRODUCT=6/28de/11ff/110", "parent PRODUCT=6/28de/11ff/110"] - for extra in ({"FAKE_EVDEV_STEAM_VIRTUAL": "1"}, {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142,0x045E/0x028E"}, + for extra in ({}, {"FAKE_EVDEV_UINPUT": "1"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "0"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "1"}, + {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"}, + {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142,0x045E/0x028E"}, + {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x045e/0x028e"}, {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x28de/0x11ff"}, - {"FAKE_EVDEV_UINPUT": "1", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-ring.txt", "0x28de/0x1142\n0x045e/0x028e\n")}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": self.id_list("except-other.txt", "0x28de/0x11ff\n")}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-long.txt", "0x28de/0x1142\n" * 400 + "0x045e/0x028e\n")}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x45e/0x28e"}, - {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"}): + {"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": ""}, + {"FAKE_EVDEV_UINPUT": "1", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"}): with self.subTest(**extra): self.assertEqual(self.identity(**extra), steam) diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py new file mode 100644 index 0000000000..6862da426f --- /dev/null +++ b/tools/tests/test_native_hook_handoff.py @@ -0,0 +1,2528 @@ +import errno +import fcntl +import json +import os +import select +import shutil +import signal +import socket +import struct +import subprocess +import sys +import tempfile +import termios +import threading +import time +import unittest +from pathlib import Path + +from tools.tests.test_usr2_preload import runner + +CLD_EXITED = 1 + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +# fork() and exec argv[1] with "3", without the hook: prints the exit status it got +EXEC_PROBE = r""" +#include +#include +#include + +int main(int argc, char **argv) { + pid_t pid = fork(); + if (pid == 0) { + execl(argv[1], "target", "3", (char *)NULL); + _exit(127); + } + int status = 0; + if (waitpid(pid, &status, 0) != pid) return 1; + printf("%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; +} +""" + +PARENT = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern char **environ; + +static int gate[2] = {-1, -1}; + +static void open_gate(int sig) { + (void)sig; + if (write(gate[1], "1", 1) != 1) _exit(125); +} + +// nothread: a second thread forks the child; __WNOTHREAD waits see only their own thread's children +static char *nothread_arg; +static int nothread_wrap; +static pthread_mutex_t nothread_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t nothread_cond = PTHREAD_COND_INITIALIZER; +static int nothread_step; +static pid_t nothread_child; + +static void nothread_await(int step) { + pthread_mutex_lock(¬hread_lock); + while (nothread_step < step) pthread_cond_wait(¬hread_cond, ¬hread_lock); + pthread_mutex_unlock(¬hread_lock); +} + +static void nothread_go(int step) { + pthread_mutex_lock(¬hread_lock); + nothread_step = step; + pthread_cond_broadcast(¬hread_cond); + pthread_mutex_unlock(¬hread_lock); +} + +static void *nothread_forker(void *unused) { + (void)unused; + pid_t pid = fork(); + if (pid == 0) { + if (nothread_wrap) execl("/bin/wrap", "wrap", "/bin/target", "target", nothread_arg, (char *)NULL); + execl("/bin/target", "target", nothread_arg, (char *)NULL); + _exit(127); + } + if (pid < 0) _exit(121); + nothread_child = pid; + usleep(1500000); // the program has exited by now + nothread_go(1); + nothread_await(2); + int status = 0; + pid_t r = waitpid(pid, &status, __WNOTHREAD); + printf("own\t%d\n", r == pid); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + return NULL; +} + +// laterecord: a program this thread spawns (not listed: glibc's posix_spawn(), recorded by the +// parent) is recorded only once the hook's test gate opens, by when it is gone and a later child of +// the main thread has its pid, handed off and its forked child reaped +static int late_done[2], late_hold[2], late_gate; + +static void *late_spawner(void *unused) { + (void)unused; + char gate[32]; + snprintf(gate, sizeof(gate), "%d %d", late_gate, (int)syscall(SYS_gettid)); + setenv("DDH_TEST_RECORD_GATE", gate, 1); + pid_t pid = 0; + char *args[] = {"wrap", NULL}; // exits at once: nothing to wrap + int err = posix_spawn(&pid, "/bin/wrap", NULL, NULL, args, environ); + if (write(late_done[1], &err, sizeof(err)) != sizeof(err)) _exit(123); // recorded + char c; + if (read(late_hold[0], &c, 1) != 1) _exit(124); // alive while the main thread's wait looks + return NULL; +} + +// Whether the hook's table (at any number here) has child's entry claimed: its handoff is with the app +static int claimed(pid_t child) { + char path[32], target[64]; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; + for (int slot = 0; slot < 1024; slot++) { + int32_t head[4]; // child, real, parent, state + if (pread(fd, head, sizeof(head), 64 + slot * 64) == (ssize_t)sizeof(head) && head[0] == child && head[3] == 3) + return 1; + } + } + return 0; +} + +// live 1: the late record is made while the later child is still handing its program off (the fake +// spawner holds its reply), so the start time it reads is that child's. live 2: made once the later +// child has recorded itself, before it execs and starts its handoff. +static int late_record(const char *arg, int live) { + int gate[2]; + if (pipe(gate) != 0 || pipe(late_done) != 0 || pipe(late_hold) != 0) return 1; + late_gate = gate[0]; + pthread_t spawner; + pthread_create(&spawner, NULL, late_spawner, NULL); + // the spawned program, reaped: the only child yet + pid_t first = 0; + int status = 0; + for (int i = 0; i < 3000 && (first = waitpid(-1, &status, WNOHANG)) <= 0; i++) usleep(10000); + if (first <= 0) return 1; + // the next fork gets the pid again + FILE *f = fopen("/proc/sys/kernel/ns_last_pid", "w"); + if (!f) return 1; + fprintf(f, "%d", (int)first - 1); + if (fclose(f) != 0) return 1; + int hold[2], at[2]; + if (live == 2 && (pipe(hold) != 0 || pipe(at) != 0)) return 1; + pid_t pid = fork(); + if (pid == 0) { + if (live == 2) { + // back from fork(), whose hook has recorded it: the parent's word to go on comes after the + // late record + char c = 1; + close(hold[1]); + if (write(at[1], &c, 1) != 1 || read(hold[0], &c, 1) != 1) _exit(126); + } + execl("/bin/target", "target", arg, (char *)NULL); + _exit(127); + } + if (pid < 0) return 1; + printf("reused\t%d\n", pid == first); + int err = -1; + if (live == 1) { + int claim = 0; + for (int i = 0; i < 500 && !(claim = claimed(pid)); i++) usleep(10000); + printf("claimed\t%d\n", claim); + if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; + } + if (live == 2) { + char c; + struct pollfd p = {at[0], POLLIN, 0}; + int ready = poll(&p, 1, 10000) == 1 && read(at[0], &c, 1) == 1; + printf("recorded\t%d\n", ready); + if (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err)) return 1; + close(hold[0]); + if (write(hold[1], "1", 1) != 1) return 1; + } + // its forked child exits once the program runs: reaped here, the program's exit left alone + char path[64]; + snprintf(path, sizeof(path), "/proc/%d", (int)pid); + for (int i = 0; i < 1000 && access(path, F_OK) == 0; i++) { + waitpid(-1, &status, WNOHANG); + usleep(10000); + } + printf("reaped\t%d\n", access(path, F_OK) != 0); + if (!live && (write(gate[1], "1", 1) != 1 || read(late_done[0], &err, sizeof(err)) != sizeof(err))) return 1; + printf("spawned\t%d\n", err); + printf("own\t%d\n", (int)waitpid(pid, &status, WNOHANG | __WNOTHREAD) == 0); + kill(pid, SIGKILL); + printf("ended\t%d\n", waitpid(pid, &status, 0) == pid && WIFSIGNALED(status)); + if (write(late_hold[1], "1", 1) != 1) return 1; + pthread_join(spawner, NULL); + return 0; +} + +static void *gone_forker(void *unused) { + (void)unused; + pid_t pid = fork(); + if (pid == 0) { + execl("/bin/target", "target", nothread_arg, (char *)NULL); + _exit(127); + } + if (pid < 0) _exit(121); + nothread_child = pid; + return NULL; // the thread ends: its child goes to the main thread +} + +// nothreadnested: a signal's handler waits, with no __WNOTHREAD, while it interrupts the main +// thread's __WNOTHREAD wait; that wait still takes only the main thread's children afterwards +static void nested_wait(int sig) { + (void)sig; + int status = 0; + int saved = errno; + waitpid(4194303, &status, WNOHANG); // no such child: takes nothing + errno = saved; +} + +// prepclose: another thread's close_range(799, 801) has looked at the kept fds, none of them the +// table's yet, and waits on the hook's test gate while the first fork makes the table at 800 +static int prep_in[2], prep_out[2]; +static long prep_closed = -2; + +static void *prep_closer(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", prep_in[0], prep_out[1], (int)syscall(SYS_gettid)); + setenv("DDNATV_TEST_CLOSE_RANGE_GATE", gate, 1); + prep_closed = syscall(SYS_close_range, 799, 801, 0); + return NULL; +} + +static int prep_hold_ms = 0; // after the table's fd is kept: past the hook's wait for the close +static int prep_kept[2]; // the hook's word that it has kept the table's fd (DDH_TEST_TABLE_KEPT) +static int prep_acked; + +static void *prep_release(void *unused) { + (void)unused; + // once the first fork has made and kept the table's fd, while it waits for the close to end + struct pollfd p = {prep_kept[0], POLLIN, 0}; + char c; + prep_acked = poll(&p, 1, 10000) == 1 && read(prep_kept[0], &c, 1) == 1; + usleep(prep_hold_ms * 1000); + if (write(prep_in[1], "1", 1) != 1) _exit(122); + return NULL; +} + +// How many of the hook's tables are open here, at any numbers +static int tables_open(void) { + char path[32], target[64]; + int count = 0; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n > 0 && (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) == 0)) count++; + } + return count; +} + +static int table_open(void) { return tables_open() > 0; } + +// nowaitpeek: one thread's waitid(WNOWAIT) has seen the exit of a forked child that handed its +// program off (held there by the hook's wait gate) when another wait takes the program's exit and +// frees the entry; that look reports nothing, not the forked child's exit +static int nowait_in[2], nowait_out[2]; + +static void *nowait_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", nowait_in[0], nowait_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_WAIT_GATE", gate, 1); + siginfo_t si; + memset(&si, 0, sizeof(si)); + errno = 0; + int r = waitid(P_ALL, 0, &si, WEXITED | WNOWAIT); + printf("looked\t%d\n", r); + printf("echild\t%d\n", r == -1 && errno == ECHILD); + printf("lookedpid\t%d\n", r == 0 ? (int)si.si_pid : 0); + return NULL; +} + +// twowaits: one thread's wait has found the forked child (held there by the hook's test gate, for +// longer than any other wait would wait for it) when another thread's wait takes the program's exit; +// the child is reported once +static int two_in[2], two_out[2]; + +static void *first_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", two_in[0], two_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_WAIT_GATE", gate, 1); + int status = 0; + pid_t r = waitpid(-1, &status, 0); + printf("first\t%d\n", (int)r); + return NULL; +} + +static void *releaser(void *unused) { + (void)unused; + usleep(1500000); // the other wait is under way by now, and has had more than a second + if (write(two_in[1], "1", 1) != 1) _exit(122); + return NULL; +} + +// reapreuse: one thread's wait has reaped the first child's forked child and is held before it marks +// the entry (the hook's reap gate), while the first child is collected, its slot freed, and a second +// child takes the slot; that wait then reports the second child once, with its program's status +static int reuse_in[2], reuse_out[2]; + +static void *reuse_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", reuse_in[0], reuse_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_REAP_GATE", gate, 1); + int status = 0, reports = 0, last = 0, sig = -1; + pid_t r; + while ((r = waitpid(-1, &status, 0)) > 0) { + reports++; + last = r; + sig = WIFSIGNALED(status) ? WTERMSIG(status) : -1; + } + printf("reports\t%d\n", reports); + printf("last\t%d\n", last); + printf("lastsignal\t%d\n", sig); + return NULL; +} + +// stoppeek: one thread's wait for a child stopped while its handoff is with the app has seen the stop +// (held there by the hook's wait gate) when the child goes on, hands its program off and its forked +// child exits; that wait reports the program's exit, not the forked child's +static int peek_in[2], peek_out[2]; +static pid_t peek_child; + +static void *peek_waiter(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", peek_in[0], peek_out[1], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_WAIT_GATE", gate, 1); + int status = 0; + // the stop is gone by the time it takes the event: this one wait reports the program's end + pid_t r = waitpid(peek_child, &status, WUNTRACED); + printf("waited\t%d\n", r == peek_child); + printf("stopped\t%d\n", r == peek_child && WIFSTOPPED(status)); + printf("code\t%d\n", r == peek_child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return NULL; +} + +// Whether pid is a zombie here, its exit not taken (the kernel's word, no wait of any kind) +static int zombie(pid_t pid) { + char path[64], stat[256]; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + FILE *f = fopen(path, "r"); + if (!f) return 0; + size_t n = fread(stat, 1, sizeof(stat) - 1, f); + fclose(f); + stat[n] = 0; + char *end = strrchr(stat, ')'); + return end && end[1] == ' ' && end[2] == 'Z'; +} + +// A thread's state letter (R, S, Z...), or 0 +static char thread_state(pid_t tid) { + char path[64], stat[256]; + snprintf(path, sizeof(path), "/proc/self/task/%d/stat", (int)tid); + FILE *f = fopen(path, "r"); + if (!f) return 0; + size_t n = fread(stat, 1, sizeof(stat) - 1, f); + fclose(f); + stat[n] = 0; + char *end = strrchr(stat, ')'); + return end && end[1] == ' ' ? end[2] : 0; +} + +// The state of the hook's table entry for child (any table here), or -1 when it has none: a forked +// child of this process when child is 0 (its pid in *found) +static int entry_state_of(pid_t child, pid_t *found) { + char path[32], target[64]; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; + for (int slot = 0; slot < 1024; slot++) { + int32_t head[4]; // child, real, parent, state + if (pread(fd, head, sizeof(head), 64 + slot * 64) != (ssize_t)sizeof(head) || head[3] == 0) continue; + if (child ? head[0] == child : head[2] == getpid()) { + if (found) *found = head[0]; + return head[3]; + } + } + } + return -1; +} + +// Whether the app's report of child's program (status, child: 32 bytes into its entry) is in the table +static int reported(pid_t child) { + char path[32], target[64]; + for (int fd = 3; fd < 4096; fd++) { + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0 || (target[n] = 0, strncmp(target, "/memfd:ddnatv-handoff", 21) != 0)) continue; + for (int slot = 0; slot < 1024; slot++) { + int32_t head[1], report[2]; + if (pread(fd, head, sizeof(head), 64 + slot * 64) == (ssize_t)sizeof(head) && head[0] == child && + pread(fd, report, sizeof(report), 64 + slot * 64 + 32) == (ssize_t)sizeof(report) && report[1] == child) + return 1; + } + } + return 0; +} + +// nohangtwo: a handed-off child A whose program has exited while its forked child is held (the hook's +// test switch), and a child B that is ready: a WNOHANG wait reports B. kind 0: B ordinary, any child; +// 1: B handed off too (its program exited, its forked child free to go); 2: a wait for our group +// (waitpid(0)), with B ordinary and an exited child D in a group of its own, which it must not take. +static int nohang_two(const char *arg, int kind) { + int hold[2]; + if (pipe(hold) != 0) return 1; + char fd[16]; + snprintf(fd, sizeof(fd), "%d", hold[0]); + setenv("DDH_TEST_SHIM_HOLD", fd, 1); + pid_t a = fork(); + if (a == 0) { + execl("/bin/target", "target", arg, (char *)NULL); + _exit(127); + } + if (a < 0) return 1; + unsetenv("DDH_TEST_SHIM_HOLD"); + // exited in the table (2), or handed off (1) with the app's report of its exit in: either is an exit + // the wait's look for exited entries reaches, not a claim (3) still under way + int done = 0; + for (int i = 0; i < 1000 && !done; i++) { + int st = entry_state_of(a, NULL); + done = st == 2 || (st == 1 && reported(a)); + if (!done) usleep(10000); + } + printf("aexited\t%d\n", done); + pid_t d = 0; + if (kind == 2) { + d = fork(); + if (d == 0) { + setpgid(0, 0); + _exit(6); + } + if (d < 0) return 1; + } + pid_t b = fork(); + if (b == 0) { + if (kind == 1) { + execl("/bin/target", "target", "5", (char *)NULL); + _exit(127); + } + _exit(5); + } + if (b < 0) return 1; + int ready = 0; + for (int i = 0; i < 1000 && !ready; i++) { + int st = kind == 1 ? entry_state_of(b, NULL) : 0; + // a handed-off B: its exit in the table and its forked child exited, so nothing holds it back + ready = zombie(b) && (kind != 1 || st == 2 || (st == 1 && reported(b))) && (!d || zombie(d)); + if (!ready) usleep(10000); + } + printf("bwaitable\t%d\n", ready); + char path[32]; + snprintf(path, sizeof(path), "/proc/%d", (int)a); + printf("aheld\t%d\n", access(path, F_OK) == 0 && !zombie(a)); + pid_t which = kind == 2 ? 0 : -1; + int status = 0; + pid_t r = waitpid(which, &status, WNOHANG); + printf("first\t%d\n", r == b); + printf("firstexit\t%d\n", r == b && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + if (write(hold[1], "1", 1) != 1) return 1; + r = waitpid(which, &status, 0); + printf("second\t%d\n", r == a); + printf("exit\t%d\n", r == a && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + if (d) { + r = waitpid(d, &status, WNOHANG); + printf("other\t%d\n", r == d && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + } + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; +} + +// reapbeforerecord: a thread forks a listed child and is held before its fork is recorded (the hook's +// record gate); meanwhile another thread's blocking wait reaps the child's forked child and must go +// on waiting for the program, not drop it when the record is made +static int rbr_gate[2]; +static pid_t rbr_pid; // all three read before the join of their writer: atomic +static pid_t rbr_got = -2; +static int rbr_status; + +static void *rbr_forker(void *arg) { + char gate[32]; + snprintf(gate, sizeof(gate), "%d %d", rbr_gate[0], (int)syscall(SYS_gettid)); + setenv("DDH_TEST_RECORD_GATE", gate, 1); + pid_t pid = fork(); + if (pid == 0) { + execl("/bin/target", "target", (const char *)arg, (char *)NULL); + _exit(127); + } + __atomic_store_n(&rbr_pid, pid, __ATOMIC_RELEASE); + return NULL; +} + +static void *rbr_waiter(void *unused) { + (void)unused; + int status = 0; + pid_t r = waitpid(-1, &status, 0); + rbr_status = status; + __atomic_store_n(&rbr_got, r, __ATOMIC_RELEASE); + return NULL; +} + +static int reap_before_record(const char *arg) { + if (pipe(rbr_gate) != 0) return 1; + pthread_t forker, waiter; + pthread_create(&forker, NULL, rbr_forker, (void *)arg); + pid_t child = 0; + int st = -1; + for (int i = 0; i < 1000 && (st = entry_state_of(0, &child)) != 1; i++) usleep(10000); + int exited = 0; + for (int i = 0; st == 1 && child > 0 && i < 500 && !(exited = zombie(child)); i++) usleep(10000); + int handed = st == 1 && child > 0 && exited; + printf("handed\t%d\n", handed); + if (!handed) { + // no handed-off child to go on with: the forker let go, and nothing signalled + if (write(rbr_gate[1], "1", 1) != 1) return 1; + pthread_join(forker, NULL); + return 0; + } + pthread_create(&waiter, NULL, rbr_waiter, NULL); + char path[32]; + snprintf(path, sizeof(path), "/proc/%d", (int)child); + int reaped = 0; + for (int i = 0; i < 500 && !(reaped = access(path, F_OK) != 0); i++) usleep(10000); + printf("shimreaped\t%d\n", reaped); + printf("unrecorded\t%d\n", __atomic_load_n(&rbr_pid, __ATOMIC_ACQUIRE) == 0); + if (write(rbr_gate[1], "1", 1) != 1) return 1; + pthread_join(forker, NULL); + printf("forked\t%d\n", rbr_pid == child); + usleep(500000); + printf("waiting\t%d\n", __atomic_load_n(&rbr_got, __ATOMIC_ACQUIRE) == -2); + kill(child, SIGTERM); + pthread_join(waiter, NULL); + printf("got\t%d\n", rbr_got == child); + printf("signal\t%d\n", rbr_got == child && WIFSIGNALED(rbr_status) ? WTERMSIG(rbr_status) : -1); + return 0; +} + +// waitidblocked: the child holds before its exec until the parent's waitid(P_PID) has been seen blocked +// (its thread asleep) with no entry claimed yet, so the wait begins before the handoff exists +static siginfo_t wb_info; // read only after the join +static int wb_done = -2; // these two polled meanwhile: atomic +static pid_t wb_tid; +static pid_t wb_child; + +static void *wb_waiter(void *unused) { + (void)unused; + memset(&wb_info, 0, sizeof(wb_info)); + __atomic_store_n(&wb_tid, (pid_t)syscall(SYS_gettid), __ATOMIC_RELEASE); + int r = waitid(P_PID, (id_t)wb_child, &wb_info, WEXITED); + __atomic_store_n(&wb_done, r, __ATOMIC_RELEASE); + return NULL; +} + +static int waitid_blocked(const char *arg) { + int go[2]; + if (pipe(go) != 0) return 1; + wb_child = fork(); + if (wb_child == 0) { + char c; + close(go[1]); + if (read(go[0], &c, 1) != 1) _exit(126); + execl("/bin/target", "target", arg, (char *)NULL); + _exit(127); + } + if (wb_child < 0) return 1; + close(go[0]); + pthread_t waiter; + pthread_create(&waiter, NULL, wb_waiter, NULL); + int asleep = 0; + for (int i = 0; i < 500 && asleep < 10; i++) { + usleep(20000); + pid_t tid = __atomic_load_n(&wb_tid, __ATOMIC_ACQUIRE); + asleep = tid && __atomic_load_n(&wb_done, __ATOMIC_ACQUIRE) == -2 && thread_state(tid) == 'S' ? asleep + 1 : 0; + } + printf("blocked\t%d\n", asleep >= 10); + printf("unclaimed\t%d\n", entry_state_of(wb_child, NULL) < 0); + if (write(go[1], "1", 1) != 1) return 1; + pthread_join(waiter, NULL); + printf("same\t%d\n", wb_done == 0 && wb_info.si_pid == wb_child); + printf("code\t%d\n", wb_info.si_code); + printf("exit\t%d\n", wb_info.si_status); + int status = 0; + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; +} + +static void *bystander(void *unused) { + (void)unused; + int status = 0; + printf("bystander\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); + return NULL; +} + +// nothreadheir: the main thread and the forking one both end; the kernel gives the child to the +// group's first live thread, the heir (created first), and not to the bystander +static void *heir(void *unused) { + (void)unused; + nothread_await(2); + int status = 0; + pid_t r = waitpid(nothread_child, &status, __WNOTHREAD); + printf("own\t%d\n", r == nothread_child); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + return NULL; +} + +static void *late_bystander(void *unused) { + (void)unused; + nothread_await(1); + // both waits only once the main thread has ended (its task a zombie) + char path[64], stat[256]; + snprintf(path, sizeof(path), "/proc/self/task/%d/stat", (int)getpid()); + int ended = 0; + for (int i = 0; i < 500 && !ended; i++) { + FILE *f = fopen(path, "r"); + size_t n = f ? fread(stat, 1, sizeof(stat) - 1, f) : 0; + if (f) fclose(f); + stat[n] = 0; + char *s = strrchr(stat, ')'); + ended = f && s && s[1] == ' ' && (s[2] == 'Z' || s[2] == 'X'); + if (!ended) usleep(10000); + } + printf("mainended\t%d\n", ended); + int status = 0; + printf("bystander\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); + nothread_go(2); + return NULL; +} + +int main(int argc, char **argv) { + setvbuf(stdout, NULL, _IONBF, 0); // what it got to, also when it does not finish + pid_t pid; + if (strcmp(argv[1], "nothreadheir") == 0) { + nothread_arg = argv[2]; + pthread_t first, forker, other; + pthread_create(&first, NULL, heir, NULL); + pthread_create(&forker, NULL, gone_forker, NULL); + pthread_join(forker, NULL); + pthread_create(&other, NULL, late_bystander, NULL); + usleep(1500000); // the program has exited by now + nothread_go(1); + pthread_exit(NULL); // the main thread ends too; the others finish the process + } + if (strcmp(argv[1], "nohangtwo") == 0) return nohang_two(argv[2], 0); + if (strcmp(argv[1], "nohangtwohanded") == 0) return nohang_two(argv[2], 1); + if (strcmp(argv[1], "nohangtwogroup") == 0) return nohang_two(argv[2], 2); + if (strcmp(argv[1], "reapbeforerecord") == 0) return reap_before_record(argv[2]); + if (strcmp(argv[1], "waitidblocked") == 0) return waitid_blocked(argv[2]); + if (strcmp(argv[1], "laterecord") == 0) return late_record(argv[2], 0); + if (strcmp(argv[1], "laterecordlive") == 0) return late_record(argv[2], 1); + if (strcmp(argv[1], "laterecordearly") == 0) return late_record(argv[2], 2); + if (strcmp(argv[1], "nothreadgone") == 0) { + nothread_arg = argv[2]; + pthread_t forker; + pthread_create(&forker, NULL, gone_forker, NULL); + pthread_join(forker, NULL); + usleep(1500000); // the program has exited by now + // another thread than the one the child went to: not its child + pthread_t other; + pthread_create(&other, NULL, bystander, NULL); + pthread_join(other, NULL); + int status = 0; + pid_t r = waitpid(nothread_child, &status, __WNOTHREAD); + printf("own\t%d\n", r == nothread_child); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + return 0; + } + if (strcmp(argv[1], "nothreadnested") == 0) { + // the main thread's own program runs on; the other thread's has exited by the time it waits + pid_t own = fork(); + if (own == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + if (own < 0) return 1; + nothread_arg = argv[2]; + pthread_t forker; + pthread_create(&forker, NULL, nothread_forker, NULL); + nothread_await(1); + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = nested_wait; // no SA_RESTART: the wait ends with EINTR after one more look + sigaction(SIGALRM, &sa, NULL); + alarm(1); + int status = 0; + errno = 0; + pid_t r = waitpid(-1, &status, __WNOTHREAD); + printf("outer\t%d\n", (int)r); + printf("eintr\t%d\n", r == -1 && errno == EINTR); + kill(own, SIGKILL); + printf("ownend\t%d\n", waitpid(own, &status, 0) == own && WIFSIGNALED(status)); + nothread_go(2); + pthread_join(forker, NULL); + return 0; + } + if (strcmp(argv[1], "nothread") == 0 || strcmp(argv[1], "nothreadwrap") == 0) { + nothread_arg = argv[2]; + nothread_wrap = argv[1][8] != 0; + pthread_t forker; + pthread_create(&forker, NULL, nothread_forker, NULL); + nothread_await(1); + int status = 0; + printf("other\t%d\n", (int)waitpid(-1, &status, WNOHANG | __WNOTHREAD)); + printf("otherpid\t%d\n", (int)waitpid(nothread_child, &status, WNOHANG | __WNOTHREAD)); + printf("otherwait3\t%d\n", (int)wait3(&status, WNOHANG | __WNOTHREAD, NULL)); + nothread_go(2); + pthread_join(forker, NULL); + return 0; + } + if (strcmp(argv[1], "prepclose") == 0 || strcmp(argv[1], "prepcloselate") == 0) { + // late: the close goes on past the hook's wait for it, through its second try; a later fork + // makes the table then + int late = argv[1][9] != 0; + prep_hold_ms = late ? 1500 : 0; + if (pipe(prep_in) != 0 || pipe(prep_out) != 0 || pipe(prep_kept) != 0) return 1; + char kept[16]; + snprintf(kept, sizeof(kept), "%d", prep_kept[1]); + setenv("DDH_TEST_TABLE_KEPT", kept, 1); + pthread_t closer, release; + pthread_create(&closer, NULL, prep_closer, NULL); + char c; + if (read(prep_out[0], &c, 1) != 1) return 1; // it has looked + pthread_create(&release, NULL, prep_release, NULL); + pid_t pid = fork(); + if (pid == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (pid < 0) return 1; + pthread_join(release, NULL); + pthread_join(closer, NULL); + printf("ranged\t%ld\n", prep_closed); + int status = 0; + printf("same\t%d\n", waitpid(pid, &status, 0) == pid); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + if (late) { + pid_t again = fork(); + if (again == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (again < 0) return 1; + printf("again\t%d\n", waitpid(again, &status, 0) == again && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + } + printf("acked\t%d\n", prep_acked); + printf("table\t%d\n", table_open()); + return 0; + } + if (strcmp(argv[1], "prepcloseheld") == 0) { + // the close stays under way through three forks, each of whose tries gives the table up: one + // table's fd at most is left for it, tried again, not another made each time + if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; + pthread_t closer; + pthread_create(&closer, NULL, prep_closer, NULL); + char c; + if (read(prep_out[0], &c, 1) != 1) return 1; + int status = 0; + for (int i = 0; i < 3; i++) { + pid_t quick = fork(); + if (quick == 0) _exit(0); + if (quick < 0) return 1; + waitpid(quick, &status, 0); + } + printf("tables\t%d\n", tables_open()); + if (write(prep_in[1], "1", 1) != 1) return 1; + pthread_join(closer, NULL); + // The close has closed the given-up table's 800 by now; a file of the program's own takes the + // number, as another thread's open could, and outlives the next try, which finds no table there. + char target[64]; + printf("freed800\t%d\n", readlink("/proc/self/fd/800", target, sizeof(target)) < 0); + int mine = open("/dev/null", O_RDONLY); + if (mine < 0 || dup2(mine, 800) != 800) return 1; + close(mine); + pid_t again = fork(); // the close is over: the table is made now + if (again == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (again < 0) return 1; + printf("again\t%d\n", waitpid(again, &status, 0) == again && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + printf("table\t%d\n", table_open()); + ssize_t n = readlink("/proc/self/fd/800", target, sizeof(target) - 1); + if (n > 0) target[n] = 0; + printf("mine800\t%d\n", n > 0 && strcmp(target, "/dev/null") == 0); + return 0; + } + if (strcmp(argv[1], "nowaitpeek") == 0) { + if (pipe(nowait_in) != 0 || pipe(nowait_out) != 0) return 1; + pid_t child = fork(); + if (child == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + if (child < 0) return 1; + pthread_t waiter; + pthread_create(&waiter, NULL, nowait_waiter, NULL); + char c; + if (read(nowait_out[0], &c, 1) != 1) return 1; // it has seen the forked child's exit + kill(child, SIGTERM); + int status = 0; + printf("taken\t%d\n", waitpid(child, &status, 0) == child && WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM); + if (write(nowait_in[1], "1111", 4) != 4) return 1; + pthread_join(waiter, NULL); + printf("child\t%d\n", (int)child); + return 0; + } + if (strcmp(argv[1], "forkclose") == 0) { + // another thread's close_range() is under way (held on the test gate) when this forks a child, + // which then makes a table of its own for a child of its own: it waits for no close of its parent's + if (pipe(prep_in) != 0 || pipe(prep_out) != 0) return 1; + pthread_t closer; + pthread_create(&closer, NULL, prep_closer, NULL); + char c; + if (read(prep_out[0], &c, 1) != 1) return 1; + pid_t child = fork(); + if (child == 0) { + pid_t grandchild = fork(); + if (grandchild == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (grandchild < 0) _exit(123); + int status = 0; + if (waitpid(grandchild, &status, 0) != grandchild) _exit(124); + _exit(WIFEXITED(status) ? WEXITSTATUS(status) : 125); + } + if (child < 0) return 1; + int status = 0; + printf("child\t%d\n", waitpid(child, &status, 0) == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + if (write(prep_in[1], "1", 1) != 1) return 1; + pthread_join(closer, NULL); + return 0; + } + if (strcmp(argv[1], "reapreuse") == 0) { + if (pipe(reuse_in) != 0 || pipe(reuse_out) != 0) return 1; + pid_t first = fork(); + if (first == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + if (first < 0) return 1; + pthread_t waiter; + pthread_create(&waiter, NULL, reuse_waiter, NULL); + char c; + if (read(reuse_out[0], &c, 1) != 1) return 1; // it has reaped the first's forked child + kill(first, SIGTERM); + usleep(1000000); // the program's end is reported + int status = 0; + printf("first\t%d\n", waitpid(first, &status, 0) == first && WIFSIGNALED(status)); + pid_t second = fork(); + if (second == 0) { + execl("/bin/target", "target", "sleep", (char *)NULL); + _exit(127); + } + if (second < 0) { + if (write(reuse_in[1], "1111", 4) != 4) return 1; // the waiter let go before the fixture fails + return 1; + } + // handed off, its forked child exited (its exit not taken: the waiter is held) + int exited = 0; + for (int i = 0; i < 500 && !(exited = zombie(second)); i++) usleep(10000); + printf("secondexited\t%d\n", exited); + if (write(reuse_in[1], "1111", 4) != 4) return 1; // for this reap and any after it + usleep(500000); + kill(second, SIGTERM); + pthread_join(waiter, NULL); + printf("second\t%d\n", (int)second); + return 0; + } + if (strcmp(argv[1], "stoppeek") == 0) { + if (pipe(peek_in) != 0 || pipe(peek_out) != 0) return 1; + peek_child = fork(); + if (peek_child == 0) { + execl("/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (peek_child < 0) return 1; + usleep(300000); // its handoff is with the app (the fake spawner holds its reply) + syscall(SYS_tgkill, peek_child, peek_child, SIGSTOP); + pthread_t waiter; + pthread_create(&waiter, NULL, peek_waiter, NULL); + char c; + if (read(peek_out[0], &c, 1) != 1) return 1; // it has seen an event: the gate says which + printf("peeked\t%d\n", c); + if (c != CLD_STOPPED) return 0; // not the stop, so not the ordering this is about: the test fails + syscall(SYS_tgkill, peek_child, peek_child, SIGCONT); + // the reply has come, the program runs, the forked child has exited (its exit still not taken) + int gone = 0; + for (int i = 0; i < 500 && !(gone = zombie(peek_child)); i++) usleep(10000); + printf("shimexited\t%d\n", gone); + if (write(peek_in[1], "11111111", 8) != 8) return 1; // for each look + pthread_join(waiter, NULL); + return 0; + } + // waitidpid: the child holds before its exec until the parent's wait has begun + if (strcmp(argv[1], "waitidpid") == 0 && pipe(gate) != 0) return 1; + if (strcmp(argv[1], "spawn") == 0) { + // as Python's subprocess does since 3.13, with its close_fds as a file action + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_addclosefrom_np(&actions, 3); + char *args[] = {"target", argv[2], NULL}; + int err = posix_spawn(&pid, argc > 3 ? argv[3] : "/bin/target", &actions, NULL, args, environ); + printf("spawned\t%d\n", err); + if (err) return 0; + } else if ((pid = fork()) == 0) { + if (strcmp(argv[1], "closefds") == 0) { + // as Python's subprocess does before exec; an ordinary fd shows that it closed them + int probe = open("/dev/null", O_RDONLY); + printf("closerange\t%ld\n", (long)syscall(SYS_close_range, 3, ~0U, 0)); + printf("closed\t%d\n", probe >= 3 && fcntl(probe, F_GETFD) < 0); + fflush(stdout); + } + if (strcmp(argv[1], "group") == 0) setpgid(0, 0); + if (gate[0] >= 0) { + char c; + close(gate[1]); + if (read(gate[0], &c, 1) != 1) _exit(126); + } + if (strcmp(argv[1], "manyargs") == 0) { + // argv[3] after 32 others, as a long env-wrapped launch has it + char *args[37] = {"target", argv[2]}; + for (int i = 2; i < 34; i++) args[i] = "x"; + args[34] = argv[3]; + args[35] = NULL; + execv("/bin/target", args); + _exit(127); + } + execl(argc > 3 ? argv[3] : "/bin/target", "target", argv[2], (char *)NULL); + _exit(127); + } + if (pid < 0) return 1; + int status = 0; + if (strcmp(argv[1], "waitidpid") == 0) { + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = open_gate; + sa.sa_flags = SA_RESTART; + sigaction(SIGALRM, &sa, NULL); + alarm(1); + siginfo_t si; + memset(&si, 0, sizeof(si)); + int r = waitid(P_PID, pid, &si, WEXITED); + printf("same\t%d\n", r == 0 && si.si_pid == pid); + printf("code\t%d\n", si.si_code); + printf("exit\t%d\n", si.si_status); + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; + } + int all = strcmp(argv[1], "waitidall") == 0 ? __WALL : 0; + if (strcmp(argv[1], "waitid") == 0 || all) { + // at once, before the child has claimed its handoff, and for stops too (and with __WALL) + siginfo_t si; + errno = 0; + printf("pid0\t%d\n", waitid(P_PID, 0, &si, WEXITED) < 0 && errno == EINVAL); + memset(&si, 0, sizeof(si)); + int r = waitid(P_ALL, 0, &si, WEXITED | WSTOPPED | all); + printf("same\t%d\n", r == 0 && si.si_pid == pid); + printf("code\t%d\n", si.si_code); + printf("exit\t%d\n", si.si_status); + printf("uid\t%d\n", (int)si.si_uid); + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; + } + if (strcmp(argv[1], "twowaits") == 0) { + if (pipe(two_in) != 0 || pipe(two_out) != 0) return 1; + pthread_t first, release; + pthread_create(&first, NULL, first_waiter, NULL); + char c; + if (read(two_out[0], &c, 1) != 1) return 1; // the first wait has reaped the forked child + kill(pid, SIGTERM); // the program's: it ends, and its exit is ready + usleep(1000000); + pthread_create(&release, NULL, releaser, NULL); + pid_t r = -1; + for (int i = 0; i < 300 && (r = waitpid(-1, &status, WNOHANG)) == 0; i++) usleep(10000); + printf("second\t%d\n", (int)r); + printf("signal\t%d\n", r == pid && WIFSIGNALED(status) ? WTERMSIG(status) : -1); + pthread_join(release, NULL); + pthread_join(first, NULL); + printf("child\t%d\n", (int)pid); + return 0; + } + if (strcmp(argv[1], "stopclaim") == 0) { + // stopped while its handoff is with the app (the fake spawner holds its reply), then continued: by + // tgkill(), as a group's stop reaches it, where kill() would hold the signal for the program + usleep(300000); + syscall(SYS_tgkill, pid, pid, SIGSTOP); + printf("stopped\t%d\n", waitpid(pid, &status, WUNTRACED) == pid && WIFSTOPPED(status)); + usleep(1500000); // the reply has come meanwhile + syscall(SYS_tgkill, pid, pid, SIGCONT); + } + if (strcmp(argv[1], "badopts") == 0) { + usleep(1500000); // the program has exited by now + // refused (WNOWAIT is waitid()'s) or selecting no forked child (__WCLONE alone): the exit stays + errno = 0; + printf("nowait\t%d\n", (int)wait4(-1, &status, WNOHANG | WNOWAIT, NULL) == -1 && errno == EINVAL); + printf("clone\t%d\n", (int)waitpid(pid, &status, WNOHANG | __WCLONE) != pid); + printf("cloneall\t%d\n", (int)waitpid(-1, &status, WNOHANG | __WCLONE) != pid); + errno = 0; + printf("intmin\t%d\n", (int)waitpid(-2147483647 - 1, &status, WNOHANG) == -1 && errno == ESRCH); + } + if (strcmp(argv[1], "nowait") == 0) { + // no wait until the program has long exited, as Plasma's shell never waits for what it launches + usleep(2000000); + char path[64], line[256] = ""; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + FILE *f = fopen(path, "r"); + if (f) { + if (!fgets(line, sizeof(line), f)) line[0] = 0; + fclose(f); + } + char *s = strrchr(line, ')'); + printf("zombie\t%d\n", s && s[1] == ' ' && s[2] == 'Z'); + } + int group = strcmp(argv[1], "group") == 0; + if (group) { + setpgid(pid, pid); + usleep(300000); + // the child is in a group of its own: not ours + printf("ours\t%d\n", (int)waitpid(0, &status, WNOHANG)); + } + if (strcmp(argv[1], "kill") == 0) { + printf("nohang\t%d\n", (int)waitpid(pid, &status, WNOHANG)); + usleep(300000); + printf("kill\t%d\n", kill(pid, SIGTERM)); + } + pid_t r = waitpid(group ? -pid : pid, &status, 0); + printf("same\t%d\n", r == pid); + if (WIFEXITED(status)) printf("exit\t%d\n", WEXITSTATUS(status)); + if (WIFSIGNALED(status)) printf("signal\t%d\n", WTERMSIG(status)); + printf("again\t%d\n", (int)waitpid(-1, &status, WNOHANG)); + return 0; +} +""" + +TARGET = r""" +#include +#include +#include + +int main(int argc, char **argv) { + if (strcmp(argv[1], "sleep") == 0) for (;;) pause(); + return atoi(argv[1]); +} +""" + +# A worker's program that puts files where the hook keeps its parent's pidfd: it gets the numbers, the +# hook makes no descriptor for it, and its parent stays known +DUPOVER = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static int is(int fd, const char *what) { + char path[64], target[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0) return 0; + target[n] = 0; + return strcmp(target, what) == 0; +} + +static unsigned long fds(void) { // a sum over the open fds, the listing's own left out + DIR *d = opendir("/proc/self/fd"); + unsigned long sum = 0; + struct dirent *e; + while (d && (e = readdir(d))) { + if (e->d_name[0] == '.' || atoi(e->d_name) == dirfd(d)) continue; + sum = sum * 31 + (unsigned long)atoi(e->d_name) + 1; + } + if (d) closedir(d); + return sum; +} + +int main(void) { + printf("pidfd\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); + int file = open("/dev/null", O_WRONLY); + unsigned long before = fds(); + dup2(file, 900); + printf("nonew\t%d\n", fds() == before); + printf("taken\t%d\n", is(900, "/dev/null")); + printf("moved\t%d\n", (int)getppid()); + dup2(file, 901); // the spare too: no pidfd left, /proc answers + printf("again\t%d\n", (int)getppid()); + long closed = syscall(SYS_close_range, 3, ~0U, 0); + printf("closerange\t%ld\n", closed); + printf("fileclosed\t%d\n", fcntl(file, F_GETFD) == -1); + printf("closed\t%d\n", (int)getppid()); + return 0; +} +""" + +# A worker's program with its table at fd 1000 (kept, as 900 and 901 are): a dup2() onto the pidfd +# lets go of 900 while another thread's close_range(899, 2000) is between its parts, held there by the +# hook's test gate. The kept fds above 900 stay open. +PIDFD_PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +int main(void) { + errno = 0; + long r = syscall(SYS_waitid, 3, INT_MAX, NULL, WEXITED | WNOHANG, NULL); + printf("waitid\t%ld %d\n", r, errno); + int pidfd = -1; + errno = 0; + r = syscall(SYS_clone, 0x00001000 | SIGCHLD, NULL, &pidfd, NULL, 0); + if (r == 0) _exit(9); + printf("clone\t%ld %d %d\n", r < 0 ? -1L : 1L, errno, pidfd); + if (r > 0) waitpid((pid_t)r, NULL, 0); + r = syscall(SYS_clone, SIGCHLD, NULL, NULL, NULL, 0); + if (r == 0) _exit(7); + int status = 0; + printf("fork\t%d\n", r > 0 && waitpid((pid_t)r, &status, 0) == r && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; +} +""" + +# A child subreaper, as every session process is (preload/subreaper.c), that never waits for a child +# it did not fork. adopt: a child that exits at once leaves a grandchild, which exits once the child is +# gone; own: its own child, which it waits for only later; vfork: one vfork() made, its program static +# (no hook, so no record of it); handler: as adopt, with a SIGCHLD handler of its own; ignore: SIGCHLD +# ignored, so the kernel reaps. +ORPHANS = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t calls; +static void counted(int sig) { (void)sig; calls++; } + +static void nap(long ms) { + struct timespec t = {ms / 1000, (ms % 1000) * 1000000L}; + while (nanosleep(&t, &t) != 0 && errno == EINTR) {} +} + +static int zombie(pid_t pid) { + char path[64], line[256] = ""; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + FILE *f = fopen(path, "r"); + if (!f) return 0; + if (!fgets(line, sizeof(line), f)) line[0] = 0; + fclose(f); + char *s = strrchr(line, ')'); + return s && s[1] == ' ' && s[2] == 'Z'; +} + +int main(int argc, char **argv) { + const char *mode = argv[1]; + int subreaper = 0; + printf("subreaper\t%d\n", prctl(PR_SET_CHILD_SUBREAPER, 1) == 0 && prctl(PR_GET_CHILD_SUBREAPER, &subreaper) == 0 && subreaper); + fflush(stdout); + if (strcmp(mode, "handler") == 0) { + struct sigaction sa, seen; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = counted; + sa.sa_flags = SA_RESTART; + sigaction(SIGCHLD, &sa, NULL); + sigaction(SIGCHLD, NULL, &seen); + printf("view\t%d\n", seen.sa_handler == counted); + } + if (strcmp(mode, "ignore") == 0) signal(SIGCHLD, SIG_IGN); + if (strcmp(mode, "own") == 0 || strcmp(mode, "vfork") == 0) { + pid_t child = strcmp(mode, "vfork") == 0 ? vfork() : fork(); + if (child == 0) { + if (argc > 2) execl(argv[2], "target", "7", (char *)NULL); + _exit(7); + } + nap(1500); + int status = 0; + pid_t r = waitpid(child, &status, 0); + printf("own\t%d\n", r == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; + } + int pipefd[2]; + if (pipe(pipefd) != 0) return 1; + pid_t middle = fork(); + if (middle == 0) { + pid_t grandchild = fork(); + if (grandchild == 0) { + nap(300); // its parent is gone by then + _exit(5); + } + if (write(pipefd[1], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) _exit(1); + _exit(0); + } + pid_t grandchild = 0; + if (read(pipefd[0], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) return 1; + int status = 0; + printf("middle\t%d\n", waitpid(middle, &status, 0) == middle); + nap(1500); + printf("orphan\t%d\n", zombie(grandchild)); + printf("adopted\t%d\n", waitpid(grandchild, &status, WNOHANG) == grandchild); + if (strcmp(mode, "handler") == 0) printf("calls\t%d\n", calls > 0); + return 0; +} +""" + +DUPRACE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static int in[2], out[2]; +static long closed = -2; + +static int is(int fd, const char *what) { + char path[64], target[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0) return 0; + target[n] = 0; + return strncmp(target, what, strlen(what)) == 0; +} + +static void *closer(void *unused) { + (void)unused; + char gate[48]; + snprintf(gate, sizeof(gate), "%d %d %d", in[0], out[1], (int)syscall(SYS_gettid)); + setenv("DDNATV_TEST_CLOSE_RANGE_GATE", gate, 1); + closed = syscall(SYS_close_range, 899, 2000, 0); + return NULL; +} + +int main(void) { + printf("kept\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]") && is(1000, "/memfd:")); + int file = open("/dev/null", O_WRONLY); + if (dup2(file, 950) != 950) return 1; // an ordinary fd in the range, which it closes + if (pipe(in) != 0 || pipe(out) != 0) return 1; + pthread_t thread; + pthread_create(&thread, NULL, closer, NULL); + char c; + if (read(out[0], &c, 1) != 1) return 1; // between the parts + dup2(file, 900); + if (write(in[1], "111", 3) != 3) return 1; // one for each part + pthread_join(thread, NULL); + printf("ranged\t%ld\n", closed); + printf("ordinary\t%d\n", fcntl(950, F_GETFD) == -1); + printf("spare\t%d\n", is(901, "anon_inode:[pidfd]")); + printf("table\t%d\n", is(1000, "/memfd:")); + printf("parent\t%d\n", (int)getppid()); + return 0; +} +""" + +# A worker's program where one thread gives itself a table of its own (close_range() with +# CLOSE_RANGE_UNSHARE) and takes the parent's pidfd number over with dup2(), then closes it there. +# The first thread's table still holds the pidfd, which its close() leaves open. +SPLIT = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +#ifndef CLOSE_RANGE_UNSHARE +#define CLOSE_RANGE_UNSHARE (1U << 1) +#endif + +static int split_closed, own_closed; + +static int is(int fd, const char *what) { + char path[64], target[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", fd); + ssize_t n = readlink(path, target, sizeof(target) - 1); + if (n <= 0) return 0; + target[n] = 0; + return strcmp(target, what) == 0; +} + +static void *splitter(void *file) { + long r = syscall(SYS_close_range, 950, 950, CLOSE_RANGE_UNSHARE); + split_closed = r == 0 && fcntl(950, F_GETFD) == -1; + dup2(*(int *)file, 900); + close(900); + own_closed = fcntl(900, F_GETFD) == -1; + return NULL; +} + +int main(void) { + printf("kept\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); + int file = open("/dev/null", O_WRONLY); + if (dup2(file, 950) != 950) return 1; + pthread_t thread; + pthread_create(&thread, NULL, splitter, &file); + pthread_join(thread, NULL); + printf("split\t%d\n", split_closed); + printf("own\t%d\n", own_closed); + printf("shared\t%d\n", is(950, "/dev/null")); + close(900); + printf("pidfd\t%d\n", is(900, "anon_inode:[pidfd]") && is(901, "anon_inode:[pidfd]")); + printf("parent\t%d\n", (int)getppid()); + return 0; +} +""" + +# A worker's program that checks its parent through the hook's pidfd (kept at 900) when it has one. +# Built with NOFDS, it first takes every free descriptor, so that /proc cannot be read: the answer can +# then only come from the pidfd, which needs no new one (and /proc's failure counts as alive). +PIDFDPPID = r""" +#include +#include +#include +#include +#include + +int main(void) { + char target[64]; + ssize_t n = readlink("/proc/self/fd/900", target, sizeof(target) - 1); + target[n > 0 ? n : 0] = 0; + printf("pidfd\t%d\n", strcmp(target, "anon_inode:[pidfd]") == 0); + fflush(stdout); +#ifdef NOFDS + struct rlimit lim = {512, 512}; // below the hook's kept fds, which stay open + setrlimit(RLIMIT_NOFILE, &lim); + while (open("/dev/null", O_RDONLY) >= 0) {} + printf("nofds\t%d\n", open("/proc/self/stat", O_RDONLY) < 0); +#endif + printf("parent\t%d\n", (int)getppid()); + return 0; +} +""" + +# A worker's program that says whether it has the hook's pidfd of its parent (kept at 900) and exits +# with 9 at once. Built with NOFDS, it first takes every free descriptor (/proc then cannot be read). +EXIT9 = r""" +#include +#include +#include +#include +#include + +int main(void) { + char target[64]; + ssize_t n = readlink("/proc/self/fd/900", target, sizeof(target) - 1); + target[n > 0 ? n : 0] = 0; + printf("pidfd\t%d\n", strcmp(target, "anon_inode:[pidfd]") == 0); +#ifdef NOFDS + struct rlimit lim = {512, 512}; // below the hook's kept fds, which stay open + setrlimit(RLIMIT_NOFILE, &lim); + while (open("/dev/null", O_RDONLY) >= 0) {} + printf("nofds\t%d\n", open("/proc/self/stat", O_RDONLY) < 0); +#endif + fflush(stdout); + return 9; +} +""" + +# An unlisted program that execs the next one, as env and shell wrappers do +WRAP = r""" +#include + +int main(int argc, char **argv) { + if (argc < 3) return 2; + execv(argv[1], argv + 2); // wrap PATH ARGV0 ARGS... + return 127; +} +""" + + +class FakeSpawner(threading.Thread): + """Stands in for the app's spawn socket: runs the program and reports its exit into the table.""" + + def __init__(self, name, prefix, root, reports=True, delay=0): + super().__init__(daemon=True) + self.delay = delay # seconds before the reply: the forked child waits with its entry claimed + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.bind("\0" + name) + self.sock.listen(4) + self.prefix = prefix + self.root = root + self.reports = reports # False: as an app that died with its worker, no exit report + self.requests = [] + # The programs it ran, as pidfds: ended with the test whatever becomes of them, and never another + # process given a pid of theirs once they have been reaped. A program it could not have one for + # is never run (failures says so); none is started once the ending has begun (closed). + self.pidfds = [] + self.failures = [] + self.closed = False + self.lock = threading.Lock() + + def run(self): + while True: + try: + conn, _ = self.sock.accept() + except OSError: + return + header = self.read(conn, 4) + payload = self.read(conn, struct.unpack(">I", header)[0]) if header else b"" + if not payload: + conn.close() + continue + request = json.loads(payload) + fds = [] + while len(fds) < len(request["fds"]) + 1: + data, chunk, _, _ = socket.recv_fds(conn, 1, request["fdchunks"]) + fds.extend(chunk) + if not data: + break # the client went away between chunks + if len(fds) < len(request["fds"]) + 1: + for fd in fds: + os.close(fd) + conn.close() + continue + self.requests.append(request) + table = fds[request["table"]] + program = str(self.root) + request["file"] + if self.delay: + threading.Event().wait(self.delay) + # As a worker does: a process whose pid goes back first, which runs the program only + # once the hook takes it on with "go" + with self.lock: + pid, pidfd = -1, None + if not self.closed: + gate_r, gate_w = os.pipe() + pid = os.fork() + if pid == 0: + os.close(gate_w) + if os.read(gate_r, 1) == b"1": + argv = list(self.prefix) + [program] + request["argv"][1:] + os.execv(argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0]), argv) + os._exit(127) + os.close(gate_r) + try: + pidfd = os.pidfd_open(pid) + self.pidfds.append(pidfd) + except (AttributeError, OSError) as error: + self.failures.append("no pidfd for a worker: %s" % error) + went = False + try: + if pidfd is not None: + conn.sendall(b"pid %d\n" % pid) + went = not request.get("ack") or self.read(conn, 3) == b"go\n" + if went and request.get("ack"): + conn.sendall(b"ok\n") # the app's last word, before the worker may run it + if went: + os.write(gate_w, b"1") + except OSError: + went = False # the fixture went away mid-handshake + finally: + for fd in fds: + if fd != table: + os.close(fd) + conn.close() + if pid > 0: + os.close(gate_w) # a worker not told to go ends at once + if not went: + if pid > 0: + os.waitpid(pid, 0) + os.close(table) + continue + threading.Thread(target=self.report if self.reports else self.reap, args=(pid, table, request), daemon=True).start() + + @staticmethod + def read(conn, size): + data = b"" + while len(data) < size: + more = conn.recv(size - len(data)) + if not more: + return b"" # the client went away + data += more + return data + + @staticmethod + def reap(pid, table, request): + os.waitpid(pid, 0) + os.close(table) + + @staticmethod + def report(pid, table, request): + code = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]) + status = (-code) & 0x7F if code < 0 else (code & 0xFF) << 8 + # as GuestWorkers.reportExit: one write of the status and the child it is for; the hook + # moves the entry to exited itself + entry = 64 + request["slot"] * 64 + os.pwrite(table, struct.pack(" out 2> err": the controlling terminal on none of its standard fds + result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal="hidden") + self.assertEqual([], requests) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_near_the_limit_a_job_reading_dev_null_is_handed_off(self): + # "cmd &" from a shell without job control: the foreground group, stdin /dev/null + result, requests, out = self.run_parent("wait", "7", handoff="other", pressure=0, as_shell=True, terminal="null") + self.assertEqual(1, len(requests), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_near_the_limit_the_steam_client_is_not(self): + steam = self.root / "bin/steam" + if not steam.exists(): + shutil.copy(self.root / "bin/target", steam) + result, requests, out = self.run_parent("wait", "3", "/bin/steam", handoff="other", pressure=0, as_shell=True) + self.assertEqual([], requests) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_near_the_limit_a_quick_tool_is_not(self): + # sed, grep, sort...: a few milliseconds of work, not an app process of their own + sed = self.root / "bin/sed" + if not sed.exists(): + shutil.copy(self.root / "bin/target", sed) + result, requests, out = self.run_parent("wait", "3", "/bin/sed", handoff="other", pressure=0, as_shell=True) + self.assertEqual([], requests) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_near_the_limit_a_quick_tool_named_only_in_an_argument_is_handed_off(self): + # only the program itself counts: "target ... sed" is not sed + result, requests, out = self.run_parent("manyargs", "7", "sed", handoff="other", pressure=0, as_shell=True) + self.assertEqual(1, len(requests), out.stderr) + + def test_near_the_limit_a_launch_naming_steam_in_any_argument_is_not(self): + # as "env ... /path/Steam/steamrtarm64/steam", with the path after 32 other arguments + result, requests, out = self.run_parent("manyargs", "3", "/root/.local/share/Steam/steamrtarm64/steam", + handoff="other", pressure=0, as_shell=True) + self.assertEqual([], requests) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_a_wait_of_another_thread_with_wnothread_does_not_take_the_program(self): + result, requests, out = self.run_parent("nothread", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("-1", result.get("other"), out.stdout) + self.assertEqual("-1", result.get("otherpid"), out.stdout) + self.assertEqual("-1", result.get("otherwait3"), out.stdout) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_a_table_given_up_again_and_again_costs_one_fd(self): + if self.child_status != "3": + self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc)") + result, requests, out = self.run_parent("prepcloseheld", "5", extra_env={"DDH_TEST_LATE_TABLE": "1"}) + self.assertEqual("1", result.get("tables"), out.stdout + out.stderr) + # the given-up table's number, closed by the close and then the program's own file, stays its + self.assertEqual("1", result.get("freed800"), out.stdout) + self.assertEqual("1", result.get("mine800"), out.stdout) + self.assertEqual("5", result.get("again"), out.stdout) + self.assertEqual("1", result.get("table"), out.stdout) + self.assertEqual(1, len(requests), out.stderr) + + def test_a_waitid_nowait_reports_no_child_whose_entry_went_meanwhile(self): + result, requests, out = self.run_parent("nowaitpeek", "sleep") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("taken"), out.stdout + out.stderr) + self.assertEqual("1", result.get("echild"), out.stdout) + self.assertEqual("0", result.get("lookedpid"), out.stdout) + + def test_a_forked_child_waits_for_no_close_of_its_parents(self): + # no table in the parent (a close held across its tries), so the child makes one + result, requests, out = self.run_parent("forkclose", "3", extra_env={"DDH_TEST_LATE_TABLE": "1"}) + self.assertEqual(1, len(requests), out.stdout + out.stderr) + self.assertEqual("3", result.get("child"), out.stdout) + + def test_a_late_mark_of_a_reused_slot_leaves_the_new_child_once(self): + result, requests, out = self.run_parent("reapreuse", "sleep") + self.assertEqual(2, len(requests), out.stderr) + # the second child took the first's slot, and had handed off before the late mark came + self.assertEqual(requests[0]["slot"], requests[1]["slot"], requests) + self.assertEqual("1", result.get("first"), out.stdout + out.stderr) + self.assertEqual("1", result.get("secondexited"), out.stdout) + self.assertEqual("1", result.get("reports"), out.stdout) + self.assertEqual(result.get("second"), result.get("last"), out.stdout) + self.assertEqual(str(signal.SIGTERM.value), result.get("lastsignal"), out.stdout) + + def test_a_stop_seen_before_the_child_hands_off_reports_its_program(self): + result, requests, out = self.run_parent("stoppeek", "6", delay=1.0) + self.assertEqual(str(os.CLD_STOPPED), result.get("peeked"), out.stdout + out.stderr) # the look saw the stop + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("shimexited"), out.stdout + out.stderr) + # the one wait that saw the stop reports the program's end, not a stop and not the forked child's + self.assertEqual("1", result.get("waited"), out.stdout) + self.assertEqual("0", result.get("stopped"), out.stdout) + self.assertEqual("6", result.get("code"), out.stdout) + + def test_two_waits_report_a_handed_off_child_once(self): + result, requests, out = self.run_parent("twowaits", "sleep") + self.assertEqual(1, len(requests), out.stderr) + child = result.get("child") + self.assertEqual(child, result.get("second"), out.stdout) + self.assertEqual(str(signal.SIGTERM.value), result.get("signal"), out.stdout) + self.assertEqual("-1", result.get("first"), out.stdout) + + def test_a_stop_while_the_handoff_is_claimed_keeps_the_claim(self): + result, requests, out = self.run_parent("stopclaim", "6", delay=1.0) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("stopped"), out.stdout) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("6", result.get("exit"), out.stdout) + + def test_a_wnothread_wait_a_handler_interrupts_keeps_to_its_thread(self): + result, requests, out = self.run_parent("nothreadnested", "7") + self.assertEqual(2, len(requests), out.stderr) + self.assertEqual("1", result.get("eintr"), out.stdout) + self.assertEqual("1", result.get("ownend"), out.stdout) + # the other thread's child is still its own + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_a_wait_with_options_wait4_refuses_or_clone_only_leaves_the_exit(self): + result, requests, out = self.run_parent("badopts", "5") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("nowait"), out.stdout) + self.assertEqual("1", result.get("clone"), out.stdout) + self.assertEqual("1", result.get("cloneall"), out.stdout) + self.assertEqual("1", result.get("intmin"), out.stdout) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("5", result.get("exit"), out.stdout) + + def test_a_posix_spawn_of_a_file_with_only_the_elf_magic_fails_as_it_would(self): + stub = self.root / "bin/stub" + stub.write_bytes(b"\x7fELF") + stub.chmod(0o755) + result, requests, out = self.run_parent("spawn", "6", "/bin/stub", handoff="stub") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual([], requests) + self.assertEqual(str(errno.ENOEXEC), result.get("spawned"), out.stdout) + self.assertNotIn("exit", result, out.stdout) + self.assertNotIn("signal", result, out.stdout) + + def test_wnothread_child_goes_to_the_first_live_thread(self): + # The forking thread and the main one both ended. Which thread the kernel gives the child to + # (qemu-user has a thread of its own first) is what the same program shows without the hook. + result, requests, out = self.run_parent("nothreadheir", "7") + plain, _, plain_out = self.run_parent("nothreadheir", "7", hook=False) + # the waits ran only after the main thread had ended, in both runs + self.assertEqual("1", result.get("mainended"), out.stdout) + self.assertEqual("1", plain.get("mainended"), plain_out.stdout) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual(plain.get("bystander"), result.get("bystander"), (out.stdout, plain_out.stdout)) + self.assertEqual(plain.get("own"), result.get("own"), (out.stdout, plain_out.stdout)) + if result.get("own") == "1": + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_wnothread_takes_a_child_whose_thread_ended(self): + # the kernel gives it to the main thread: another thread's wait does not take it + result, requests, out = self.run_parent("nothreadgone", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("-1", result.get("bystander"), out.stdout) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_a_late_record_of_a_spawned_child_keeps_a_handoffs_owner(self): + self.late_record() + + def test_a_late_record_keeps_an_owner_whose_start_was_not_read(self): + # the fork's child could not read its own start time: its record has none to be told by + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}) + + def test_a_late_record_reading_the_new_childs_start_keeps_its_owner(self): + # made while the later child, which could not read its own start, still hands its program off + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live="live") + + def test_a_late_record_before_the_new_child_execs_keeps_its_owner(self): + # made once the later child, which could not read its own start, has recorded itself and + # before it execs: no handoff of it yet to tell by + self.late_record({"DDH_TEST_FORK_START_UNKNOWN": "1"}, live="early") + + def late_record(self, env=None, live=None): + if self.child_status != "3": + self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so nothing can be spawned") + # the pid has to be given again, which only a pid namespace of the test's own allows + if not os.environ.get("DDH_TEST_PIDNS"): + unshare = shutil.which("unshare") + if not unshare or subprocess.run([unshare, "-Urpf", "--mount-proc", "true"], capture_output=True).returncode: + self.skipTest("no user and pid namespace for this test") + # this module by the name it was loaded as, from the repository's root or this directory + here, top = Path(__file__).resolve().parent, Path(__file__).resolve().parents[2] + path = os.pathsep.join([str(here), str(top)] + ([os.environ["PYTHONPATH"]] if os.environ.get("PYTHONPATH") else [])) + out = subprocess.run([unshare, "-Urpf", "--mount-proc", sys.executable, "-m", "unittest", self.id()], + env={**os.environ, "DDH_TEST_PIDNS": "1", "PYTHONPATH": path}, cwd=top, + capture_output=True, text=True, timeout=300) + self.assertEqual(0, out.returncode, out.stderr) + self.assertNotIn("skipped", out.stderr, out.stderr) + return + result, requests, out = self.run_parent("laterecord" + (live or ""), "sleep", extra_env=env, + delay=1.0 if live == "live" else 0) + self.assertEqual("1", result.get("reused"), out.stdout + out.stderr) + if live == "live": + self.assertEqual("1", result.get("claimed"), out.stdout) + if live == "early": + self.assertEqual("1", result.get("recorded"), out.stdout) + self.assertEqual("0", result.get("spawned"), out.stdout) + self.assertEqual("1", result.get("reaped"), out.stdout) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("1", result.get("ended"), out.stdout) + + def test_wnothread_takes_a_program_started_through_a_wrapper(self): + if self.child_status != "3": + self.skipTest("a child here cannot exec an aarch64 program (no binfmt_misc), so the wrapper cannot run") + # the hook names its own path inside the guest's root for the programs it execs + rooted = self.root / str(self.hook).lstrip("/") + rooted.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(self.hook, rooted) + result, requests, out = self.run_parent("nothreadwrap", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("-1", result.get("other"), out.stdout) + self.assertEqual("-1", result.get("otherpid"), out.stdout) + self.assertEqual("1", result.get("own"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_waitid_for_a_pid_begun_before_its_claim_reports_the_program(self): + result, requests, out = self.run_parent("waitidpid", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual(str(CLD_EXITED), result.get("code"), out.stdout) + self.assertEqual("7", result.get("exit"), out.stdout) + self.assertEqual("-1", result.get("again"), out.stdout) + + def test_near_the_limit_a_terminals_foreground_job_is_not(self): + result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0, as_shell=True, terminal=True) + self.assertEqual([], requests) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def ppid_in_worker(self, parent): + # as a worker's own program: DDH_WORKER_PID is its pid, DDH_TABLE names the process that forked it + tmp = Path(self.tmp.name) + probe = tmp / "ppid" + if not probe.exists(): + (tmp / "ppid.c").write_text('#include \n#include \nint main(void) { printf("%d", (int)getppid()); return 0; }\n') + subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "ppid.c")], check=True) + env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root)} + if parent is not None: + env["DDH_TABLE"] = "3:0:%d:0" % parent + settings = " ".join("-E %s=%s" % item for item in env.items()) if self.prefix else \ + " ".join("%s=%s" % item for item in env.items()) + worker = "-E DDH_WORKER_PID=$$" if self.prefix else "DDH_WORKER_PID=$$" + runner = " ".join(self.prefix) + " " + settings + " " + worker if self.prefix else "env " + settings + " " + worker + out = subprocess.run(["sh", "-c", "exec %s %s" % (runner, probe)], capture_output=True, text=True, timeout=60) + return out.stdout.strip() + + def test_a_handed_off_programs_parent_is_the_process_that_forked_it(self): + forker = subprocess.Popen(["sleep", "60"]) + self.addCleanup(forker.wait) + self.addCleanup(forker.kill) + self.assertEqual(str(forker.pid), self.ppid_in_worker(forker.pid)) + + def test_a_handed_off_program_whose_forking_process_is_gone_has_init_as_parent(self): + self.assertEqual("1", self.ppid_in_worker(4194303)) + + def test_a_handed_off_program_whose_forking_process_exited_unreaped_has_init_as_parent(self): + forker = subprocess.Popen(["true"]) + self.addCleanup(forker.wait) + stat = Path("/proc/%d/stat" % forker.pid) + pause = threading.Event() + for _ in range(100): + if stat.read_text().rsplit(")", 1)[1].split()[0] == "Z": + break + pause.wait(0.05) + # exited and not reaped (Popen reaps only in wait() or poll()) + self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) + self.assertEqual("1", self.ppid_in_worker(forker.pid)) + self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) + + def test_through_its_pidfd_a_handed_off_programs_live_parent_is_its_parent(self): + parent, result, out = self.run_worker_program("pidfdlive", PIDFDPPID) + self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr) + self.assertEqual(str(parent), result.get("parent"), out.stdout) + + def test_through_its_pidfd_a_handed_off_programs_unreaped_parent_is_gone(self): + forker = subprocess.Popen(["true"]) + self.addCleanup(forker.wait) + stat = Path("/proc/%d/stat" % forker.pid) + pause = threading.Event() + for _ in range(100): + if stat.read_text().rsplit(")", 1)[1].split()[0] == "Z": + break + pause.wait(0.05) + self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) + # a pidfd opens for an exited parent that is not reaped, and reads as exited; /proc cannot be + # read meanwhile (no free fd), where a failure counts as alive: only the pidfd gives init + _, result, out = self.run_worker_program("pidfdzombie", "#define NOFDS 1\n" + PIDFDPPID, parent=forker.pid) + self.assertEqual("1", result.get("pidfd"), out.stdout + out.stderr) + self.assertEqual("1", result.get("nofds"), out.stdout) + self.assertEqual("1", result.get("parent"), out.stdout) + self.assertEqual("Z", stat.read_text().rsplit(")", 1)[1].split()[0]) + + def test_without_a_pidfd_a_handed_off_programs_gone_parent_is_init(self): + # no process has the pid, so no pidfd: /proc answers + _, result, out = self.run_worker_program("pidfdgone", PIDFDPPID, parent=4194303) + self.assertEqual("0", result.get("pidfd"), out.stdout + out.stderr) + self.assertEqual("1", result.get("parent"), out.stdout) + + def test_wnohang_reports_a_ready_child_while_a_handoffs_forked_child_runs(self): + result, requests, out = self.run_parent("nohangtwo", "3") + self.assertEqual(1, len(requests), out.stderr) + # the state this is about: the program's exit in the table, its forked child alive, the other ready + self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) + self.assertEqual("1", result.get("bwaitable"), out.stdout) + self.assertEqual("1", result.get("aheld"), out.stdout) + self.assertEqual("1", result.get("first"), out.stdout) + self.assertEqual("5", result.get("firstexit"), out.stdout) + self.assertEqual("1", result.get("second"), out.stdout) + self.assertEqual("3", result.get("exit"), out.stdout) + self.assertEqual("-1", result.get("again"), out.stdout) + + def test_wnohang_reports_a_ready_handoff_while_another_ones_forked_child_runs(self): + result, requests, out = self.run_parent("nohangtwohanded", "3") + self.assertEqual(2, len(requests), out.stderr) + self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) + self.assertEqual("1", result.get("bwaitable"), out.stdout) + self.assertEqual("1", result.get("aheld"), out.stdout) + self.assertEqual("1", result.get("first"), out.stdout) + self.assertEqual("5", result.get("firstexit"), out.stdout) + self.assertEqual("1", result.get("second"), out.stdout) + self.assertEqual("3", result.get("exit"), out.stdout) + self.assertEqual("-1", result.get("again"), out.stdout) + + def test_wnohang_for_the_group_reports_its_ready_child_while_a_forked_child_runs(self): + result, requests, out = self.run_parent("nohangtwogroup", "3") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("1", result.get("aexited"), out.stdout + out.stderr) + self.assertEqual("1", result.get("bwaitable"), out.stdout) + self.assertEqual("1", result.get("aheld"), out.stdout) + # the group's ready child, not the exited one of another group + self.assertEqual("1", result.get("first"), out.stdout) + self.assertEqual("5", result.get("firstexit"), out.stdout) + self.assertEqual("1", result.get("second"), out.stdout) + self.assertEqual("3", result.get("exit"), out.stdout) + self.assertEqual("6", result.get("other"), out.stdout) + self.assertEqual("-1", result.get("again"), out.stdout) + + def start_worker_exit(self, name, parent, state, nofds=False, child_start=1 << 62): + # A worker's program that exits with 9 at once, its entry (slot 0) given parent and state, as + # the parent's check of a gone worker leaves it while it holds it (TAKEN). With nofds it first + # takes every free descriptor, so that /proc cannot be read when it exits. A child_start before + # the parent's start leaves it without the parent's pidfd. Returns the run and the table. + tmp = Path(self.tmp.name) + probe = tmp / name + (tmp / (name + ".c")).write_text(("#define NOFDS 1\n" if nofds else "") + EXIT9) + subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / (name + ".c"))], check=True) + table = os.memfd_create("ddh-test-table", 0) + self.addCleanup(os.close, table) + os.ftruncate(table, 64 + 1024 * 64) + os.pwrite(table, struct.pack(" +#include +#include + +int execve(const char *path, char *const argv[], char *const envp[]) { + (void)path; (void)argv; + for (int i = 0; envp[i]; i++) { + if (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0) + printf("env\t%d\t%s\n", i, envp[i]); + } + printf("exec\n"); + fflush(stdout); + _exit(0); +} +""" + +PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + if (argc > 1 && strcmp(argv[1], "exec") == 0) { + char *envp[] = {"PATH=/bin", argc > 2 ? argv[2] : NULL, NULL}; + const char *program = argc > 3 ? argv[3] : "/bin/true"; + char *args[] = {(char *)program, NULL}; + execve(program, args, envp); + return 1; + } + printf("ids\t%u\t%u\t%u\t%u\n", getuid(), geteuid(), getgid(), getegid()); + printf("syscall\t%ld\n", syscall(SYS_getuid)); + struct passwd *pw = getpwuid(getuid()); + printf("user\t%s\t%s\n", pw ? pw->pw_name : "-", pw ? pw->pw_dir : "-"); + struct passwd *root = getpwnam("root"); + printf("root\t%u\n", root ? root->pw_uid : 999); + struct group *gr = getgrgid(getgid()); + printf("group\t%s\n", gr ? gr->gr_name : "-"); + struct stat st; + stat("/bin/true", &st); + printf("owner\t%d\n", st.st_uid == getuid()); + errno = 0; + int to_root = setuid(0); + printf("setuid0\t%d\t%d\n", to_root, errno); + printf("setuid_own\t%d\n", setuid(getuid())); + int sv[2]; + socketpair(AF_UNIX, SOCK_STREAM, 0, sv); + pid_t child = fork(); + if (child == 0) { pause(); _exit(0); } + struct ucred cred; + socklen_t len = sizeof(cred); + getsockopt(sv[0], SOL_SOCKET, SO_PEERCRED, &cred, &len); + printf("peer\t%d\n", cred.uid == getuid()); + kill(child, 9); + waitpid(child, NULL, 0); + return 0; +} +""" + + +class NativeHookUserModeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + (cls.root / "bin").mkdir(parents=True) + (cls.root / "etc").mkdir() + (cls.root / "etc/passwd").write_text(f"root:x:{os.getuid()}:{os.getgid()}:root:/root:/bin/bash\nroot:x:0:0:root:/root:/bin/bash\n") + (cls.root / "bin/true").write_text("") + (cls.root / "bin/true").chmod(0o755) + (cls.root / "bin/script").write_text("#!/bin/true\n") + (cls.root / "bin/script").chmod(0o755) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_probe(self, *args, user=None): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + if user: + hook_env["DDNATV_USER"] = user + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_USER")} + if user: + # A peer's user is the first entry of /proc/PID/environ, which under qemu is qemu's own + env = {"DDNATV_USER": user, **env} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), *args], env=env, capture_output=True, text=True, timeout=120) + result = {} + for line in out.stdout.splitlines(): + key, *values = line.split("\t") + result.setdefault(key, []).append(values) + self.assertTrue(result, out.stdout + out.stderr) + return result + + def test_programs_are_root_by_default(self): + r = self.run_probe() + self.assertEqual([["0", "0", "0", "0"]], r["ids"]) + self.assertEqual([["0"]], r["syscall"]) + self.assertEqual("root", r["user"][0][0]) + self.assertEqual([["1"]], r["owner"]) + self.assertEqual([["0", "0"]], r["setuid0"]) + self.assertEqual([["1"]], r["peer"]) + + def test_the_app_user_sees_its_real_ids_and_cannot_become_root(self): + uid, gid = os.getuid(), os.getgid() + if uid == 0: + self.skipTest("the app's user is root's uid on this runner, so root's ids are its own") + r = self.run_probe(user="app") + self.assertEqual([[str(uid), str(uid), str(gid), str(gid)]], r["ids"]) + self.assertEqual([[str(uid)]], r["syscall"]) + self.assertEqual([["deck", "/root"]], r["user"]) + self.assertEqual([["deck"]], r["group"]) + self.assertEqual([["0"]], r["root"]) + self.assertEqual([["1"]], r["owner"]) + self.assertEqual([["-1", "1"]], r["setuid0"]) + self.assertEqual([["0"]], r["setuid_own"]) + self.assertEqual([["1"]], r["peer"]) + + def test_programs_an_app_user_starts_stay_that_user_whatever_their_environment(self): + r = self.run_probe("exec", "DDNATV_USER=root", user="app") + self.assertEqual([["0", "DDNATV_USER=app"]], r["env"]) + + def test_become_switches_the_started_program_once(self): + self.assertNotIn("env", self.run_probe("exec", "DDNATV_BECOME=root", user="app")) + self.assertEqual([["0", "DDNATV_USER=app"]], self.run_probe("exec", "DDNATV_BECOME=app")["env"]) + + def test_become_reaches_a_scripts_interpreter(self): + self.assertNotIn("env", self.run_probe("exec", "DDNATV_BECOME=root", "/bin/script", user="app")) + self.assertEqual([["0", "DDNATV_USER=app"]], self.run_probe("exec", "DDNATV_BECOME=app", "/bin/script")["env"]) + + def test_root_never_passes_an_app_user_on(self): + self.assertNotIn("env", self.run_probe("exec", "DDNATV_USER=app")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_output_refresh.py b/tools/tests/test_output_refresh.py index e931c4b187..0cb109c0e4 100644 --- a/tools/tests/test_output_refresh.py +++ b/tools/tests/test_output_refresh.py @@ -128,7 +128,9 @@ int main(void) { while (write(g_input_pipe[1], &wake, sizeof(wake)) == sizeof(wake)) n++; assert(n > 0 && errno == EAGAIN); droiddeck_wayland_set_output_refresh_rate(120000); - drain(); expect(4, 120000, 1); + droiddeck_dispatch_pending_input(); + assert(queued() == 0); + expect(4, 120000, 1); droiddeck_wayland_set_output_refresh_rate(0); drain(); expect(5, 60000, 1); droiddeck_wayland_set_output_refresh_rate(-1); @@ -162,7 +164,8 @@ class OutputRefreshTest(unittest.TestCase): self.skipTest('A host C compiler is required') source = SOURCE.read_text() functions = ('nominal_refresh_ns', 'output_send_mode', 'output_notify_mode', - 'output_resized', 'on_input_readable', 'droiddeck_wayland_output_resized', + 'output_resized', 'dispatch_input', 'on_input_readable', + 'droiddeck_dispatch_pending_input', 'droiddeck_wayland_output_resized', 'droiddeck_wayland_set_scale_mode', 'droiddeck_wayland_set_output_refresh_rate') harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS diff --git a/tools/tests/test_picture_position_mapping.py b/tools/tests/test_picture_position_mapping.py index 2c9eb8e32b..f6e7673840 100644 --- a/tools/tests/test_picture_position_mapping.py +++ b/tools/tests/test_picture_position_mapping.py @@ -50,6 +50,20 @@ static void check(int sw, int sh, int ow, int oh, int alignment) { assert(!vkp_game_picture_rect(rect)); near(g_map.off_y, (int)((oh - sh * g_map.ky) * 0.5)); } +static void check_zoomed_portrait(int alignment) { + g_extent.width = 1080; g_extent.height = 1920; + g_mode = VKP_MODE_FIT; g_align = alignment; g_zoom = 1.5f; + update_map(1280, 720); + float rect[4]; + assert(vkp_game_picture_rect(rect)); + double height = 720 * g_map.ky; + assert(height < 1920); + near(rect[1], alignment == VKP_ALIGN_PICTURE_TOP ? 0 : 1920 - height); + double sx, sy; + assert(vkp_output_to_scene(540, rect[1] + height / 2, &sx, &sy)); + near(sx, 640); near(sy, 360); + g_zoom = 1.0f; +} int main(void) { for (int alignment = VKP_ALIGN_PICTURE_TOP; alignment <= VKP_ALIGN_PICTURE_BOTTOM; alignment++) { check(1240, 1100, 2480, 2200, alignment); @@ -57,7 +71,11 @@ int main(void) { check(1024, 768, 2480, 2200, alignment); check(1920, 1080, 2400, 1080, alignment); check(1240, 1100, 2480, 1394, alignment); + check(1280, 720, 1080, 1920, alignment); + check(1280, 800, 1080, 1920, alignment); + check_zoomed_portrait(alignment); } + g_extent.width = 2480; g_extent.height = 1394; g_align = VKP_ALIGN_TOP; update_map(1280, 720); assert(g_map.rh == 697 && g_map.ry == 0); puts("PASS"); diff --git a/tools/tests/test_prepare_windows_runtime.py b/tools/tests/test_prepare_windows_runtime.py index 56e8d59306..6ee26692de 100644 --- a/tools/tests/test_prepare_windows_runtime.py +++ b/tools/tests/test_prepare_windows_runtime.py @@ -1,4 +1,6 @@ +import hashlib import importlib.util +import json from pathlib import Path import struct import tempfile @@ -78,6 +80,7 @@ class WindowsRuntimePreparationTest(unittest.TestCase): mock.patch.object(prepare, 'read_gamescope', return_value=({}, { 'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \ mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \ + mock.patch.object(prepare, 'prepare_ime', return_value=({}, {})), \ mock.patch.object(prepare, 'git', return_value=b''), \ mock.patch.object(prepare.runtime, 'record'), mock.patch.object(prepare.runtime, 'verify'), \ mock.patch.object(prepare.vr_build, 'build', return_value=({vr_name: b'new library'}, vr_manifest)) as build: @@ -109,7 +112,14 @@ class WindowsRuntimePreparationTest(unittest.TestCase): archive.assert_not_called() def test_current_helpers_are_allowed_only_when_restaged_from_source(self): - helpers = prepare.LOCAL_SESSION_HELPERS + helpers = { + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-session', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input', + } + self.assertEqual(prepare.LOCAL_SESSION_HELPERS, helpers) sources = {prepare.ROOT / path: 'assets/linuxfs/' + path.split('/overlay/')[1] for path in helpers} for local_changes in (set(), helpers): @@ -138,7 +148,7 @@ class WindowsRuntimePreparationTest(unittest.TestCase): def test_other_helper_changes_still_need_an_audit(self): with mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()), \ mock.patch.object(prepare, 'changed', return_value={ - 'tools/linuxfs/overlay/usr/local/bin/droiddeck-session'}): + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-unreviewed'}): with self.assertRaisesRegex(ValueError, 'Sources changed since'): prepare.check_sources() @@ -175,5 +185,337 @@ class WindowsRuntimePreparationTest(unittest.TestCase): prepare.check_sources() + def test_ime_sources_are_regenerated_from_pinned_rpms_in_every_stage(self): + ime = {'tools/ime/prepare.py', 'tools/ime/packages.json', 'tools/ime/smoke.py'} + with mock.patch.object(prepare, 'changed', side_effect=[ime, ime, ime]), \ + mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(), b'']): + classifications = prepare.check_sources() + self.assertEqual(set(classifications), ime) + for action in classifications.values(): + self.assertIn('regenerated from checksum-pinned RPMs', action) + self.assertIn('never reused from donor', action) + + def test_unknown_ime_and_native_sources_still_fail_the_audit(self): + for path in ('tools/ime/unreviewed.py', 'app/src/main/cpp/unreviewed.cpp'): + with self.subTest(path=path), \ + mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()), \ + mock.patch.object(prepare, 'changed', return_value={path}): + with self.assertRaisesRegex(ValueError, 'Sources changed since'): + prepare.check_sources() + with mock.patch.object(prepare, 'changed', side_effect=[set(), set(), set()]), \ + mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(), + b'tools/ime/unreviewed.py\0']): + with self.assertRaisesRegex(ValueError, 'Unreviewed runtime'): + prepare.check_sources() + + def test_ime_payload_is_staged_before_record_and_overrides_donor_files(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + apk = root / 'donor.apk' + files = {prepare.IME_MANIFEST: b'generated manifest', + 'usr/local/share/droiddeck/pinyin.so': b'generated ime'} + with ZipFile(apk, 'w') as package: + package.writestr('assets/linuxfs/' + prepare.IME_MANIFEST, b'donor manifest') + package.writestr('assets/linuxfs/usr/local/share/droiddeck/pinyin.so', b'donor ime') + (root / 'app/build').mkdir(parents=True) + (root / 'app/build/runtime-inputs.json').write_text('{}') + staged = {} + + def record(): + for name in files: + staged[name] = (root / 'app/src/main/assets/linuxfs' / name).read_bytes() + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare, 'check_sources', return_value={}), \ + mock.patch.object(prepare, 'DONOR_SHA256', prepare.runtime.digest(apk)), \ + mock.patch.object(prepare, 'REBUILT', {}), \ + mock.patch.object(prepare, 'JNI', ()), mock.patch.object(prepare, 'PREPARED', ()), \ + mock.patch.object(prepare, 'LOCAL_BUILD_PLUMBING', set()), \ + mock.patch.object(prepare, 'source_assets', return_value={}), \ + mock.patch.object(prepare, 'read_gamescope', return_value=({}, { + 'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \ + mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \ + mock.patch.object(prepare, 'prepare_ime', + return_value=(files, {'version': 1, 'files': {}})), \ + mock.patch.object(prepare, 'git', return_value=b''), \ + mock.patch.object(prepare.runtime, 'record', side_effect=record), \ + mock.patch.object(prepare.runtime, 'verify'), \ + mock.patch.object(prepare.vr_build, 'build', return_value=({}, {})): + prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip') + self.assertEqual(staged, files) + output = json.loads((root / 'app/build/windows-runtime-provenance.json').read_text()) + self.assertEqual(output['ime_build'], {'version': 1, 'files': {}}) + self.assertIn('regenerated from checksum-pinned RPMs', + output['outputs']['app/src/main/assets/linuxfs/' + prepare.IME_MANIFEST]['origin']) + + def test_second_preparation_accepts_existing_generated_ime_files(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + apk = root / 'donor.apk' + with ZipFile(apk, 'w') as package: + package.writestr('assets/linuxfs/unchanged.so', b'unchanged component') + (root / 'app/build').mkdir(parents=True) + (root / 'app/build/runtime-inputs.json').write_text('{}') + files = {prepare.IME_MANIFEST: b'generated manifest'} + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare, 'check_sources', return_value={}), \ + mock.patch.object(prepare, 'DONOR_SHA256', prepare.runtime.digest(apk)), \ + mock.patch.object(prepare, 'REBUILT', {}), \ + mock.patch.object(prepare, 'JNI', ()), mock.patch.object(prepare, 'PREPARED', ()), \ + mock.patch.object(prepare, 'LOCAL_BUILD_PLUMBING', set()), \ + mock.patch.object(prepare, 'source_assets', return_value={}), \ + mock.patch.object(prepare, 'read_gamescope', return_value=({}, { + 'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \ + mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \ + mock.patch.object(prepare, 'prepare_ime', + return_value=(files, {'version': 1, 'files': {}})) as prepare_ime, \ + mock.patch.object(prepare, 'git', return_value=b''), \ + mock.patch.object(prepare.runtime, 'record'), \ + mock.patch.object(prepare.runtime, 'verify'), \ + mock.patch.object(prepare.vr_build, 'build', return_value=({}, {})) as build_vr, \ + mock.patch.object(prepare.vr_build, 'validate', return_value=({}, {})) as validate_vr: + prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip') + prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip', rebuilt_vr=root / 'cached-vr') + build_vr.assert_called_once() + validate_vr.assert_called_once() + self.assertEqual(prepare_ime.call_args_list, [ + mock.call(prepare.vr_build.IMAGE), + mock.call(prepare.vr_build.IMAGE), + ]) + self.assertEqual((root / 'app/src/main/assets/linuxfs' / prepare.IME_MANIFEST).read_bytes(), + b'generated manifest') + + def test_windows_ime_preparation_uses_docker_without_local_extractors(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools/ime').mkdir(parents=True) + (root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8') + (root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8') + manifest = {'version': 1, 'files': { + 'usr/local/share/droiddeck/pinyin.so': { + 'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}} + commands = [] + + def run(command, check=True, capture_output=True, text=True): + commands.append(command) + if command[1:3] == ['image', 'inspect']: + return mock.Mock(returncode=0, stdout='sha256:image-id linux/amd64\n', stderr='') + mounted = next(part for part in command if part.endswith(':/out')) + output = Path(mounted.removesuffix(':/out')) + target = output / 'usr/local/share/droiddeck/pinyin.so' + target.parent.mkdir(parents=True) + target.write_bytes(b'ime') + (output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8') + return mock.Mock(returncode=0, stdout='', stderr='') + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker') as locate, \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + files, provenance = prepare.prepare_ime('compiler-image') + inspect_command, command = commands + self.assertEqual(inspect_command, ['docker', 'image', 'inspect', '--format', + '{{.Id}} {{.Os}}/{{.Architecture}}', 'compiler-image']) + self.assertEqual(command[0], 'docker') + self.assertIn('--rm', command) + self.assertIn('--platform', command) + self.assertIn('linux/amd64', command) + self.assertIn('sha256:image-id', command) + self.assertNotIn('sha256:image-id linux/amd64', command) + self.assertNotIn('compiler-image', command) + shell = command[-1] + self.assertNotIn('apt-get', shell) + self.assertIn('command -v "$tool"', shell) + self.assertIn('rpm2cpio cpio', shell) + self.assertIn('rebuild compiler image using tools/local-cross.Dockerfile', shell) + self.assertIn('exec python3 /src/tools/ime/prepare.py', shell) + self.assertIn('--packages /cache', shell) + self.assertIn('--download', shell) + self.assertIn('--output /out', shell) + locate.assert_called_once_with('docker') + self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime') + self.assertEqual(json.loads(files[prepare.IME_MANIFEST]), manifest) + self.assertEqual(provenance, manifest) + + def test_windows_ime_preparation_reuses_existing_default_image_without_building(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools/ime').mkdir(parents=True) + (root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8') + (root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8') + manifest = {'version': 1, 'files': { + 'usr/local/share/droiddeck/pinyin.so': { + 'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}} + commands = [] + + def run(command, check=True, capture_output=True, text=True, input=None): + commands.append(command) + if command[1:3] == ['image', 'inspect']: + return mock.Mock(returncode=0, stdout='sha256:existing-v5 linux/amd64\n', stderr='') + mounted = next(part for part in command if part.endswith(':/out')) + output = Path(mounted.removesuffix(':/out')) + target = output / 'usr/local/share/droiddeck/pinyin.so' + target.parent.mkdir(parents=True) + target.write_bytes(b'ime') + (output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8') + return mock.Mock(returncode=0, stdout='', stderr='') + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + files, provenance = prepare.prepare_ime(prepare.vr_build.IMAGE) + self.assertEqual(prepare.vr_build.IMAGE, 'droiddeck-local-cross:24.04-v5') + self.assertEqual([cmd[1] for cmd in commands], ['image', 'run']) + self.assertEqual(commands[0], ['docker', 'image', 'inspect', '--format', + '{{.Id}} {{.Os}}/{{.Architecture}}', 'droiddeck-local-cross:24.04-v5']) + self.assertIn('sha256:existing-v5', commands[1]) + self.assertNotIn('sha256:existing-v5 linux/amd64', commands[1]) + self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime') + self.assertEqual(provenance, manifest) + + def test_windows_ime_preparation_builds_missing_or_incompatible_default_image_and_runs_by_id(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools/ime').mkdir(parents=True) + (root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8') + (root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8') + (root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\r\nRUN echo ok\r\n') + manifest = {'version': 1, 'files': { + 'usr/local/share/droiddeck/pinyin.so': { + 'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}} + for label, first_inspect in ( + ('missing', mock.Mock(returncode=1, stdout='', stderr='No such image')), + ('linux/arm64', mock.Mock(returncode=0, stdout='sha256:arm64-id linux/arm64\n', stderr='')), + ('windows/amd64', mock.Mock(returncode=0, stdout='sha256:win-id windows/amd64\n', stderr='')), + ): + with self.subTest(case=label): + calls = [] + inspected = 0 + + def run(command, check=True, capture_output=False, text=False, input=None): + nonlocal inspected + calls.append((command, input)) + if command[1:3] == ['image', 'inspect']: + inspected += 1 + if inspected == 1: + return first_inspect + return mock.Mock(returncode=0, stdout='sha256:built-v5-id linux/amd64\n', stderr='') + if command[1] == 'build': + return mock.Mock(returncode=0) + mounted = next(part for part in command if part.endswith(':/out')) + output = Path(mounted.removesuffix(':/out')) + target = output / 'usr/local/share/droiddeck/pinyin.so' + target.parent.mkdir(parents=True) + target.write_bytes(b'ime') + (output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8') + return mock.Mock(returncode=0) + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + files, provenance = prepare.prepare_ime(prepare.vr_build.IMAGE) + self.assertEqual([cmd[1] for cmd, _ in calls], ['image', 'build', 'image', 'run']) + self.assertEqual(calls[0][0], ['docker', 'image', 'inspect', '--format', + '{{.Id}} {{.Os}}/{{.Architecture}}', + 'droiddeck-local-cross:24.04-v5']) + build_cmd, build_input = calls[1] + self.assertEqual(build_cmd[:8], ['docker', 'build', '--platform', 'linux/amd64', + '--tag', 'droiddeck-local-cross:24.04-v5', '--file', '-']) + self.assertEqual(build_input, b'FROM ubuntu:24.04\nRUN echo ok\n') + run_cmd = calls[3][0] + self.assertIn('sha256:built-v5-id', run_cmd) + self.assertNotIn('sha256:built-v5-id linux/amd64', run_cmd) + self.assertNotIn('sha256:arm64-id', run_cmd) + self.assertNotIn('sha256:win-id', run_cmd) + self.assertNotIn('droiddeck-local-cross:24.04-v5', run_cmd) + self.assertNotIn('apt-get', run_cmd[-1]) + self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime') + self.assertEqual(provenance, manifest) + + def test_windows_ime_preparation_reports_default_image_build_failure(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools').mkdir(parents=True) + (root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\n') + commands = [] + build_error = prepare.subprocess.CalledProcessError(17, ['docker', 'build']) + + def run(command, check=True, capture_output=False, text=False, input=None): + commands.append(command) + if command[1:3] == ['image', 'inspect']: + return mock.Mock(returncode=1, stdout='', stderr='No such image') + if command[1] == 'build': + raise build_error + self.fail('unexpected command: ' + repr(command)) + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + with self.assertRaises(ValueError) as context: + prepare.prepare_ime(prepare.vr_build.IMAGE) + message = str(context.exception) + self.assertIn(prepare.vr_build.IMAGE, message) + self.assertRegex(message, r'(?i)build.*default compiler') + self.assertRegex(message, r'(?i)output.*rerun') + self.assertIs(context.exception.__cause__, build_error) + self.assertEqual(context.exception.__cause__.returncode, 17) + self.assertEqual([cmd[1] for cmd in commands], ['image', 'build']) + + def test_windows_ime_preparation_stops_if_default_image_still_has_no_id_or_wrong_platform_after_build(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools').mkdir(parents=True) + (root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\n') + for label, result, detail in ( + ('missing', mock.Mock(returncode=1, stdout='', stderr='still missing'), 'still missing'), + ('wrong-arch', mock.Mock(returncode=0, stdout='sha256:arm64-id linux/arm64\n', stderr=''), 'linux/arm64'), + ('malformed', mock.Mock(returncode=0, stdout='sha256:only-id\n', stderr=''), 'sha256:only-id'), + ): + with self.subTest(case=label): + commands = [] + + def run(command, check=True, capture_output=False, text=False, input=None): + commands.append(command) + if command[1:3] == ['image', 'inspect']: + return result + return mock.Mock(returncode=0) + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + with self.assertRaisesRegex(ValueError, 'requires the existing Docker image') as context: + prepare.prepare_ime(prepare.vr_build.IMAGE) + self.assertIn('linux/amd64', str(context.exception)) + self.assertIn(prepare.vr_build.IMAGE, str(context.exception)) + self.assertIn(detail, str(context.exception)) + self.assertEqual([cmd[1] for cmd in commands], ['image', 'build', 'image']) + + def test_windows_ime_preparation_rejects_a_missing_or_incompatible_custom_image_before_running(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + for label, result, detail in ( + ('missing', mock.Mock(returncode=1, stdout='', stderr='No such image'), 'No such image'), + ('linux/arm64', mock.Mock(returncode=0, stdout='sha256:custom-arm linux/arm64\n', stderr=''), 'linux/arm64'), + ('windows/amd64', mock.Mock(returncode=0, stdout='sha256:custom-win windows/amd64\n', stderr=''), 'windows/amd64'), + ): + with self.subTest(case=label): + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', return_value=result) as run: + with self.assertRaisesRegex(ValueError, 'requires the existing Docker image') as context: + prepare.prepare_ime('custom-image') + self.assertIn('linux/amd64', str(context.exception)) + self.assertIn('custom-image', str(context.exception)) + self.assertIn(detail, str(context.exception)) + run.assert_called_once() + self.assertEqual(run.call_args.args[0], ['docker', 'image', 'inspect', '--format', + '{{.Id}} {{.Os}}/{{.Architecture}}', 'custom-image']) + + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_ring_pad_sdl_identity.py b/tools/tests/test_ring_pad_sdl_identity.py new file mode 100644 index 0000000000..d10ca0257f --- /dev/null +++ b/tools/tests/test_ring_pad_sdl_identity.py @@ -0,0 +1,125 @@ +from pathlib import Path +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +SHIM = r""" +#include +#include +#include + +int ioctl(int fd, unsigned long request, ...) { + va_list ap; + va_start(ap, request); + struct input_id *id = va_arg(ap, struct input_id *); + va_end(ap); + (void)fd; + if (request != EVIOCGID) return -1; + memset(id, 0, sizeof(*id)); + id->bustype = 3; + id->vendor = 0x045e; + id->product = 0x028e; + return 0; +} +""" + +QUERY = r""" +#include +#include +#include +#include +#include + +void query(const char *path) { + struct input_id id; + int fd = open(path, O_RDONLY | O_CLOEXEC); + int rc = ioctl(fd, EVIOCGID, &id); + printf("%d %04x:%04x\n", rc, id.vendor, id.product); + close(fd); +} +""" + +PROGRAM = r""" +#include +#include +#include + +void query(const char *path); + +int main(int argc, char **argv) { + (void)argc; + if (strcmp(argv[1], "-") != 0) dlopen(argv[1], RTLD_NOW); + if (strcmp(argv[2], "program") == 0) { + query(argv[3]); + } else { + void *sdl = dlopen(argv[2], RTLD_NOW | RTLD_LOCAL); + void (*sdl_query)(const char *) = (void (*)(const char *))dlsym(sdl, "query"); + sdl_query(argv[3]); + } + fflush(stdout); + return 0; +} +""" + + +@unittest.skipUnless(sys.platform == "linux" and shutil.which("cc"), "needs Linux and cc") +class RingPadSdlIdentityTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dir = Path(tempfile.mkdtemp()) + build = cls.dir / "build" + build.mkdir() + for name, text in (("shim.c", SHIM), ("query.c", QUERY), ("program.c", PROGRAM), ("empty.c", "int bus;\n")): + (build / name).write_text(text) + cls.lib = cls.dir / "libddsession.so" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib), + *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) + cls.shim = cls.dir / "libshim.so" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.shim), str(build / "shim.c")], check=True) + cls.winebus = cls.dir / "winebus.so" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "empty.c")], check=True) + cls.sdl_library = cls.dir / "libSDL2-2.0.so.0" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.sdl_library), str(build / "query.c")], check=True) + cls.program = cls.dir / "program" + subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "query.c"), "-ldl"], + check=True) + cls.ring = cls.dir / "ring0" + cls.ring.write_text("") + cls.virtual = cls.dir / "ring16" + cls.virtual.write_text("") + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.dir, True) + + def query(self, winebus=True, caller="sdl", path=None, **extra): + env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.lib, self.shim), + FAKE_EVDEV_MEMFD_PATHS="0=%s;16=%s" % (self.ring, self.virtual)) + env.pop("FAKE_EVDEV_STEAM_PAD_AS_X360", None) + env.update(extra) + result = subprocess.run([str(self.program), str(self.winebus) if winebus else "-", + str(self.sdl_library) if caller == "sdl" else "program", str(path or self.ring)], + env=env, capture_output=True, text=True, timeout=10, check=True) + return result.stdout.strip() + + def test_sdl_in_a_winebus_process_sees_a_ring_pad_as_the_steam_input_pad(self): + self.assertEqual(self.query(), "0 28de:11ff") + + def test_sdl_outside_winebus_keeps_the_pad_identity(self): + self.assertEqual(self.query(winebus=False), "0 045e:028e") + + def test_other_callers_and_devices_keep_their_identity(self): + self.assertEqual(self.query(caller="program"), "0 045e:028e") + self.assertEqual(self.query(path=self.virtual), "0 045e:028e") + + def test_a_winebus_without_a_udev_bus_keeps_the_pad_for_sdl(self): + self.assertEqual(self.query(FAKE_EVDEV_STEAM_PAD_AS_X360="1"), "0 045e:028e") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_robust_list_preload.py b/tools/tests/test_robust_list_preload.py new file mode 100644 index 0000000000..acbb899fec --- /dev/null +++ b/tools/tests/test_robust_list_preload.py @@ -0,0 +1,87 @@ +from pathlib import Path +import os +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +PROGRAM = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +static int ask(const char *name) { + struct robust_list_head *head = NULL; + size_t len = 0; + errno = 0; + long ret = syscall(SYS_get_robust_list, 0, &head, &len); + int ok = ret == 0 && head != NULL && len == sizeof(*head) && head->futex_offset < 0; + printf("%s %s ret=%ld errno=%d len=%zu\n", name, ok ? "ok" : "failed", ret, errno, len); + return ok; +} + +static int leader_gone(void) { + char line[256]; + FILE *status = fopen("/proc/self/status", "r"); + int zombie = 0; + while (status && fgets(line, sizeof line, status)) + if (!strncmp(line, "State:", 6)) zombie = strchr(line, 'Z') != NULL; + if (status) fclose(status); + return zombie; +} + +static void *after_leader(void *unused) { + (void)unused; + for (int i = 0; i < 200 && !leader_gone(); i++) usleep(10000); + printf("leader %s\n", leader_gone() ? "zombie" : "alive"); + exit(ask("after-leader-exit") ? 0 : 1); +} + +static void *thread(void *unused) { + (void)unused; + return (void *)(long)ask("thread"); +} + +int main(void) { + pthread_t t; + void *ok; + if (!ask("main")) return 1; + pthread_create(&t, NULL, thread, NULL); + pthread_join(t, &ok); + if (!ok) return 1; + pthread_create(&t, NULL, after_leader, NULL); + pthread_exit(NULL); +} +""" + + +class RobustListAfterLeaderExit(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = Path(tempfile.mkdtemp()) + cls.lib = cls.tmp / "librobust.so" + subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib), + str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), + str(PRELOAD / "writewatch.c"), str(PRELOAD / "clockpause.c"), "-ldl"], check=True) + source = cls.tmp / "robust.c" + source.write_text(PROGRAM) + subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-pthread", "-o", str(cls.tmp / "robust"), str(source)], + check=True) + + def test_every_thread_gets_its_list_after_the_first_thread_exits(self): + result = subprocess.run([str(self.tmp / "robust")], capture_output=True, text=True, timeout=30, + env=dict(os.environ, LD_PRELOAD=str(self.lib))) + self.assertIn("leader zombie", result.stdout) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn("after-leader-exit ok", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_session_bus.py b/tools/tests/test_session_bus.py index 3528500f1d..81f1801741 100644 --- a/tools/tests/test_session_bus.py +++ b/tools/tests/test_session_bus.py @@ -34,7 +34,10 @@ class SessionBusTest(unittest.TestCase): match = re.search(r'^ *if \[ -z "\$\{DBUS_SESSION_BUS_ADDRESS:-\}" \]; then\n.*?^ *fi\n *fi\n', SESSION.read_text(), re.M | re.S) self.assertIsNotNone(match) - script = "nap() { sleep \"$1\"; }\n" + match.group(0) + 'echo "ADDRESS=$DBUS_SESSION_BUS_ADDRESS"\nkill %1 2>/dev/null\n' + spawn = re.search(r'^dd_spawn\(\) \{\n.*?^\}\n', SESSION.read_text(), re.M | re.S) + self.assertIsNotNone(spawn) + script = ("nap() { sleep \"$1\"; }\n" + spawn.group(0) + match.group(0) + + 'echo "ADDRESS=$DBUS_SESSION_BUS_ADDRESS"\nkill $dd_spawned 2>/dev/null\n') env = {"PATH": "%s:/usr/bin:/bin" % self.bin, "XDG_RUNTIME_DIR": str(self.runtime)} if env_address: env["DBUS_SESSION_BUS_ADDRESS"] = env_address diff --git a/tools/tests/test_session_dbus.py b/tools/tests/test_session_dbus.py new file mode 100644 index 0000000000..d602cab9e1 --- /dev/null +++ b/tools/tests/test_session_dbus.py @@ -0,0 +1,199 @@ +"""Real subprocess checks that droiddeck-session starts its bus before the compositor.""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SESSION = ROOT / "tools/linuxfs/overlay/usr/local/bin/droiddeck-session" + +FIXTURE = '''#!/usr/bin/env python3 +import ctypes, json, os, signal, subprocess, sys, time + + +def stat_ppid(pid): + try: + with open(f"/proc/{pid}/stat", "r", encoding="utf-8") as f: + data = f.read() + return int(data.rsplit(") ", 1)[1].split()[1]) + except (FileNotFoundError, IndexError, ProcessLookupError, ValueError): + return None + + +def wait_orphan(pid, timeout=2.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + wpid, status = os.waitpid(pid, os.WNOHANG) + if wpid == pid: + return status + except ChildProcessError: + return None + time.sleep(0.05) + return None + + +libc = ctypes.CDLL(None, use_errno=True) +if libc.prctl(36, 1, 0, 0, 0) != 0: + raise OSError(ctypes.get_errno(), "prctl(PR_SET_CHILD_SUBREAPER) failed") + +harness = sys.argv[1] +fpid = os.getpid() +sib = subprocess.Popen(["sleep", "60"]) +orphan_pid = None +orphan_adopted = False +orphan_reaped = False +orphan_killed = False +out, rc = "", None +try: + helper = ( + "import subprocess; " + "p = subprocess.Popen(['sleep', '60'], start_new_session=True, " + "stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL); " + "print(p.pid)" + ) + spawner = subprocess.run([sys.executable, "-c", helper], + capture_output=True, text=True, check=True, timeout=5) + orphan_pid = int(spawner.stdout.strip()) + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if stat_ppid(orphan_pid) == fpid: + orphan_adopted = True + break + time.sleep(0.05) + res = subprocess.run(["bash", harness, "steam"], + env=dict(os.environ, DD_INSIDE="1"), + capture_output=True, text=True, timeout=15) + out, rc = res.stdout, res.returncode + if orphan_adopted: + status = wait_orphan(orphan_pid) + orphan_reaped = status is not None + orphan_killed = ( + orphan_reaped + and os.WIFSIGNALED(status) + and os.WTERMSIG(status) == signal.SIGKILL + ) +except subprocess.TimeoutExpired as exc: + out = exc.stdout or "" + if isinstance(out, bytes): + out = out.decode() + rc = "timeout" +finally: + alive = sib.poll() is None + sib.kill() + try: + sib.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + if orphan_pid is not None and not orphan_reaped: + try: + os.kill(orphan_pid, signal.SIGKILL) + except ProcessLookupError: + pass + wait_orphan(orphan_pid) + +ppid = bus = None +for line in out.splitlines(): + if line.startswith("PPID="): + ppid = int(line[5:]) + elif line.startswith("BUS="): + bus = line[4:] +print(json.dumps({ + "fixture_pid": fpid, + "inner_ppid": ppid, + "inner_bus": bus, + "fixture_bus": os.environ.get("DBUS_SESSION_BUS_ADDRESS", ""), + "sibling_killed": not alive, + "orphan_adopted": orphan_adopted, + "orphan_killed": orphan_killed, + "inner_rc": rc, +})) +''' + +HARNESS = r"""#!/bin/bash +set -u +export HOME=${{HOME:-/root}} +mode=${{1:-desktop}} +shift || true +{guard_before} +if [ -z "${{DD_INSIDE:-}}" ]; then + exec "$DD_FIXTURE" "$0" +fi +{guard_after} +printf 'PPID=%s\n' "$PPID" +printf 'BUS=%s\n' "${{DBUS_SESSION_BUS_ADDRESS:-}}" +{reap} +reap_orphans +""" + +SETUP = 'if [ -z "${DD_INSIDE:-}" ]; then\n /usr/local/bin/droiddeck-fonts' + + +def extract(): + src = SESSION.read_text(encoding="utf-8") + gstart = src.index("# Steam and its helpers share one session bus per session") + guard = src[gstart:src.index("\nfi\n", gstart) + 4] + rstart = src.index("reap_orphans() {") + reap = src[rstart:src.index("\n}\n", rstart) + 3] + return src, guard, reap + + +def build_harness(): + src, guard, reap = extract() + assert src.index("shift || true") < src.index(guard) + if src.index(guard) < src.index(SETUP): + before, after = guard, "" + else: + before, after = "", guard + return HARNESS.format(guard_before=before, guard_after=after, reap=reap) + + +@unittest.skipUnless( + sys.platform.startswith("linux") + and shutil.which("dbus-run-session") + and shutil.which("bash"), + "requires Linux and dbus-run-session and bash on PATH", +) +class SessionDBusTest(unittest.TestCase): + def _run(self, inherited): + with tempfile.TemporaryDirectory() as td: + td = Path(td) + harness = td / "harness.sh" + fixture = td / "fixture.py" + harness.write_text(build_harness(), encoding="utf-8") + harness.chmod(0o755) + fixture.write_text(FIXTURE, encoding="utf-8") + fixture.chmod(0o755) + env = {k: v for k, v in os.environ.items() + if k not in ("DBUS_SESSION_BUS_ADDRESS", "DD_INSIDE")} + env["DD_FIXTURE"] = str(fixture) + cmd = ["bash", str(harness), "steam"] + if inherited: + cmd = ["dbus-run-session", "--"] + cmd + res = subprocess.run(cmd, env=env, cwd=td, capture_output=True, + text=True, timeout=30) + self.assertEqual(res.returncode, 0, res.stderr) + return json.loads(res.stdout.strip().splitlines()[-1]) + + def _check(self, data): + self.assertEqual(data["inner_ppid"], data["fixture_pid"]) + self.assertTrue(data["fixture_bus"]) + self.assertEqual(data["inner_bus"], data["fixture_bus"]) + self.assertTrue(data["sibling_killed"]) + self.assertTrue(data["orphan_adopted"]) + self.assertTrue(data["orphan_killed"]) + self.assertEqual(data["inner_rc"], 0) + + def test_fresh_bus(self): + self._check(self._run(False)) + + def test_inherited_bus(self): + self._check(self._run(True)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_steam_ime_runtime.py b/tools/tests/test_steam_ime_runtime.py new file mode 100644 index 0000000000..44c2e90aed --- /dev/null +++ b/tools/tests/test_steam_ime_runtime.py @@ -0,0 +1,65 @@ +"""Steam pinyin runtime requirements, without network access or a running Steam client.""" +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +TOOLS = Path(__file__).resolve().parents[1] +SESSION = TOOLS / 'linuxfs/overlay/usr/local/bin/droiddeck-session' +WRAPPER = '/usr/local/bin/droiddeck-steam-ime' +ENGINE = '/usr/local/lib/droiddeck-ime/ibus-engine-pinyin' +DAEMON = '/usr/bin/ibus-daemon' +CLIENT = '/usr/bin/ibus' + + +class SteamImeRuntimeTest(unittest.TestCase): + @unittest.skipUnless(shutil.which('bash') and shutil.which('timeout'), 'needs bash and timeout') + def test_steam_start_only_exports_address_after_success(self): + source = SESSION.read_text() + start = source.index(' unset IBUS_ADDRESS\n ime_ibus_pid=') + fragment = source[start:source.index(' while :; do', start)] + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + commands = { + WRAPPER: ('wrapper', '#!/bin/bash\nprintf launched > "$XDG_RUNTIME_DIR/wrapper-started"\nexec sleep 5\n'), + ENGINE: ('engine', '#!/bin/bash\nexit 0\n'), + DAEMON: ('daemon', '#!/bin/bash\nexit 0\n'), + CLIENT: ('client', '#!/bin/bash\ntest -f "$XDG_RUNTIME_DIR/wrapper-started" || exit 1\nprintf "pinyin\\n"\n'), + } + for path, (basename, script) in commands.items(): + f = root / basename + if path != DAEMON: + f.write_text(script) + f.chmod(0o755) + fragment = fragment.replace(f'{path} ', f'"{f}" ').replace(f'{path} ]', f'"{f}" ]') + env = dict(os.environ, XDG_RUNTIME_DIR=directory, IBUS_ADDRESS='unrelated-address') + cleanup = '\nprintf "address=%s\\n" "${IBUS_ADDRESS-unset}"\n' + cleanup += 'printf "pid=%s\\n" "${ime_ibus_pid:-none}"; stop_steam_ime\n' + process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + fragment + cleanup], + text=True, capture_output=True, check=True, env=env, timeout=10) + self.assertIn('does not include IBus', process.stdout) + self.assertIn('address=unset', process.stdout) + self.assertFalse((root / 'wrapper-started').exists()) + (root / 'daemon').write_text(commands[DAEMON][1]) + (root / 'daemon').chmod(0o755) + (root / 'client').write_text('#!/bin/bash\nexit 1\n') + refused = fragment.replace('SECONDS + 5', 'SECONDS + 1') + process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + refused + cleanup], + text=True, capture_output=True, check=True, env=env, timeout=10) + self.assertIn('the pinyin engine did not start', process.stdout) + self.assertIn('address=unset', process.stdout) + self.assertIn('pid=none', process.stdout) + (root / 'wrapper-started').unlink() + (root / 'client').write_text(commands[CLIENT][1]) + process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + fragment + cleanup], + text=True, capture_output=True, check=True, env=env, timeout=10) + self.assertIn('pinyin engine ready', process.stdout) + self.assertIn('address=unix:path=', process.stdout) + self.assertEqual((root / 'wrapper-started').read_text(), 'launched') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_steam_tool_manifest_seed.py b/tools/tests/test_steam_tool_manifest_seed.py new file mode 100644 index 0000000000..54d547c451 --- /dev/null +++ b/tools/tests/test_steam_tool_manifest_seed.py @@ -0,0 +1,205 @@ +import runpy +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from tools.tests.test_droiddeck_fex import AppInfoTest + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +SESSION = BIN / "droiddeck-session" +COMPAT = runpy.run_path(str(BIN / "steam-compatibility")) +EAC = 1826330 +SCOUT = 1070560 +EAC_ID = str(EAC) +SCOUT_ID = str(SCOUT) +EAC_NAME = "Proton EasyAntiCheat Runtime" +SCOUT_NAME = "Steam Linux Runtime 1.0 (scout)" + + +def tool(name, osarch="", kind="tool", installdir=None): + return { + "common": {"name": name, "oslist": "linux", "osarch": osarch, "type": kind}, + "config": {"installdir": installdir or name}, + } + + +class SteamToolManifestSeedTest(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.steam = self.root / "Steam" + (self.steam / "appcache").mkdir(parents=True) + (self.steam / "steamapps").mkdir() + self.entries = {EAC: tool(EAC_NAME), SCOUT: tool(SCOUT_NAME)} + self.write_appinfo() + + def write_appinfo(self, entries=None): + COMPAT["APPINFO_CACHE"].clear() + (self.steam / "appcache/appinfo.vdf").write_bytes( + AppInfoTest.appinfo(self.entries if entries is None else entries)) + + def manifest(self, app, root=None): + return (root or self.steam) / ("steamapps/appmanifest_%s.acf" % app) + + def seed(self): + return COMPAT["seed_unavailable_arm64_tools"](str(self.steam)) + + def test_seeds_bare_manifests_for_unavailable_tool_dependencies(self): + self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID]) + for app, name in ((EAC_ID, EAC_NAME), (SCOUT_ID, SCOUT_NAME)): + text = self.manifest(app).read_text() + for expected in ('"appid" "%s"' % app, '"Universe" "1"', '"StateFlags" "4"', + '"name" "%s"' % name, '"installdir" "%s"' % name, + '"AutoUpdateBehavior" "1"'): + self.assertIn(expected, text) + self.assertFalse(self.manifest("976730").exists()) + + def test_seeding_is_idempotent(self): + self.seed() + first = {app: self.manifest(app).read_text() for app in (EAC_ID, SCOUT_ID)} + self.assertEqual(self.seed(), []) + self.assertEqual({app: self.manifest(app).read_text() for app in first}, first) + + def test_a_real_install_in_another_library_is_never_overwritten(self): + other = self.root / "SD" + (other / "steamapps").mkdir(parents=True) + existing = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"4"\n}\n' % SCOUT_ID + (other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(existing) + (self.steam / "steamapps/libraryfolders.vdf").write_text( + '"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other) + self.assertEqual(self.seed(), [EAC_ID]) + self.assertFalse(self.manifest(SCOUT_ID).exists()) + self.assertEqual((other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text(), existing) + + def test_a_partial_install_in_another_library_is_completed_in_place(self): + other = self.root / "SD" + (other / "steamapps").mkdir(parents=True) + partial = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"2"\n}\n' % SCOUT_ID + (other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(partial) + (self.steam / "steamapps/libraryfolders.vdf").write_text( + '"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other) + self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID]) + self.assertFalse(self.manifest(SCOUT_ID).exists()) + self.assertIn('"StateFlags" "4"', + (other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text()) + + def test_a_real_install_in_any_library_wins_over_a_partial_one(self): + other = self.root / "SD" + (other / "steamapps").mkdir(parents=True) + partial = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"2"\n}\n' % SCOUT_ID + installed = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"4"\n}\n' % SCOUT_ID + self.manifest(SCOUT_ID).write_text(partial) + (other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(installed) + (self.steam / "steamapps/libraryfolders.vdf").write_text( + '"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other) + self.assertEqual(self.seed(), [EAC_ID]) + self.assertEqual(self.manifest(SCOUT_ID).read_text(), partial) + self.assertEqual((other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text(), installed) + + def test_a_failed_write_leaves_no_manifest_behind(self): + real_link = COMPAT["os"].link + + def fail_for_scout(source, target): + if SCOUT_ID in str(target): + raise OSError("disk full") + return real_link(source, target) + + with mock.patch.object(COMPAT["os"], "link", side_effect=fail_for_scout): + self.assertEqual(self.seed(), [EAC_ID]) + self.assertFalse(self.manifest(SCOUT_ID).exists()) + self.assertEqual(sorted(p.name for p in (self.steam / "steamapps").iterdir()), + ["appmanifest_%s.acf" % EAC_ID]) + self.assertEqual(self.seed(), [SCOUT_ID]) + self.assertEqual(self.manifest(SCOUT_ID).read_text(), + COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True)) + + def test_new_manifest_publication_preserves_a_concurrent_install(self): + real_link = COMPAT["os"].link + installed = COMPAT["manifest_text"](SCOUT_ID, "Existing tool", "Existing", False) + + def publish(source, target): + if SCOUT_ID in str(target): + Path(target).write_text(installed) + return real_link(source, target) + + with mock.patch.object(COMPAT["os"], "link", side_effect=publish): + self.assertEqual(self.seed(), [EAC_ID]) + self.assertEqual(self.manifest(SCOUT_ID).read_text(), installed) + self.assertEqual(self.seed(), []) + self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*"))) + + def test_partial_staged_write_is_not_published_and_retry_repairs(self): + real_temporary = COMPAT["tempfile"].NamedTemporaryFile + + def temporary(*args, **kwargs): + output = real_temporary(*args, **kwargs) + real_write = output.write + + def write(text): + if SCOUT_ID in text: + real_write(text[:text.index(' "installdir"')]) + output.flush() + raise OSError("disk full") + return real_write(text) + + output.write = write + return output + + with mock.patch.object(COMPAT["tempfile"], "NamedTemporaryFile", side_effect=temporary): + self.assertEqual(self.seed(), [EAC_ID]) + self.assertFalse(self.manifest(SCOUT_ID).exists()) + self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*"))) + self.assertEqual(self.seed(), [SCOUT_ID]) + self.assertEqual(self.manifest(SCOUT_ID).read_text(), + COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True)) + + def test_failed_replacement_preserves_partial_manifest_and_retry_repairs(self): + partial = '"AppState" { "appid" "%s" "StateFlags" "2" }' % SCOUT_ID + self.manifest(SCOUT_ID).write_text(partial) + with mock.patch.object(COMPAT["os"], "replace", side_effect=OSError("disk full")): + self.assertEqual(self.seed(), [EAC_ID]) + self.assertEqual(self.manifest(SCOUT_ID).read_text(), partial) + self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*"))) + self.assertEqual(self.seed(), [SCOUT_ID]) + self.assertEqual(self.manifest(SCOUT_ID).read_text(), + COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True)) + + def test_tools_with_an_arm64_depot_are_skipped(self): + entries = dict(self.entries) + entries[SCOUT] = tool(SCOUT_NAME, osarch="arm64") + self.write_appinfo(entries) + self.assertEqual(self.seed(), [EAC_ID]) + self.assertFalse(self.manifest(SCOUT_ID).exists()) + + def test_an_app_that_is_not_a_tool_is_skipped(self): + entries = dict(self.entries) + entries[SCOUT] = tool(SCOUT_NAME, kind="game") + self.write_appinfo(entries) + self.assertEqual(self.seed(), [EAC_ID]) + self.assertFalse(self.manifest(SCOUT_ID).exists()) + + def test_missing_appinfo_uses_the_display_names(self): + (self.steam / "appcache/appinfo.vdf").unlink() + COMPAT["APPINFO_CACHE"].clear() + self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID]) + self.assertIn('"name" "%s"' % SCOUT_NAME, self.manifest(SCOUT_ID).read_text()) + + def test_flag_seeds_without_running_full_compatibility_setup(self): + with mock.patch.object(COMPAT["sys"], "argv", + ["steam-compatibility", str(self.steam), "--seed-arm64-tools"]): + COMPAT["main"]() + self.assertTrue(self.manifest(EAC_ID).is_file()) + self.assertTrue(self.manifest(SCOUT_ID).is_file()) + self.assertFalse((self.steam / "compatibilitytools.d").exists()) + + def test_session_seeds_only_on_the_arm64_client_path(self): + arm64, x64 = SESSION.read_text().split( + " else\n _dd_x64_tool=$(droiddeck-steam-x64 --default-tool)", 1) + self.assertIn('steam-compatibility "$steam_root" --seed-arm64-tools', arm64) + self.assertNotIn("--seed-arm64-tools", x64) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_subsurface_release.py b/tools/tests/test_subsurface_release.py index ea472be5fe..c8ad7fcf12 100644 --- a/tools/tests/test_subsurface_release.py +++ b/tools/tests/test_subsurface_release.py @@ -95,7 +95,7 @@ class SubsurfaceReleaseTest(unittest.TestCase): def test_compositor_attach_and_commit_use_the_release_hold(self): self.assertIn('pending_releases_cancel(buffer);', function_body(self.source, 'take_dmabuf')) - commit = function_body(self.source, 'surface_commit') + commit = function_body(self.source, 'surface_state_apply') self.assertIn('pending_releases_apply(s);', commit) self.assertLess(commit.index('take_dmabuf(s, db, buffer);'), commit.index('pending_releases_apply(s);')) self.assertLess(commit.index('buf_trace_attach(buffer);'), commit.index('if (s->role == ROLE_CURSOR)')) diff --git a/tools/tests/test_text_input.py b/tools/tests/test_text_input.py new file mode 100644 index 0000000000..352bd35ad8 --- /dev/null +++ b/tools/tests/test_text_input.py @@ -0,0 +1,907 @@ +"""Exercise the text bridge through a real X11 client and Xutf8LookupString.""" +import ctypes +import ctypes.util +import locale +import os +import runpy +import select +import shutil +import signal +import socket +import stat +import struct +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path +from types import SimpleNamespace + +HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-text-input" +XVFB = shutil.which("Xvfb") +FOCUS_PROPERTY = b"GAMESCOPE_KEYBOARD_FOCUS_DISPLAY" +SAMPLE = "中文ABC123,。é😀" +MAX_TEXT = 65536 +ACK_OK = b"\x01" +ACK_FAILED = b"\x00" + +KEY_PRESS_MASK = 1 << 0 +KEY_RELEASE_MASK = 1 << 1 +STRUCTURE_NOTIFY_MASK = 1 << 17 +KEY_PRESS = 2 +KEY_RELEASE = 3 +MAP_NOTIFY = 19 +MAPPING_NOTIFY = 34 +REVERT_TO_PARENT = 2 +PROPERTY_REPLACE = 0 +INPUT_STYLE = 0x0408 # XIMPreeditNothing | XIMStatusNothing +LC_ALL = 6 # glibc +CODESET = 14 # glibc +KEYSYM_BACKSPACE = 0xff08 +KEYSYM_RETURN = 0xff0d + +_X11 = None + + +class XKeyEvent(ctypes.Structure): + _fields_ = [ + ("type", ctypes.c_int), + ("serial", ctypes.c_ulong), + ("send_event", ctypes.c_int), + ("display", ctypes.c_void_p), + ("window", ctypes.c_ulong), + ("root", ctypes.c_ulong), + ("subwindow", ctypes.c_ulong), + ("time", ctypes.c_ulong), + ("x", ctypes.c_int), + ("y", ctypes.c_int), + ("x_root", ctypes.c_int), + ("y_root", ctypes.c_int), + ("state", ctypes.c_uint), + ("keycode", ctypes.c_uint), + ("same_screen", ctypes.c_int), + ] + + +class XModifierKeymap(ctypes.Structure): + _fields_ = [ + ("max_keypermod", ctypes.c_int), + ("modifiermap", ctypes.POINTER(ctypes.c_ubyte)), + ] + + +def _load_x11(): + lib = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6") + lib.XInitThreads.restype = ctypes.c_int + lib.XInitThreads() # the consumer reads events in its own thread + lib.XOpenDisplay.argtypes = [ctypes.c_char_p] + lib.XOpenDisplay.restype = ctypes.c_void_p + lib.XCloseDisplay.argtypes = [ctypes.c_void_p] + lib.XDefaultRootWindow.argtypes = [ctypes.c_void_p] + lib.XDefaultRootWindow.restype = ctypes.c_ulong + lib.XCreateSimpleWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, + ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong, + ctypes.c_ulong] + lib.XCreateSimpleWindow.restype = ctypes.c_ulong + lib.XDestroyWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + lib.XSelectInput.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_long] + lib.XMapWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + lib.XSetInputFocus.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong] + lib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int] + lib.XPending.argtypes = [ctypes.c_void_p] + lib.XPending.restype = ctypes.c_int + lib.XNextEvent.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + lib.XConnectionNumber.argtypes = [ctypes.c_void_p] + lib.XConnectionNumber.restype = ctypes.c_int + lib.XSetLocaleModifiers.argtypes = [ctypes.c_char_p] + lib.XOpenIM.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + lib.XOpenIM.restype = ctypes.c_void_p + lib.XCreateIC.restype = ctypes.c_void_p + lib.XDestroyIC.argtypes = [ctypes.c_void_p] + lib.XCloseIM.argtypes = [ctypes.c_void_p] + lib.Xutf8LookupString.argtypes = [ctypes.c_void_p, ctypes.POINTER(XKeyEvent), + ctypes.POINTER(ctypes.c_char), ctypes.c_int, + ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.c_int)] + lib.Xutf8LookupString.restype = ctypes.c_int + lib.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), + ctypes.POINTER(ctypes.c_int)] + lib.XRefreshKeyboardMapping.argtypes = [ctypes.c_void_p] + lib.XGetKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_int, + ctypes.POINTER(ctypes.c_int)] + lib.XGetKeyboardMapping.restype = ctypes.POINTER(ctypes.c_ulong) + lib.XQueryKeymap.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + lib.XFree.argtypes = [ctypes.c_void_p] + lib.XGetModifierMapping.argtypes = [ctypes.c_void_p] + lib.XGetModifierMapping.restype = ctypes.POINTER(XModifierKeymap) + lib.XFreeModifiermap.argtypes = [ctypes.POINTER(XModifierKeymap)] + lib.XFreeModifiermap.restype = ctypes.c_int + lib.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] + lib.XInternAtom.restype = ctypes.c_ulong + lib.XChangeProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, + ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int] + return lib + + +def libx11(): + global _X11 + if _X11 is None: + _X11 = _load_x11() + return _X11 + + +class XTextConsumer: + """An ordinary X11 client: it owns a focused window and keeps reading the key events the + bridge injects, converting each one through its own input context.""" + + def __init__(self, lib, display): + self.lib = lib + self.lock = threading.Lock() + self._text = b"" + self._presses = [] + self._releases = [] + self._keysyms = [] + self._stopped = threading.Event() + self._thread = None + self._im = None + self._ic = None + self._dpy = lib.XOpenDisplay(display.encode()) + if not self._dpy: + raise RuntimeError("the test client cannot open X display " + display) + try: + self._window = lib.XCreateSimpleWindow(self._dpy, lib.XDefaultRootWindow(self._dpy), + 0, 0, 200, 100, 0, 0, 0) + lib.XSelectInput(self._dpy, self._window, + KEY_PRESS_MASK | KEY_RELEASE_MASK | STRUCTURE_NOTIFY_MASK) + lib.XMapWindow(self._dpy, self._window) + self._wait_for_map(display) + lib.XSetInputFocus(self._dpy, self._window, REVERT_TO_PARENT, 0) + lib.XSync(self._dpy, False) + self.snapshot = self.keymap() + self._open_input_context() + except Exception: + self.close() + raise + + def _wait_for_map(self, display): + event = ctypes.create_string_buffer(192) + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if self.lib.XPending(self._dpy): + self.lib.XNextEvent(self._dpy, ctypes.cast(event, ctypes.c_void_p)) + if ctypes.cast(event, ctypes.POINTER(XKeyEvent)).contents.type == MAP_NOTIFY: + return + else: + select.select([self.lib.XConnectionNumber(self._dpy)], [], [], 0.05) + raise RuntimeError("the test client window never became viewable on " + display) + + def _open_input_context(self): + locale.setlocale(locale.LC_CTYPE, "C.UTF-8") + self.lib.XSetLocaleModifiers(b"@im=none") + self._im = self.lib.XOpenIM(self._dpy, None, None, None) + if not self._im: + raise RuntimeError("Xlib has no input method here, so Xutf8LookupString cannot run") + self._ic = self.lib.XCreateIC(ctypes.c_void_p(self._im), + ctypes.c_char_p(b"inputStyle"), ctypes.c_ulong(INPUT_STYLE), + ctypes.c_char_p(b"clientWindow"), ctypes.c_ulong(self._window), + ctypes.c_char_p(b"focusWindow"), ctypes.c_ulong(self._window), + ctypes.c_void_p(0)) + if not self._ic: + raise RuntimeError("Xlib refused an input context for Xutf8LookupString") + self.lib.XSync(self._dpy, False) + + def start(self): + self._thread = threading.Thread(target=self._pump, daemon=True) + self._thread.start() + + def _pump(self): + event = ctypes.create_string_buffer(192) + raw = ctypes.cast(event, ctypes.c_void_p) + fd = self.lib.XConnectionNumber(self._dpy) + while not self._stopped.is_set(): + try: + pending = self.lib.XPending(self._dpy) + except (OSError, ValueError): + return + if not pending: + try: + readable, _, _ = select.select([fd], [], [], 0.05) + except (OSError, ValueError): + return + if not readable: + continue + while self.lib.XPending(self._dpy): + self.lib.XNextEvent(self._dpy, raw) + if ctypes.cast(event, ctypes.POINTER(ctypes.c_int)).contents.value == MAPPING_NOTIFY: + self.lib.XRefreshKeyboardMapping(raw) + continue + key = ctypes.cast(event, ctypes.POINTER(XKeyEvent)) + if key.contents.type == KEY_PRESS: + self._press(key) + elif key.contents.type == KEY_RELEASE: + with self.lock: + self._releases.append(key.contents.keycode) + + def _press(self, key): + buffer = ctypes.create_string_buffer(64) + keysym = ctypes.c_ulong(0) + status = ctypes.c_int(0) + count = self.lib.Xutf8LookupString(ctypes.c_void_p(self._ic), key, buffer, len(buffer), + ctypes.byref(keysym), ctypes.byref(status)) + with self.lock: + self._presses.append(key.contents.keycode) + self._keysyms.append(keysym.value) + if count > 0: + self._text += buffer.raw[:count] + + def wait_for(self, count, timeout=10): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + with self.lock: + if len(self._presses) >= count and len(self._releases) >= count: + return True + time.sleep(0.01) + with self.lock: + return len(self._presses) >= count and len(self._releases) >= count + + def counts(self): + with self.lock: + return len(self._presses), len(self._releases) + + def press_count(self): + with self.lock: + return len(self._presses) + + def press_keycodes(self): + with self.lock: + return sorted(self._presses) + + def release_keycodes(self): + with self.lock: + return sorted(self._releases) + + def keysyms(self): + with self.lock: + return list(self._keysyms) + + def text(self): + with self.lock: + raw = self._text + try: + return raw.decode("utf-8") + except UnicodeDecodeError as error: + raise AssertionError("the X11 client derived %r, which is not UTF-8: %s" % (raw, error)) + + def keymap(self): + first = ctypes.c_int(0) + maximum = ctypes.c_int(0) + self.lib.XDisplayKeycodes(self._dpy, ctypes.byref(first), ctypes.byref(maximum)) + count = maximum.value - first.value + 1 + per = ctypes.c_int(0) + symbols = self.lib.XGetKeyboardMapping(self._dpy, first.value, count, ctypes.byref(per)) + if not symbols: + raise RuntimeError("XGetKeyboardMapping returned nothing") + values = [symbols[index] for index in range(count * per.value)] + self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p)) + return (first.value, per.value, values) + + def modifier_codes(self): + """Keycodes the server treats as modifiers; they are never replaceable.""" + mapping = self.lib.XGetModifierMapping(self._dpy) + if not mapping: + return set() + try: + width = mapping.contents.max_keypermod + keys = mapping.contents.modifiermap + return {keys[index] for index in range(8 * width) if keys[index]} + finally: + self.lib.XFreeModifiermap(mapping) + + def pressed_keys(self): + keys = ctypes.create_string_buffer(32) + self.lib.XQueryKeymap(self._dpy, ctypes.cast(keys, ctypes.c_void_p)) + return [index * 8 + bit for index in range(32) for bit in range(8) + if keys.raw[index] >> bit & 1] + + def close(self): + self._stopped.set() + if self._thread is not None: + self._thread.join(5) + self._thread = None + if self._ic: + self.lib.XDestroyIC(ctypes.c_void_p(self._ic)) + self._ic = None + if self._im: + self.lib.XCloseIM(ctypes.c_void_p(self._im)) + self._im = None + if self._dpy: + if getattr(self, "_window", None): + self.lib.XDestroyWindow(self._dpy, self._window) + self.lib.XCloseDisplay(self._dpy) + self._dpy = None + + +class XRoot: + """Publishes the session properties the bridge reads from the main display's root window.""" + + def __init__(self, lib, display): + self.lib = lib + self._dpy = lib.XOpenDisplay(display.encode()) + if not self._dpy: + raise RuntimeError("the test client cannot open X display " + display) + self.root = lib.XDefaultRootWindow(self._dpy) + + def set_string(self, name, value): + data = ctypes.create_string_buffer(value, len(value)) + self.lib.XChangeProperty(self._dpy, self.root, self._atom(name), self._atom(b"STRING"), + 8, PROPERTY_REPLACE, ctypes.cast(data, ctypes.c_void_p), len(value)) + self.lib.XSync(self._dpy, False) + + def set_packed_cardinals(self, name, value): + # gamescope 3.16.29 stores the display string's bytes packed into CARDINALs, little endian. + padded = value + b"\0" * (-len(value) % 4) + words = [int.from_bytes(padded[start:start + 4], "little") for start in range(0, len(padded), 4)] + data = (ctypes.c_ulong * len(words))(*words) + self.lib.XChangeProperty(self._dpy, self.root, self._atom(name), self._atom(b"CARDINAL"), + 32, PROPERTY_REPLACE, ctypes.cast(data, ctypes.c_void_p), len(words)) + self.lib.XSync(self._dpy, False) + + def _atom(self, name): + return self.lib.XInternAtom(self._dpy, name, 0) + + def close(self): + if self._dpy: + self.lib.XCloseDisplay(self._dpy) + self._dpy = None + + +LAUNCHER = ( + "import subprocess, sys, time\n" + "child = subprocess.Popen([sys.executable, sys.argv[1], sys.argv[2]])\n" + "open(sys.argv[3], 'w').write(str(child.pid))\n" + "time.sleep(120)\n" +) + + +@unittest.skipUnless(XVFB, "Xvfb is not installed") +class TextInputTest(unittest.TestCase): + maxDiff = 8000 + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.log = self.dir / "helper.log" + try: + self.lib = libx11() + except OSError as error: + self.fail("libX11 is missing, so no X11 client can check the bridge: %s" % error) + + def start_display(self): + for number in range(90, 140): + path = Path("/tmp/.X11-unix/X%d" % number) + if path.exists(): + continue + process = subprocess.Popen( + [XVFB, ":%d" % number, "-screen", "0", "320x240x24", "-nolisten", "tcp"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(self.stop_display, process) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if path.exists(): + return ":%d" % number + if process.poll() is not None: + break + time.sleep(0.02) + self.fail("no Xvfb display could be started") + + @staticmethod + def stop_display(process): + if process.poll() is not None: + return + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + def consume(self, display): + try: + consumer = XTextConsumer(self.lib, display) + except RuntimeError as error: + self.fail(str(error)) + self.addCleanup(consumer.close) + consumer.start() + return consumer + + def start_helper(self, socket_path, display, game_display=None): + self.assertTrue(HELPER.is_file(), + "the text bridge %s does not exist; the helper never started" % HELPER) + env = dict(os.environ) + env["DISPLAY"] = display + env.pop("STEAM_GAME_DISPLAY_0", None) + if game_display is not None: + env["STEAM_GAME_DISPLAY_0"] = game_display + stream = open(self.log, "wb") + self.addCleanup(stream.close) + process = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)], env=env, + stdin=subprocess.DEVNULL, stdout=stream, stderr=subprocess.STDOUT) + self.addCleanup(self.stop_helper, process) + self.wait_for_socket(process, socket_path) + return process + + @staticmethod + def stop_helper(process): + if process.poll() is not None: + return + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + def wait_for_socket(self, process, socket_path, timeout=10): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if process.poll() is not None: + self.fail("the text bridge exited with %s before serving %s; output: %r" + % (process.returncode, socket_path.name, self.output())) + if self.listening(socket_path): + return + time.sleep(0.02) + self.fail("the text bridge never listened on %s; output: %r" + % (socket_path.name, self.output())) + + @staticmethod + def listening(socket_path): + try: + info = socket_path.lstat() + except OSError: + return False + if not stat.S_ISSOCK(info.st_mode): + return False + probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + probe.settimeout(0.5) + probe.connect(str(socket_path)) + except OSError: + return False + finally: + probe.close() + return True + + def output(self): + try: + return self.log.read_text(errors="replace")[-2000:] + except OSError: + return "" + + def output_bytes(self): + try: + return self.log.read_bytes() + except OSError: + return b"" + + def frame(self, socket_path, payload, timeout=15, shutdown=False): + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.addCleanup(client.close) + client.settimeout(timeout) + client.connect(str(socket_path)) + client.sendall(payload) + if shutdown: + client.shutdown(socket.SHUT_WR) + ack = b"" + while len(ack) < 1: + try: + chunk = client.recv(1) + except socket.timeout: + self.fail("the bridge did not answer within %s seconds" % timeout) + if not chunk: + break + ack += chunk + try: + tail = client.recv(1) + except socket.timeout: + self.fail("the bridge kept the connection open after answering %r" % ack) + self.assertEqual(b"", tail, "the bridge sent more than its one answer") + return ack + + def commit(self, socket_path, text, timeout=15): + payload = text if isinstance(text, bytes) else text.encode() + return self.frame(socket_path, struct.pack(">I", len(payload)) + payload, timeout) + + def test_exact_unicode_reaches_a_real_x11_client(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE), "the bridge did not accept the text") + self.assertTrue(consumer.wait_for(len(SAMPLE)), + "the X11 client saw %d presses and %d releases of the %d key pairs the text needs" + % (consumer.counts() + (len(SAMPLE),))) + self.assertEqual(SAMPLE, consumer.text()) + self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(), + "a key was pressed without its release") + self.stop_helper(process) + self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down") + self.assertEqual(consumer.snapshot, consumer.keymap(), + "the bridge did not restore the keyboard map") + self.assertNotIn(SAMPLE.encode(), self.output_bytes(), "the bridge logged the text it typed") + + def test_adjacent_commits_reach_the_client_in_order(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + for text in ("中文", " ", "abc"): + self.assertEqual(ACK_OK, self.commit(socket_path, text), + "the bridge did not accept %r" % text) + expected = "中文 abc" + self.assertTrue(consumer.wait_for(len(expected)), + "the X11 client saw %d presses and %d releases of the %d key pairs the text needs" + % (consumer.counts() + (len(expected),))) + self.assertEqual(expected, consumer.text()) + self.stop_helper(process) + self.assertEqual(consumer.snapshot, consumer.keymap(), + "the bridge did not restore the keyboard map") + self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down") + + def test_chinese_then_backspace_then_return_are_real_keysyms(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + for text in ("中文", "\b", "\r"): + self.assertEqual(ACK_OK, self.commit(socket_path, text), + "the bridge did not accept %r" % text) + self.assertTrue(consumer.wait_for(4), + "the X11 client saw %d presses and %d releases of the 4 key pairs the text needs" + % consumer.counts()) + self.assertEqual([0x01000000|ord("中"),0x01000000|ord("文"),KEYSYM_BACKSPACE,KEYSYM_RETURN], + consumer.keysyms(), + "the soft controls must reach the client as real keysyms after the text") + self.assertEqual("中文\b\r", consumer.text(), + "Xutf8LookupString is a raw lookup, not an editor; the controls stay literal") + self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(), + "a key was pressed without its release") + self.stop_helper(process) + self.assertEqual(consumer.snapshot, consumer.keymap(), + "the bridge did not restore the keyboard map") + self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down") + + def test_malformed_frames_are_refused_and_the_next_text_still_works(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + frames = { + "invalid utf8": (struct.pack(">I", 2) + b"\xff\xfe", False), + "surrogate": (struct.pack(">I", 3) + b"\xed\xa0\x80", False), + "nul": (struct.pack(">I", 3) + b"a\x00b", False), + "empty text": (struct.pack(">I", 0), False), + "over the size limit": (struct.pack(">I", MAX_TEXT + 1), False), + "little endian length": (struct.pack("I", 10) + b"abc", True), + } + for name, (payload, shutdown) in frames.items(): + with self.subTest(name): + self.assertEqual(ACK_FAILED, self.frame(socket_path, payload, shutdown=shutdown), + "%s must be refused with ACK 0" % name) + time.sleep(0.3) + self.assertEqual(0, consumer.press_count(), "a refused request still injected keys") + self.assertEqual(consumer.snapshot, consumer.keymap(), + "a refused request changed the keyboard map") + self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE)) + self.assertTrue(consumer.wait_for(len(SAMPLE)), + "the bridge stopped serving after refusing a request") + self.assertEqual(SAMPLE, consumer.text()) + self.stop_helper(process) + self.assertEqual([], consumer.pressed_keys()) + self.assertEqual(consumer.snapshot, consumer.keymap()) + + def test_stable_mappings_survive_a_delayed_consumer(self): + display = self.start_display() + try: + consumer = XTextConsumer(self.lib, display) + except RuntimeError as error: + self.fail(str(error)) + self.addCleanup(consumer.close) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + later = "更多" + self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE), + "the bridge did not accept the first frame") + self.assertEqual(ACK_OK, self.commit(socket_path, later), + "the bridge did not accept the second frame") + # Delay event lookup until both commits have been acknowledged. + consumer.start() + expected = SAMPLE + later + self.assertTrue(consumer.wait_for(len(expected)), + "the X11 client saw %d presses and %d releases of the %d key pairs the text needs" + % (consumer.counts() + (len(expected),))) + self.assertEqual(expected, consumer.text(), + "a delayed consumer must read every character exactly once, in order") + self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(), + "a key was pressed without its release") + self.stop_helper(process) + self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down") + self.assertEqual(consumer.snapshot, consumer.keymap(), + "the bridge did not restore the keyboard map") + + def test_a_frame_larger_than_the_empty_keymap_is_refused(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + lowest, width, values = consumer.snapshot + modifiers = consumer.modifier_codes() + empty = 0 + for index in range(len(values) // width): + keycode = lowest + index + if keycode < 8 or keycode > 255 or keycode in modifiers: + continue + if not any(values[index * width:(index + 1) * width]): + empty += 1 + self.assertLessEqual(empty, 248, + "the keycodes 8..255 alone cap every session at 248 slots") + flood = "".join(chr(0x4E00 + offset) for offset in range(empty + 1)) + self.assertEqual(ACK_FAILED, self.commit(socket_path, flood), + "a frame needing more distinct keysyms than empty rows must be refused") + time.sleep(0.5) + self.assertEqual(0, consumer.press_count(), "a refused frame still injected keys") + self.assertEqual(consumer.snapshot, consumer.keymap(), + "a refused frame changed the keyboard map") + self.assertEqual(ACK_OK, self.commit(socket_path, "中文"), + "the refusal consumed the slots it merely measured") + self.assertTrue(consumer.wait_for(2), "the next short text was never typed") + self.assertEqual("中文", consumer.text()) + self.stop_helper(process) + self.assertEqual([], consumer.pressed_keys()) + self.assertEqual(consumer.snapshot, consumer.keymap()) + + def assert_routing(self, publish): + main = self.start_display() + game = self.start_display() + main_consumer = self.consume(main) + game_consumer = self.consume(game) + root = XRoot(self.lib, main) + self.addCleanup(root.close) + publish(root, game.encode()) + socket_path = self.dir / "text-input.sock" + self.start_helper(socket_path, main, game_display=game) + self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE)) + self.assertTrue(game_consumer.wait_for(len(SAMPLE)), + "the display named by %s received no text" % FOCUS_PROPERTY.decode()) + self.assertEqual(SAMPLE, game_consumer.text()) + time.sleep(0.3) + self.assertEqual(0, main_consumer.press_count(), "the text went to both displays") + + def test_two_displays_route_to_the_format8_property(self): + self.assert_routing(lambda root, display: root.set_string(FOCUS_PROPERTY, display)) + + def test_two_displays_route_to_the_gamescope_format32_property(self): + self.assert_routing(lambda root, display: root.set_packed_cardinals(FOCUS_PROPERTY, display)) + + def test_ambiguous_routing_injects_nothing(self): + main = self.start_display() + game = self.start_display() + main_consumer = self.consume(main) + game_consumer = self.consume(game) + root = XRoot(self.lib, main) + self.addCleanup(root.close) + socket_path = self.dir / "text-input.sock" + self.start_helper(socket_path, main, game_display=game) + self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE), + "a missing focus property must not be guessed") + root.set_string(FOCUS_PROPERTY, b":177") + self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE), + "an unknown display must not be used") + root.set_string(FOCUS_PROPERTY, b"\xff\xfe") + self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE), + "unparseable property bytes must not be used") + time.sleep(0.3) + self.assertEqual((0, 0), (main_consumer.press_count(), game_consumer.press_count()), + "a refused route still injected keys") + + def test_sigterm_exits_and_removes_only_its_own_socket(self): + display = self.start_display() + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + foreign = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.addCleanup(foreign.close) + foreign_path = self.dir / "someone-else.sock" + foreign.bind(str(foreign_path)) + process.send_signal(signal.SIGTERM) + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + self.fail("the text bridge ignored SIGTERM") + self.assertFalse(socket_path.exists(), "the bridge left its own socket behind") + self.assertTrue(foreign_path.exists(), "the bridge removed a socket it does not own") + + def test_exits_when_the_session_that_started_it_dies(self): + display = self.start_display() + socket_path = self.dir / "text-input.sock" + self.assertTrue(HELPER.is_file(), + "the text bridge %s does not exist; the helper never started" % HELPER) + pid_file = self.dir / "bridge.pid" + launcher = subprocess.Popen([sys.executable, "-c", LAUNCHER, str(HELPER), str(socket_path), + str(pid_file)], + env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(self.stop_helper, launcher) + pid = 0 + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + text = pid_file.read_text() if pid_file.exists() else "" + if text.strip().isdigit(): + pid = int(text) + break + time.sleep(0.02) + self.assertTrue(pid, "the launching session never reported the bridge pid") + self.addCleanup(self.kill_pid, pid) + self.wait_for_socket(launcher, socket_path) + launcher.kill() + launcher.wait(timeout=10) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline and self.pid_alive(pid): + time.sleep(0.05) + self.assertFalse(self.pid_alive(pid), "the bridge outlived the session that started it") + self.assertFalse(socket_path.exists(), "the bridge left its socket behind") + + def test_a_shutdown_client_during_a_blocked_tap_gets_no_ack(self): + helper = runpy.run_path(str(HELPER)) + bridge_type = helper["XBridge"] + begun = threading.Event() + release = threading.Event() + taps = [] + + class FakeBridge: + type_text = bridge_type.type_text + + def target_display(self): + return ":fake" + + def state(self, name): + return SimpleNamespace(handle=None, codes={ord("a"): 1, ord("b"): 2}) + + def _tap(self, handle, keycode): + taps.append(keycode) + if len(taps) == 1: + begun.set() + release.wait(10) + return True + + server, client = socket.socketpair() + self.addCleanup(server.close) + self.addCleanup(client.close) + worker = threading.Thread(target=helper["serve_connection"], + args=(server, FakeBridge()), daemon=True) + worker.start() + try: + client.sendall(struct.pack(">I", (1 << 31) | 2) + b"ab") + self.assertTrue(begun.wait(10), "the bridge never began the first tap") + client.shutdown(socket.SHUT_WR) + readable, _, _ = select.select([client], [], [], 0.05) + self.assertEqual([], readable, "the bridge answered a client that went away mid-tap") + finally: + release.set() + client.settimeout(10) + self.assertEqual(ACK_FAILED, client.recv(1), + "a client that stopped reading must be told the tap failed") + worker.join(10) + self.assertFalse(worker.is_alive(), "the connection thread did not finish") + self.assertEqual([1], taps, "the bridge kept tapping after the client went away") + + def test_a_stalled_client_does_not_block_the_service(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + self.start_helper(socket_path, display) + stalled = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.addCleanup(stalled.close) + stalled.settimeout(5) + stalled.connect(str(socket_path)) + stalled.sendall(struct.pack(">I", 40)) + started = time.monotonic() + self.assertEqual(ACK_OK, self.commit(socket_path, "中文", timeout=20)) + self.assertLess(time.monotonic() - started, 20) + self.assertTrue(consumer.wait_for(2), "the later request was never typed") + self.assertEqual("中文", consumer.text()) + + def test_sigkill_restart_on_the_same_path_serves_again(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + first = self.start_helper(socket_path, display) + first.send_signal(signal.SIGKILL) + first.wait(timeout=10) + self.start_helper(socket_path, display) + self.assertEqual(ACK_OK, self.commit(socket_path, "重启", timeout=20)) + self.assertTrue(consumer.wait_for(2), "text after a SIGKILL restart was never typed") + self.assertEqual("重启", consumer.text()) + + def test_a_second_helper_leaves_the_live_listener_alone(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + self.start_helper(socket_path, display) + before = socket_path.lstat() + stream = open(self.log, "ab") + self.addCleanup(stream.close) + second = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)], + env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL, + stdout=stream, stderr=subprocess.STDOUT) + self.addCleanup(self.stop_helper, second) + try: + code = second.wait(timeout=15) + except subprocess.TimeoutExpired: + self.fail("a second text bridge kept running next to the live one") + self.assertNotEqual(0, code, "a second text bridge accepted an occupied path") + after = socket_path.lstat() + self.assertEqual((before.st_dev, before.st_ino), (after.st_dev, after.st_ino), + "a second text bridge replaced the live socket") + self.assertEqual(ACK_OK, self.commit(socket_path, "还在", timeout=20)) + self.assertTrue(consumer.wait_for(2), "the live listener stopped typing after a second launch") + self.assertEqual("还在", consumer.text()) + + def test_a_regular_file_at_the_socket_path_is_preserved(self): + display = self.start_display() + socket_path = self.dir / "occupied.sock" + socket_path.write_text("not a socket") + code = self.launch_expecting_failure(socket_path, display) + self.assertNotEqual(0, code, "the text bridge accepted a regular file as its socket") + self.assertEqual("not a socket", socket_path.read_text(), + "the text bridge overwrote a regular file") + + def test_a_symlink_at_the_socket_path_is_preserved(self): + display = self.start_display() + target = self.dir / "target" + target.write_text("keep") + socket_path = self.dir / "link.sock" + socket_path.symlink_to(target) + code = self.launch_expecting_failure(socket_path, display) + self.assertNotEqual(0, code, "the text bridge accepted a symlink as its socket") + self.assertTrue(socket_path.is_symlink(), "the text bridge removed a symlink") + self.assertEqual("keep", target.read_text()) + + def launch_expecting_failure(self, socket_path, display): + stream = open(self.log, "wb") + self.addCleanup(stream.close) + process = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)], + env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL, + stdout=stream, stderr=subprocess.STDOUT) + self.addCleanup(self.stop_helper, process) + try: + return process.wait(timeout=15) + except subprocess.TimeoutExpired: + self.fail("the text bridge kept running on an occupied path") + + @staticmethod + def kill_pid(pid): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + + @staticmethod + def pid_alive(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + try: + state = Path("/proc/%d/stat" % pid).read_text().rsplit(")", 1)[1].split()[0] + except (OSError, IndexError): + return False + return state != "Z" + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_validate_apk.py b/tools/tests/test_validate_apk.py index 707779a9f6..f6afd33718 100644 --- a/tools/tests/test_validate_apk.py +++ b/tools/tests/test_validate_apk.py @@ -28,7 +28,7 @@ class ValidateApkTest(unittest.TestCase): def git(self, *args): return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip() - def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write", fork=False): + def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write", fork=False, tests="success", build_base="a" * 40, tests_base="a" * 40): (self.root / filename).parent.mkdir(parents=True, exist_ok=True) (self.root / filename).write_text(message) self.git("add", filename) @@ -56,7 +56,16 @@ class ValidateApkTest(unittest.TestCase): if path.endswith("/pulls?state=open&head=contributor%3Afix%2Fbranch"): return [pr] if "workflows/build.yml/runs?" in path: - return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", "html_url": "https://example.org/build"}]} + title = f"building pr 1 on {sha}" + (f" against {build_base}" if build_base else "") + return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", + "display_title": title, "html_url": "https://example.org/build"}]} + if "workflows/unit-tests.yml/runs?" in path: + if tests is None: + return {"workflow_runs": []} + title = f"unit tests for pr 1 on {sha}" + (f" against {tests_base}" if tests_base else "") + return {"workflow_runs": [{"id": 9, "head_sha": sha, "html_url": "https://example.org/tests", + "display_title": title, "status": "in_progress" if tests == "pending" else "completed", + "conclusion": None if tests == "pending" else tests}]} if path.endswith("/jobs?per_page=100"): return {"jobs": [{"name": "Compile and test APK", "status": "in_progress" if result == "pending" else "completed", "conclusion": result}]} raise AssertionError(path) @@ -85,6 +94,25 @@ class ValidateApkTest(unittest.TestCase): self.validate(result=result) self.assertEqual(self.statuses[-1]["state"], result) + def test_unit_tests_must_pass_too(self): + for tests, state in (("pending", "pending"), (None, "pending"), ("failure", "failure"), ("cancelled", "failure")): + with self.subTest(tests=tests): + self.validate(tests=tests) + self.assertEqual(self.statuses[-1]["state"], state) + self.assertEqual(self.statuses[-1]["target_url"], "https://example.org/tests") + + def test_successful_runs_must_use_the_same_pr_base(self): + for build_base, tests_base in (("a" * 40, "b" * 40), ("a" * 40, None), (None, "a" * 40)): + with self.subTest(build_base=build_base, tests_base=tests_base): + self.validate(build_base=build_base, tests_base=tests_base) + self.assertEqual(self.statuses[-1]["state"], "pending") + self.assertIn("same main commit", self.statuses[-1]["description"]) + + def test_a_compile_failure_is_reported_before_test_results(self): + self.validate(result="failure", tests="failure") + self.assertEqual(self.statuses[-1]["description"], "APK compilation failed") + self.assertEqual(self.statuses[-1]["target_url"], "https://example.org/build") + def test_superseded_event_cannot_replace_current_status(self): self.validate(stale=True) self.assertEqual(self.statuses, []) diff --git a/tools/tests/test_vk_linear_dmabuf.py b/tools/tests/test_vk_linear_dmabuf.py index 4cbe70ddc4..defa642afa 100644 --- a/tools/tests/test_vk_linear_dmabuf.py +++ b/tools/tests/test_vk_linear_dmabuf.py @@ -15,6 +15,8 @@ SRC = TESTS.parents[1] / "app/src/main/cpp/waylandcomp/src" LAYER_HARNESS = r''' #include #include +#include +#include #include #include "vk_external_image_sync.h" #include "vk_linear_dmabuf.h" @@ -42,6 +44,11 @@ static const uint32_t g_qfam = 2; %(width)s %(height)s static int black_fill_below(const struct draw_list *dl, int n) { (void)dl; (void)n; return 0; } +#define LAYER_CANDIDATE_DIAGNOSTICS 32u +static unsigned g_layer_candidate_diag_count; +static int g_layer_candidate_diag_limit; +static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; } +%(candidate_skip)s %(candidate)s static int candidate(struct vkp_image *img) { @@ -135,6 +142,7 @@ class VkLinearDmabufTest(unittest.TestCase): "is_dmabuf": function(vk, "vkp_image_is_dmabuf"), "width": function(vk, "vkp_image_width"), "height": function(vk, "vkp_image_height"), + "candidate_skip": function(comp, "note_layer_candidate_skip"), "candidate": function(comp, "layer_candidate"), } with tempfile.TemporaryDirectory(prefix="droiddeck-vk-linear-layer-") as tmp: @@ -144,10 +152,11 @@ class VkLinearDmabufTest(unittest.TestCase): def test_layer_import_failure_requests_compositor_fallback(self): source = (SRC / "sc_layer.c").read_text() - for name in ("sc_layer_present", "sc_layer_present_overlay"): - with self.subTest(layer=name): - body = function(source, name) - self.assertRegex(body, r"if \(idx < 0\) \{ log_drop\(l\); return g_alloc_failed \? -1 : 0; \}") + game = function(source, "sc_layer_present") + self.assertRegex(game, r"if \(idx < 0\) \{\s*log_drop\(l\);\s*if \(g_alloc_failed\) return -1;") + self.assertRegex(function(source, "overlay_slot"), + r"if \(\*idx < 0\) \{ log_drop\(l\); return g_alloc_failed \? -1 : 0; \}") + self.assertIn("overlay_slot(", function(source, "sc_layer_present_overlay")) def test_layer_blits_use_the_imported_output_row_pitch(self): source = (SRC / "vk_present.c").read_text() @@ -156,7 +165,7 @@ class VkLinearDmabufTest(unittest.TestCase): self.assertLess(blit.index("VkBufferImageCopy copy = dst->linear_copy"), copy) self.assertLess(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 1"), copy) self.assertGreater(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 0"), copy) - for name in ("vkp_blit_image", "pass_finish"): + for name in ("vkp_blit_images", "pass_finish"): self.assertIn("blit_to_layer(", function(source, name)) diff --git a/tools/tests/test_vk_terminal_callers.py b/tools/tests/test_vk_terminal_callers.py index c1e08bf6d5..c3f7442ef6 100644 --- a/tools/tests/test_vk_terminal_callers.py +++ b/tools/tests/test_vk_terminal_callers.py @@ -117,6 +117,9 @@ int __android_log_print(int, const char *, const char *, ...); def test_blit_wait_error_same_size_pixel_upload(self): self.run_scenario('pixel-wait-error') + def test_layer_copies_share_one_submit_and_wait(self): + self.run_scenario('blit-batched') + def test_lost_device_shm_upload_keeps_cpu_snapshot(self): self.run_scenario('lost-shm-upload') diff --git a/tools/tests/test_wayland_host_order.py b/tools/tests/test_wayland_host_order.py new file mode 100644 index 0000000000..44dc7f3088 --- /dev/null +++ b/tools/tests/test_wayland_host_order.py @@ -0,0 +1,487 @@ +"""Compiled FIFO regression for the native host queue in droiddeck_ext.c.""" + +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +CC = shutil.which("cc") +ROOT = Path(__file__).resolve().parents[2] +SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/droiddeck_ext.c" +HEADER = SOURCE.with_name("droiddeck_ext.h") + +WAYLAND_H = """ +#ifndef STUB_WAYLAND_SERVER_H +#define STUB_WAYLAND_SERVER_H +#include +struct wl_display; +struct wl_event_loop; +struct wl_resource; +struct wl_client; +struct wl_event_source; +#define WL_EVENT_READABLE 1u +struct wl_event_loop *wl_display_get_event_loop(struct wl_display *); +void wl_display_flush_clients(struct wl_display *); +struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *, int, uint32_t, + int (*)(int, uint32_t, void *), void *); +#endif +""" + +ANDROID_H = """ +#ifndef STUB_ANDROID_LOG_H +#define STUB_ANDROID_LOG_H +#define ANDROID_LOG_ERROR 6 +int __android_log_print(int, const char *, const char *, ...); +#endif +""" + +AHB_H = """ +#ifndef STUB_AHB_SWAPCHAIN_H +#define STUB_AHB_SWAPCHAIN_H +void ahb_swapchain_set_mode(int, int); +#endif +""" + +COLOR_H = """ +#ifndef STUB_DROIDDECK_COLOR_H +#define STUB_DROIDDECK_COLOR_H +void droiddeck_color_set_output(int); +#endif +""" + +PROGRAM = """ +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include +#include "android/log.h" +#include "droiddeck_ext.h" +#include "ahb_swapchain.h" +#include "droiddeck_color.h" +#include "droiddeck_ext.c" + +#define CHECK(c) do { if (!(c)) { fprintf(stderr, "check failed at line %d", __LINE__); return 1; } } while (0) + +struct ev { int kind; uint32_t a; int b; char text[64]; }; +static struct ev g_ev[32]; +static int g_n; +static int g_native_key_down[KEY_CNT]; +static uint32_t g_pending_raw_release; +static int g_display_stub; +static int g_loop_stub; +static int g_fallback_accept; +static int g_fallback_token; +static int g_hdr_count; + +int text_input_host_commit(const char *u, size_t n) +{ + struct ev *e; + if (n == 3 && memcmp(u, "x11", 3) == 0) + return 0; + if (g_n >= 32 || n >= sizeof(g_ev[0].text)) + return 0; + e = &g_ev[g_n++]; + e->kind = 1; + e->a = (uint32_t)n; + memcpy(e->text, u, n); + e->text[n] = 0; + return 1; +} + +void text_input_host_preedit(const char *u, size_t n, int a, int b) +{ + (void)u; (void)n; (void)a; (void)b; +} + +void text_input_host_delete(int a, int b) { (void)a; (void)b; } +void clipboard_host_text(char *u, size_t n) { (void)n; free(u); } +int droiddeck_on_text_input_fallback(const char *u, int n, int token) +{ + if (!g_fallback_accept) return 0; + if (n == 3 && memcmp(u, "x11", 3) == 0) { + g_fallback_token = token; + return 1; + } + g_fallback_token = token; + return 1; +} + +int droiddeck_key_is_down(uint32_t k) +{ + return k < KEY_CNT && g_native_key_down[k]; +} + +void droiddeck_inject_key(uint32_t k, int s) +{ + if (k < KEY_CNT) + g_native_key_down[k] = s; + if (g_n < 32) { + g_ev[g_n].kind = 2; + g_ev[g_n].a = k; + g_ev[g_n].b = s; + g_ev[g_n].text[0] = 0; + g_n++; + } +} + +void droiddeck_dispatch_pending_input(void) +{ + if (!g_pending_raw_release) return; + droiddeck_inject_key(g_pending_raw_release, 0); + g_pending_raw_release = 0; +} + +void clipboard_init(struct wl_display *d) { (void)d; } +void text_input_init(struct wl_display *d) { (void)d; } +void toplevel_icon_init(struct wl_display *d) { (void)d; } +void single_pixel_init(struct wl_display *d) { (void)d; } +void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; } +void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; } + +struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; } +void wl_display_flush_clients(struct wl_display *d) { (void)d; } + +struct wl_event_loop *wl_display_get_event_loop(struct wl_display *d) +{ + (void)d; + return (struct wl_event_loop *)&g_loop_stub; +} + +struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, + uint32_t m, int (*f)(int, uint32_t, void *), void *d) +{ + (void)l; (void)fd; (void)m; (void)f; (void)d; + return NULL; +} + +void droiddeck_log(const char *t, const char *f, ...) { (void)t; (void)f; } + +int __android_log_print(int p, const char *t, const char *f, ...) +{ + (void)p; (void)t; (void)f; + return 0; +} + +int main(void) +{ + int saved; + CHECK(pipe2(g_wake, O_CLOEXEC | O_NONBLOCK) == 0); + droiddeck_host_text_commit("中文", (int)strlen("中文")); + droiddeck_host_key(28, 1); + droiddeck_host_key(28, 0); + droiddeck_host_text_commit("日本語", (int)strlen("日本語")); + droiddeck_host_key(14, 1); + droiddeck_host_key(14, 0); + droiddeck_host_key(111, 1); + droiddeck_host_key(111, 0); + droiddeck_host_key(15, 1); + droiddeck_host_key(15, 0); + CHECK(g_n == 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 10); + CHECK(g_ev[0].kind == 1 && strcmp(g_ev[0].text, "中文") == 0); + CHECK(g_ev[1].kind == 2 && g_ev[1].a == 28u && g_ev[1].b == 1); + CHECK(g_ev[2].kind == 2 && g_ev[2].a == 28u && g_ev[2].b == 0); + CHECK(g_ev[3].kind == 1 && strcmp(g_ev[3].text, "日本語") == 0); + CHECK(g_ev[4].kind == 2 && g_ev[4].a == 14u && g_ev[4].b == 1); + CHECK(g_ev[5].kind == 2 && g_ev[5].a == 14u && g_ev[5].b == 0); + CHECK(g_ev[6].kind == 2 && g_ev[6].a == 111u && g_ev[6].b == 1); + CHECK(g_ev[7].kind == 2 && g_ev[7].a == 111u && g_ev[7].b == 0); + CHECK(g_ev[8].kind == 2 && g_ev[8].a == 15u && g_ev[8].b == 1); + CHECK(g_ev[9].kind == 2 && g_ev[9].a == 15u && g_ev[9].b == 0); + saved = g_n; + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved); + droiddeck_host_text_commit("尾", (int)strlen("尾")); + droiddeck_host_key(16, 1); + droiddeck_host_key(16, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 3); + CHECK(g_ev[saved].kind == 1 && strcmp(g_ev[saved].text, "尾") == 0); + CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 16u && g_ev[saved + 1].b == 1); + CHECK(g_ev[saved + 2].kind == 2 && g_ev[saved + 2].a == 16u && g_ev[saved + 2].b == 0); + CHECK(g_head == NULL && g_tail == NULL); + saved = g_n; + g_fallback_accept = 1; + droiddeck_host_text_commit("x11", 3); + droiddeck_host_key(29, 1); + droiddeck_host_key(28, 1); + droiddeck_host_key(28, 0); + droiddeck_host_key(29, 0); + droiddeck_host_text_commit("later", 5); + droiddeck_host_hdr_output(1); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved); + CHECK(g_hdr_count == 1); + CHECK(g_fallback_token > 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token + 1, DROIDDECK_TEXT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved); + droiddeck_host_key(30, 1); + droiddeck_host_key(30, 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 7); + CHECK(g_ev[saved].kind == 2 && g_ev[saved].a == 29u && g_ev[saved].b == 1); + CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 28u && g_ev[saved + 1].b == 1); + CHECK(g_ev[saved + 2].kind == 2 && g_ev[saved + 2].a == 28u && g_ev[saved + 2].b == 0); + CHECK(g_ev[saved + 3].kind == 2 && g_ev[saved + 3].a == 29u && g_ev[saved + 3].b == 0); + CHECK(g_ev[saved + 4].kind == 1 && strcmp(g_ev[saved + 4].text, "later") == 0); + CHECK(g_ev[saved + 5].kind == 2 && g_ev[saved + 5].a == 30u && g_ev[saved + 5].b == 1); + CHECK(g_ev[saved + 6].kind == 2 && g_ev[saved + 6].a == 30u && g_ev[saved + 6].b == 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 7); + g_fallback_accept = 0; + droiddeck_host_text_commit("x11", 3); + droiddeck_host_key(31, 1); + droiddeck_host_key(31, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 9); + CHECK(g_ev[saved + 7].kind == 2 && g_ev[saved + 7].a == 31u && g_ev[saved + 7].b == 1); + CHECK(g_ev[saved + 8].kind == 2 && g_ev[saved + 8].a == 31u && g_ev[saved + 8].b == 0); + CHECK(g_head == NULL && g_tail == NULL); + g_n = saved = 0; + g_fallback_accept = 1; + droiddeck_host_key(29, 1); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 1); + CHECK(g_ev[saved].kind == 2 && g_ev[saved].a == 29u && g_ev[saved].b == 1); + droiddeck_host_text_commit("x11", 3); + droiddeck_host_select_game_field(0); + droiddeck_host_text_commit("discard", 7); + droiddeck_host_key(29, 0); + droiddeck_host_key(32, 1); + droiddeck_host_key(32, 0); + droiddeck_host_hdr_output(0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 1); + CHECK(g_hdr_count == 2); + CHECK(g_fallback_token > 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 2); + CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 29u && g_ev[saved + 1].b == 0); + droiddeck_host_text_commit("held", 4); + droiddeck_host_key(33, 1); + droiddeck_host_key(33, 0); + droiddeck_host_key(34, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 2); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + droiddeck_host_text_commit("resume", 6); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 14); + CHECK(g_ev[saved + 2].a == KEY_LEFTCTRL && g_ev[saved + 2].b == 1); + CHECK(g_ev[saved + 3].a == KEY_A && g_ev[saved + 3].b == 1); + CHECK(g_ev[saved + 5].a == KEY_LEFTCTRL && g_ev[saved + 5].b == 0); + CHECK(g_ev[saved + 6].kind == 1 && strcmp(g_ev[saved + 6].text, "discard") == 0); + CHECK(g_ev[saved + 7].a == 32u && g_ev[saved + 7].b == 1); + CHECK(g_ev[saved + 9].kind == 1 && strcmp(g_ev[saved + 9].text, "held") == 0); + CHECK(g_ev[saved + 13].kind == 1 && strcmp(g_ev[saved + 13].text, "resume") == 0); + CHECK(g_head == NULL && g_tail == NULL); + for (int pending = 0; pending <= 1; ++pending) { + g_n = 0; + droiddeck_inject_key(KEY_LEFTCTRL, 1); + if (pending) + droiddeck_host_text_commit("x11", 3); + droiddeck_host_select_game_field(0); + droiddeck_host_text_commit("body", 4); + if (pending) { + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 1); + } + droiddeck_inject_key(KEY_LEFTCTRL, 0); + if (pending) + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 7); + CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_LEFTCTRL && g_ev[2].b == 1); + CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_A && g_ev[3].b == 1); + CHECK(g_ev[4].kind == 2 && g_ev[4].a == KEY_A && g_ev[4].b == 0); + CHECK(g_ev[5].kind == 2 && g_ev[5].a == KEY_LEFTCTRL && g_ev[5].b == 0); + CHECK(g_ev[6].kind == 1 && strcmp(g_ev[6].text, "body") == 0); + CHECK(!droiddeck_key_is_down(KEY_LEFTCTRL)); + CHECK(g_head == NULL && g_tail == NULL); + } + + g_n = 0; + droiddeck_inject_key(KEY_RIGHTCTRL, 1); + droiddeck_host_select_game_field(1); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 5); + CHECK(g_ev[1].kind == 2 && g_ev[1].a == KEY_A && g_ev[1].b == 1); + CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_A && g_ev[2].b == 0); + CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_C && g_ev[3].b == 1); + CHECK(g_ev[4].kind == 2 && g_ev[4].a == KEY_C && g_ev[4].b == 0); + CHECK(droiddeck_key_is_down(KEY_RIGHTCTRL)); + droiddeck_inject_key(KEY_RIGHTCTRL, 0); + CHECK(g_head == NULL && g_tail == NULL); + + for (int copy = 0; copy <= 1; ++copy) { + uint32_t key = copy ? KEY_C : KEY_A; + g_n = 0; + droiddeck_inject_key(key, 1); + g_pending_raw_release = key; + droiddeck_host_select_game_field(copy); + droiddeck_host_text_commit("body", 4); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_pending_raw_release == 0); + CHECK(g_n == (copy ? 9 : 7)); + CHECK(g_ev[1].kind == 2 && g_ev[1].a == key && g_ev[1].b == 0); + CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_LEFTCTRL && g_ev[2].b == 1); + CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_A && g_ev[3].b == 1); + if (copy) CHECK(g_ev[5].kind == 2 && g_ev[5].a == KEY_C && g_ev[5].b == 1); + CHECK(g_ev[g_n - 1].kind == 1 && strcmp(g_ev[g_n - 1].text, "body") == 0); + CHECK(!droiddeck_key_is_down(key)); + } + + for (int held = 0; held <= 1; ++held) { + g_n = 0; + if (held) { + droiddeck_host_key(KEY_ENTER, 1); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(droiddeck_key_is_down(KEY_ENTER)); + g_n = 0; + } + droiddeck_host_text_commit("x11", 3); + droiddeck_host_key(KEY_LEFTCTRL, 1); + if (!held) droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + droiddeck_host_key(KEY_KPENTER, 1); + droiddeck_host_key(KEY_KPENTER, 0); + droiddeck_host_text_commit("\\r", 1); + droiddeck_host_key(KEY_LEFTCTRL, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 0); + droiddeck_host_text_commit("later", 5); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == (held ? 6 : 5)); + CHECK(g_ev[0].a == KEY_LEFTCTRL && g_ev[0].b == 1); + if (held) CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 0); + CHECK(g_ev[g_n - 4].a == KEY_LEFTCTRL && g_ev[g_n - 4].b == 0); + CHECK(g_ev[g_n - 3].kind == 1 && strcmp(g_ev[g_n - 3].text, "later") == 0); + CHECK(g_ev[g_n - 2].a == KEY_ENTER && g_ev[g_n - 2].b == 1); + CHECK(g_ev[g_n - 1].a == KEY_ENTER && g_ev[g_n - 1].b == 0); + CHECK(!droiddeck_key_is_down(KEY_ENTER) && !droiddeck_key_is_down(KEY_LEFTCTRL)); + } + + g_n = 0; + droiddeck_host_text_commit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 2 && g_ev[0].a == KEY_ENTER && g_ev[0].b == 1 && g_ev[1].b == 0); + + g_n = 0; + droiddeck_host_text_commit_and_submit("wayland", 7); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 3 && g_ev[0].kind == 1 && strcmp(g_ev[0].text, "wayland") == 0); + CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1); + CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0); + + for (int result = DROIDDECK_TEXT_NOT_DELIVERED; result <= DROIDDECK_TEXT_DELIVERED; ++result) { + g_n = 0; + droiddeck_host_text_commit_and_submit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 0); + droiddeck_host_text_commit("later", 5); + droiddeck_host_text_input_fallback_complete(g_fallback_token, result); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == (result == DROIDDECK_TEXT_DELIVERED ? 3 : 1)); + if (result == DROIDDECK_TEXT_DELIVERED) { + CHECK(g_ev[0].a == KEY_ENTER && g_ev[0].b == 1); + CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 0); + } + CHECK(g_ev[g_n - 1].kind == 1 && strcmp(g_ev[g_n - 1].text, "later") == 0); + } + + g_n = 0; + g_fallback_accept = 0; + droiddeck_host_text_commit_and_submit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 0); + droiddeck_host_text_commit("next", 4); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 3 && g_ev[0].kind == 1 && strcmp(g_ev[0].text, "next") == 0); + CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1); + CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0); + + g_n = 0; + g_fallback_accept = 1; + droiddeck_host_key(KEY_LEFTCTRL, 1); + droiddeck_host_text_commit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED); + droiddeck_host_key(KEY_LEFTCTRL, 0); + droiddeck_host_key(KEY_ENTER, 1); + for (int i = 0; i <= DROIDDECK_TEXT_DEFERRED_LIMIT; i++) + droiddeck_host_text_commit("queued", 6); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 2 && !droiddeck_key_is_down(KEY_LEFTCTRL)); + CHECK(g_deferred_overflow && !g_deferred_head && !g_deferred_count && !g_deferred_bytes); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 4 && !droiddeck_key_is_down(KEY_ENTER)); + + g_n = 0; + droiddeck_host_text_commit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_text_commit("\\r", 1); + droiddeck_host_text_commit("next", 4); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0 && g_n == 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0 && g_n == 3); + CHECK(g_ev[0].kind == 1 && strcmp(g_ev[0].text, "next") == 0); + CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1); + CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0); + + close(g_wake[0]); + close(g_wake[1]); + return 0; +} +""" + +@unittest.skipUnless(sys.platform.startswith("linux"), "requires Linux pipe2") +@unittest.skipUnless(CC, "requires cc") +class WaylandHostOrderTest(unittest.TestCase): + def test_fifo_order(self): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / "android").mkdir() + (tmp / "android/log.h").write_text(ANDROID_H) + (tmp / "wayland-server.h").write_text(WAYLAND_H) + (tmp / "ahb_swapchain.h").write_text(AHB_H) + (tmp / "droiddeck_color.h").write_text(COLOR_H) + shutil.copyfile(SOURCE, tmp / "droiddeck_ext.c") + shutil.copyfile(HEADER, tmp / "droiddeck_ext.h") + (tmp / "program.c").write_text(PROGRAM, encoding="utf-8") + subprocess.run([CC, "-std=c11", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-parameter", "-pthread", "-I", str(tmp), + "-o", str(tmp / "probe"), str(tmp / "program.c")], + cwd=tmp, check=True, timeout=30) + subprocess.run([str(tmp / "probe")], cwd=tmp, check=True, timeout=10) + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_windows_vr_build.py b/tools/tests/test_windows_vr_build.py index fa51a169ac..56da16b422 100644 --- a/tools/tests/test_windows_vr_build.py +++ b/tools/tests/test_windows_vr_build.py @@ -122,6 +122,60 @@ class WindowsVrBuildTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'configuration differs'): self.validate() + def test_build_image_selection_and_platform_validation(self): + outputs = vr.read_outputs(self.out, self.root) + cases = [ + ('cached_amd64', vr.IMAGE, [(0, 'sha256:cached linux/amd64\n')], False, 'sha256:cached', None), + ('missing_default', vr.IMAGE, [(1, ''), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None), + ('default_arm64', vr.IMAGE, [(0, 'sha256:old linux/arm64\n'), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None), + ('default_windows', vr.IMAGE, [(0, 'sha256:old windows/amd64\n'), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None), + ('custom_arm64', 'custom:vr', [(0, 'sha256:custom linux/arm64\n')], False, None, r'linux/amd64.*custom:vr'), + ('rebuild_still_arm64', vr.IMAGE, [(0, 'sha256:old linux/arm64\n'), (0, 'sha256:bad linux/arm64\n')], True, None, r'linux/amd64'), + ] + for name, image, inspects, expect_build, expected_id, err in cases: + with self.subTest(name=name): + calls, queue = [], list(inspects) + def fake_run(cmd, **kw): + calls.append(cmd) + if cmd[1:3] == ['image', 'inspect']: + rc, out = queue.pop(0) + return vr.subprocess.CompletedProcess(cmd, rc, stdout=out, stderr='') + return vr.subprocess.CompletedProcess(cmd, 0, stdout='linux\n', stderr='') + with mock.patch.object(vr.shutil, 'which', return_value='docker'), \ + mock.patch.object(vr.subprocess, 'run', side_effect=fake_run), \ + mock.patch.object(vr.subprocess, 'check_output', return_value=b'sha256:legacy\n'), \ + mock.patch.object(vr, 'read_outputs', return_value=outputs) as m_read, \ + mock.patch.object(vr, 'validate', return_value=(outputs, self.manifest)) as m_val: + if err: + with self.assertRaisesRegex(ValueError, err): + vr.build(self.out, self.include, self.root, image=image) + m_read.assert_not_called() + m_val.assert_not_called() + else: + self.assertEqual(vr.build(self.out, self.include, self.root, image=image), (outputs, self.manifest)) + m_read.assert_called_once() + m_val.assert_called_once_with(self.out, self.include, self.root) + inspect_cmds = [c for c in calls if c[1:3] == ['image', 'inspect']] + build_cmds = [c for c in calls if c[1] == 'build'] + run_cmds = [c for c in calls if c[1] == 'run'] + self.assertEqual(len(inspect_cmds), len(inspects)) + for c in inspect_cmds: + self.assertEqual(c[:5], ['docker', 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}']) + if expect_build: + self.assertEqual(len(build_cmds), 1) + self.assertEqual(build_cmds[0][:6], ['docker', 'build', '--platform', 'linux/amd64', '--tag', image]) + else: + self.assertEqual(build_cmds, []) + if expected_id: + self.assertEqual(len(run_cmds), 1) + self.assertIn(expected_id, run_cmds[0]) + self.assertNotIn(image, run_cmds[0]) + self.assertTrue(all('linux/amd64' not in a or a == 'linux/amd64' for a in run_cmds[0])) + manifest = json.loads((self.out / vr.MANIFEST).read_text(encoding='utf-8')) + self.assertEqual(manifest['compiler_image'], expected_id) + else: + self.assertEqual(run_cmds, []) + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_xbox_build_source.py b/tools/tests/test_xbox_build_source.py index 427cea3425..7a3ba0030e 100644 --- a/tools/tests/test_xbox_build_source.py +++ b/tools/tests/test_xbox_build_source.py @@ -11,8 +11,10 @@ class XboxBuildSourceTest(unittest.TestCase): import yaml except ImportError: self.fail('PyYAML is required to execute workflow steps') - workflow = yaml.safe_load((Path(__file__).resolve().parents[2] / '.github/workflows/build.yml').read_text()) - jobs = workflow['jobs'] + workflows = Path(__file__).resolve().parents[2] / '.github/workflows' + jobs = yaml.safe_load((workflows / 'build.yml').read_text())['jobs'] + unit_jobs = yaml.safe_load((workflows / 'unit-tests.yml').read_text())['jobs'] + jobs.update(unit_jobs) step = lambda job, name: next(s['run'] for s in jobs[job]['steps'] if s.get('name') == name) with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -31,13 +33,17 @@ class XboxBuildSourceTest(unittest.TestCase): git('switch', '-q', 'main') (root / 'backend').write_text('merged backend') git('commit', '-qam', 'backend changed after branch') - for name in ('source', 'xbox', 'components', 'apk', 'tests', 'dispatch'): + event_base = git('rev-parse', 'HEAD') + for name in ('source', 'xbox', 'components', 'apk', 'tests', 'unit-tests', 'dispatch'): git('clone', '-q', str(root), str(root / name)) git('checkout', '-q', head, cwd=root / name) output = root / 'output' - env['GITHUB_OUTPUT'] = str(output) + env.update(GITHUB_OUTPUT=str(output), PR_BASE_SHA=event_base) + (root / 'backend').write_text('newer main, after PR event') + git('commit', '-qam', 'main advanced before source pinning') subprocess.run(['bash', '-c', step('source', 'Pin and merge the APK source')], cwd=root / 'source', env=env, check=True, capture_output=True) base = output.read_text().strip().split('=', 1)[1] + self.assertEqual(base, event_base) tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'source') (root / 'backend').write_text('newer main, after backend build') git('commit', '-qam', 'main advanced again') @@ -51,6 +57,10 @@ class XboxBuildSourceTest(unittest.TestCase): subprocess.run(['bash', '-c', step('python-tests', 'Verify backend and test source match')], cwd=root / 'tests', env=env, check=True, capture_output=True) self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'tests'), tree) + subprocess.run(['bash', '-c', step('unit-tests', 'Merge the pinned APK base')], cwd=root / 'unit-tests', env=env, check=True, capture_output=True) + self.assertEqual((root / 'unit-tests/backend').read_text(), 'merged backend') + self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'unit-tests'), tree) + env['SOURCE_TREE'] = tree for job in ('xbox', 'components'): subprocess.run(['bash', '-c', step(job, 'Merge the pinned APK base')], cwd=root / job, env=env, check=True, capture_output=True) diff --git a/tools/tests/test_xbox_launch.py b/tools/tests/test_xbox_launch.py index be2851fd31..c866a4683d 100644 --- a/tools/tests/test_xbox_launch.py +++ b/tools/tests/test_xbox_launch.py @@ -198,6 +198,72 @@ class XboxLaunchTest(unittest.TestCase): self.assertEqual(command[:4], ['/selected/proton', 'run', 'msiexec', '/i']) self.assertTrue(command[4].startswith('Z:') and command[4].endswith('GameInputRedist.msi')) self.assertEqual(command[5:], ['/quiet']) + # The Xbox store accepts the file name in any case. + (game / 'MicrosoftGame.config').rename(game / 'microsoftgame.config') + self.assertEqual(xbox['game_config'](str(game / 'Emu.exe')), game / 'microsoftgame.config') + # A manifest that does not parse gives way to one in a parent folder, as in droiddeck-game-env. + (game / 'Sub').mkdir() + (game / 'Sub' / 'microsoftgame.config').write_text('Installers' + '' + '') + (game / 'MicrosoftGame.config').write_text( + '' + '%s' % actions) + # A fresh prefix: the redistributable installs, and its class goes even before Wine writes system.reg. + (prefix / 'system.reg').write_text('WINE REGISTRY Version 2\n') + # The installers run without the emulator's switches and with FEX's full ordering and precision. + game_env = {'A': '1', 'WINE_SPECIAL_APC_INTERRUPT': '1', 'VKD3D_PACKED_422': '1', 'FEX_LOOPSUSPENDCHECK': '1', + 'FEX_VECTORTSOENABLED': '0', 'FEX_X87REDUCEDPRECISION': '1'} + installer_env = {'A': '1', 'FEX_TSOENABLED': '1', 'FEX_VECTORTSOENABLED': '1', 'FEX_MEMCPYSETTSOENABLED': '1', + 'FEX_HALFBARRIERTSOENABLED': '1', 'FEX_X87REDUCEDPRECISION': '0'} + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), game_env) + self.assertEqual([call.args[0][:3] for call in child.call_args_list], + [['/p', 'run', 'msiexec'], ['/p', 'run', 'msiexec'], ['/p', 'run', 'reg.exe']]) + self.assertTrue(child.call_args_list[0].args[0][4].endswith('GameInputRedist.msi')) + self.assertEqual(child.call_args_list[2].args[0][3:], delete) + self.assertEqual([call.kwargs['env'] for call in child.call_args_list], [installer_env] * 3) + self.assertEqual(game_env['FEX_X87REDUCEDPRECISION'], '1') + # After the install action: a key reg.exe does not find stays quiet, a reg.exe that never answers is reported. + for outcome, reported in (({'return_value': subprocess.CompletedProcess([], 1)}, False), + ({'side_effect': subprocess.TimeoutExpired('reg.exe', 90)}, True), + ({'side_effect': FileNotFoundError(2, 'No such file or directory')}, True)): + with patch('subprocess.run', **outcome), patch('sys.stderr', new_callable=io.StringIO) as err: + xbox['remove_gameinput_service']('/p', prefix, {}, installed=True) + self.assertEqual('could not be removed' in err.getvalue(), reported, outcome) + # Installed earlier and the class is gone: nothing runs. + with patch('subprocess.run') as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + child.assert_not_called() + # A prefix where the redistributable ran before: only the class is removed. + (prefix / 'system.reg').write_text('WINE REGISTRY Version 2\n\n' + key + '@="GameInputService"\n\n') + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + self.assertEqual([call.args[0][2:] for call in child.call_args_list], [['reg.exe'] + delete]) + with patch('subprocess.run', side_effect=subprocess.TimeoutExpired('reg.exe', 90)), \ + patch('sys.stderr', new_callable=io.StringIO) as err: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + self.assertIn('could not be removed', err.getvalue()) + # Other packages keep the class. + (game / 'MicrosoftGame.config').write_text( + '%s' % actions) + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix / 'other', str(game / 'Emu.exe'), {'FEX_X87REDUCEDPRECISION': '1'}) + self.assertEqual([call.args[0][2] for call in child.call_args_list], ['msiexec', 'msiexec']) + self.assertEqual(child.call_args.kwargs['env'], {'FEX_X87REDUCEDPRECISION': '1'}) def test_a_failed_install_action_is_retried_on_the_next_launch(self): with tempfile.TemporaryDirectory() as root: diff --git a/tools/tests/test_zero_copy_acquire_fence.py b/tools/tests/test_zero_copy_acquire_fence.py new file mode 100644 index 0000000000..8b4259661c --- /dev/null +++ b/tools/tests/test_zero_copy_acquire_fence.py @@ -0,0 +1,170 @@ +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +from test_vk_pending_completion import function + +ROOT = Path(__file__).resolve().parents[2] +SRC = ROOT / 'app/src/main/cpp/waylandcomp/src' + +HARNESS = r''' +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); }; +struct wl_event_source; +struct wl_client; +struct wl_resource; +struct surface { int unused; }; +struct vkp_draw { int unused; }; +struct dmabuf_buffer { int fd; void *slot; }; +typedef struct AHardwareBuffer { int unused; } AHardwareBuffer; +DEFINES +STRUCT +static unsigned g_stat_zero_copy; +static int g_export_failed_logged; +static struct surface *g_announced; +static volatile int64_t g_last_zero_copy_ns; +static int explicit_proof; +static int export_ok, exports, presents, presented_acquire, logs, polls; +static int fake_ioctl(int fd, unsigned long req, void *arg) { + struct droiddeck_dma_buf_sync_file *f = arg; + (void)fd; + assert(req == DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE && f->flags == DROIDDECK_DMA_BUF_SYNC_READ); + ++exports; + if (!export_ok) { errno = ENOTTY; return -1; } + f->fd = dup(0); + return 0; +} +#define ioctl fake_ioctl +static int fake_poll(struct pollfd *p, nfds_t n, int timeout) { + assert(n == 1 && p->events == POLLIN && timeout == 100); + ++polls; p->revents = POLLIN; return 1; +} +#define poll fake_poll +static int64_t now_ns(void) { return 1; } +static void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b) { return &b->slot; } +static int droiddeck_dmabuf_fd(struct dmabuf_buffer *b) { return b->fd; } +static int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b) { + assert(s && b); + if (explicit_proof != 1) return explicit_proof ? -2 : -1; + int fd = dup(0); + assert(fd >= 0); + return fd; +} +static const void *droiddeck_surface_color(struct surface *s) { (void)s; return NULL; } +static void droiddeck_surface_describe(struct surface *s, char *out, size_t n) { (void)s; snprintf(out, n, "game"); } +static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; ++logs; } +static int sc_layer_present_ahb(AHardwareBuffer *a, int w, int h, int acquire, void *token, int sw, int sh, + const struct vkp_draw *d, const void *color, uint32_t format) { + (void)a; (void)w; (void)h; (void)token; (void)sw; (void)sh; (void)d; (void)color; (void)format; + ++presents; presented_acquire = acquire; + if (acquire >= 0) close(acquire); + return 0; +} +FUNCTIONS +static void run(int fd, int can_export, int copyable) { + struct dmabuf_buffer b = {.fd = fd}; + struct vkp_draw d; + const struct vkp_draw *draw = copyable ? &d : NULL; + struct ahb_buf ab; + struct surface s; + memset(&ab, 0, sizeof(ab)); + ab.id = 7; ab.w = 64; ab.h = 64; ab.fence_fd = -1; + b.slot = &ab; + export_ok = can_export; + int r = ahb_swapchain_present(&b, &s, 64, 64, draw); + if (explicit_proof) { + assert(exports == 0 && polls == 0); + if (explicit_proof == 1) { + assert(r == 0 && presents == 1 && presented_acquire >= 0 && ab.on_layer); + assert(fcntl(presented_acquire, F_GETFD) == -1 && errno == EBADF); + } else { + assert(r == -1 && presents == 0 && !ab.on_layer); + } + } else if (fd >= 0 && can_export) { + assert(r == 0 && presents == 1 && presented_acquire >= 0 && ab.on_layer && g_stat_zero_copy == 1 && polls == 0); + } else if (copyable) { + assert(r == -1 && presents == 0 && !ab.on_layer && g_stat_zero_copy == 0 && polls == (fd >= 0)); + r = ahb_swapchain_present(&b, &s, 64, 64, draw); + assert(r == -1 && presents == 0 && logs == 1); + } else { + assert(r == 0 && presents == 1 && presented_acquire == -1 && ab.on_layer && polls == (fd >= 0)); + } +} +int main(int argc, char **argv) { + assert(argc == 5); + explicit_proof = atoi(argv[4]); + run(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])); + return 0; +} +''' + + +class ZeroCopyAcquireFenceTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cc = shutil.which(os.environ.get('CC', 'cc')) + if not cc: + raise AssertionError('C compiler required') + ahb = (SRC / 'ahb_swapchain.c').read_text() + defines = '\n'.join(re.findall(r'^(?:struct droiddeck_dma_buf_sync_file \{.*?\};|#define DROIDDECK_DMA_BUF_\w+ .*)$', + ahb, re.M)) + struct = re.search(r'struct ahb_buf \{.*?\n\};', ahb, re.S).group() + source = HARNESS.replace('DEFINES', defines).replace('STRUCT', struct) + source = source.replace('FUNCTIONS', function(ahb, 'ahb_swapchain_present')) + cls.tmp = tempfile.TemporaryDirectory(prefix='droiddeck-acquire-fence-') + cls.addClassCleanup(cls.tmp.cleanup) + probe = Path(cls.tmp.name) / 'probe.c' + probe.write_text(source) + cls.binary = probe.with_suffix('') + built = subprocess.run([cc, '-std=c11', '-Wall', '-Wextra', '-Werror', '-Wno-unused-function', '-UNDEBUG', + '-include', 'stdio.h', '-I', str(SRC.parent / 'prebuilt/include'), str(probe), + '-o', str(cls.binary)], + capture_output=True, text=True) + if built.returncode: + raise AssertionError(built.stdout + built.stderr) + + def scenario(self, fd, can_export, copyable=1, explicit_proof=0): + result = subprocess.run([str(self.binary), str(fd), str(can_export), str(copyable), str(explicit_proof)], capture_output=True, text=True, + timeout=10) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_explicit_fence_goes_to_display_without_dmabuf_ioctl(self): + self.scenario(5, 0, explicit_proof=1) + + def test_failed_explicit_dup_never_falls_through_to_legacy(self): + self.scenario(5, 1, explicit_proof=2) + self.scenario(5, 0, copyable=0, explicit_proof=2) + + def test_exported_fence_goes_to_the_display(self): + self.scenario(5, 1) + + def test_kernel_without_fence_export_falls_back_to_copy(self): + self.scenario(5, 0) + + def test_buffer_without_dmabuf_fd_falls_back_to_copy(self): + self.scenario(-1, 1) + + def test_uncopyable_buffer_waits_on_the_cpu_and_stays_on_the_layer(self): + self.scenario(5, 0, 0) + + def test_uncopyable_buffer_without_dmabuf_fd_stays_on_the_layer(self): + self.scenario(-1, 1, 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_zero_copy_release_at_latch.py b/tools/tests/test_zero_copy_release_at_latch.py index 6d57d48897..e72a0bbabb 100644 --- a/tools/tests/test_zero_copy_release_at_latch.py +++ b/tools/tests/test_zero_copy_release_at_latch.py @@ -35,13 +35,21 @@ STRUCT static struct wl_list g_bufs; static struct wl_event_loop *g_loop; static int g_import_failed_logged; -static int import_ok, imports, imported_flags, deferred_releases, frees, sources; -static struct wl_event_source g_source; +static int import_ok, imports, imported_flags, deferred_releases, frees, sources, removes, merge_ok, merges; +static struct wl_event_source g_sources[4]; +static struct wl_event_source *g_removed; void wl_list_init(struct wl_list *l) { l->prev = l; l->next = l; } void wl_list_insert(struct wl_list *l, struct wl_list *e) { e->next = l->next; e->prev = l; l->next->prev = e; l->next = e; } static int fake_ioctl(int fd, unsigned long req, void *arg) { + if (req == SYNC_IOC_MERGE) { + struct sync_merge_data *m = arg; + assert(fd >= 0 && m->fd2 >= 0 && fd != m->fd2); + ++merges; + if (!merge_ok) { errno = ENOTTY; return -1; } + m->fence = dup(m->fd2); return 0; + } struct droiddeck_dma_buf_sync_file *f = arg; (void)fd; assert(req == DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE); @@ -54,13 +62,17 @@ static int droiddeck_dmabuf_fd(struct dmabuf_buffer *b) { return b->fd; } static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; } static struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, uint32_t m, int (*cb)(int, uint32_t, void *), void *d) { - (void)l; (void)fd; (void)m; (void)cb; (void)d; ++sources; return &g_source; + (void)l; (void)fd; (void)m; (void)cb; (void)d; return &g_sources[sources++]; } +static void wl_event_source_remove(struct wl_event_source *s) { assert(s); ++removes; g_removed = s; } static int on_fence_readable(int fd, uint32_t mask, void *data) { (void)fd; (void)mask; (void)data; return 0; } static void send_deferred_release(struct ahb_buf *ab) { ++deferred_releases; ab->release_pending = 0; } static void maybe_free(struct ahb_buf *ab) { (void)ab; ++frees; } FUNCTIONS -static void reset(void) { import_ok = imports = imported_flags = deferred_releases = frees = sources = 0; } +static void reset(void) { + import_ok = imports = imported_flags = deferred_releases = frees = sources = removes = merge_ok = merges = 0; + g_removed = NULL; +} static void run(int display, int can_import, int fence_signalled) { reset(); wl_list_init(&g_bufs); @@ -78,12 +90,48 @@ static void run(int display, int can_import, int fence_signalled) { assert(deferred_releases == 1 && frees == 1 && !ab.fence_src && ab.fence_fd == -1); errno = 0; assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF); } else { - assert(deferred_releases == 0 && sources == 1 && ab.fence_src == &g_source && ab.fence_fd == fds[0]); + assert(deferred_releases == 0 && sources == 1 && ab.fence_src == &g_sources[0] && ab.fence_fd == fds[0]); close(fds[0]); } close(fds[1]); } +static int closed(int fd) { errno = 0; return fcntl(fd, F_GETFD) == -1 && errno == EBADF; } +static void rerelease(int can_merge, int second_import, int second_signalled) { + reset(); + wl_list_init(&g_bufs); + struct dmabuf_buffer b = {.fd = 7}; + struct ahb_buf ab; + memset(&ab, 0, sizeof(ab)); + ab.id = 42; ab.b = &b; ab.on_layer = 1; ab.release_pending = 1; ab.fence_fd = -1; + wl_list_insert(&g_bufs, &ab.link); + int first[2], second[2]; + assert(pipe(first) == 0 && pipe(second) == 0); + handle_released(42, first[0]); + assert(ab.fence_src == &g_sources[0] && ab.fence_fd == first[0] && deferred_releases == 0); + ab.on_layer = 1; + if (second_signalled) assert(write(second[1], "x", 1) == 1); + import_ok = second_import; merge_ok = can_merge; + handle_released(42, second[0]); + assert(!ab.on_layer && deferred_releases == 0 && frees == 0); + if (second_import || second_signalled) { + assert(removes == 0 && merges == 0 && sources == 1 && ab.fence_src == &g_sources[0] && ab.fence_fd == first[0]); + assert(closed(second[0])); + close(first[0]); + } else { + assert(merges == 1 && removes == 1 && g_removed == &g_sources[0]); + assert(sources == 2 && ab.fence_src == &g_sources[1] && ab.fence_fd >= 0); + assert(closed(first[0])); + if (can_merge) assert(closed(second[0]) && ab.fence_fd != second[0]); + else assert(ab.fence_fd == second[0]); + close(ab.fence_fd); + } + close(first[1]); close(second[1]); +} int main(int argc, char **argv) { + if (argc == 5 && !strcmp(argv[1], "rerelease")) { + rerelease(atoi(argv[2]), atoi(argv[3]), atoi(argv[4])); + return 0; + } assert(argc == 4); run(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])); return 0; @@ -103,7 +151,7 @@ class ZeroCopyReleaseAtLatchTest(unittest.TestCase): ahb, re.M)) struct = re.search(r'struct ahb_buf \{.*?\n\};', ahb, re.S).group() functions = '\n'.join(function(ahb, n) for n in ('find_buf', 'handle_released')) - source = HARNESS.replace('DEFINES', '#include \n#include \n' + defines) + source = HARNESS.replace('DEFINES', '#include \n#include \n#include \n' + defines) source = source.replace('STRUCT', struct).replace('FUNCTIONS', functions) cls.tmp = tempfile.TemporaryDirectory(prefix='droiddeck-release-latch-') cls.addClassCleanup(cls.tmp.cleanup) @@ -136,6 +184,23 @@ class ZeroCopyReleaseAtLatchTest(unittest.TestCase): def test_signalled_fence_releases_without_waiting(self): self.scenario(1, 0, 1) + def rerelease(self, can_merge, second_import, second_signalled): + result = subprocess.run([str(self.binary), 'rerelease', str(can_merge), str(second_import), str(second_signalled)], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_second_unsignalled_fence_merges_into_the_pending_wait(self): + self.rerelease(1, 0, 0) + + def test_second_unsignalled_fence_replaces_the_wait_when_merge_fails(self): + self.rerelease(0, 0, 0) + + def test_second_imported_fence_keeps_the_pending_wait(self): + self.rerelease(1, 1, 0) + + def test_second_signalled_fence_keeps_the_pending_wait(self): + self.rerelease(1, 0, 1) + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/vk_dmabuf_quarantine_test.c b/tools/tests/vk_dmabuf_quarantine_test.c index f4163a4ca7..77f62ab012 100644 --- a/tools/tests/vk_dmabuf_quarantine_test.c +++ b/tools/tests/vk_dmabuf_quarantine_test.c @@ -26,6 +26,8 @@ struct dmabuf_buffer { void *ahb_state; }; enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE }; +/* These release fixtures exercise legacy attachments, which own no acquire FD. */ +#define dd_frame_acquire_clear(slot) ((void)0) struct surface { enum surface_role role; struct surface *parent; diff --git a/tools/tests/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index 0c6a3311e6..be7b2f328a 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -82,6 +82,15 @@ int vkp_effects_active(void) { return 0; } int vkp_effects_upscaling(void) { return 0; } int vkp_effects_sharpening(void) { return 0; } int vkp_effects_postprocessing(void) { return 0; } +void vkp_effects_release_generated_sources(void) {} +int vkp_effects_prepare_generated(void) { assert(0); return 0; } +VkImage vkp_effects_run_before_generated(VkCommandBuffer c, VkImage i, int w, int h, int *rw, int *rh) { + assert(0); *rw = w; *rh = h; return i; +} +VkImage vkp_effects_run_generated(VkCommandBuffer c, VkImage i, int w, int h, + int ow, int oh, int slot, int *rw, int *rh) { + assert(0); *rw = w; *rh = h; return i; +} VkFilter vkp_effects_blit_filter(void) { return VK_FILTER_NEAREST; } void vkp_effects_set_formats(VkFormat a, VkFormat b, int scene_is_pq) {} VkImage vkp_effects_run(VkCommandBuffer c, VkImage i, int w, int h, int ow, int oh, int *rw, int *rh) { @@ -99,6 +108,10 @@ int vkp_framegen_run(VkCommandBuffer c, VkImage s, VkImageView v, int w, int h, return generated; } void vkp_framegen_presented(int n) { ++presented_notifications; } +void vkp_framegen_set_layer_timing(int layer) {} +void vkp_framegen_completed(void) {} +void zfg_discard_history_update(void) {} +void zfg_commit_history_update(void) {} void vkp_gpu_busy_device(VkPhysicalDevice p, VkDevice d, uint32_t f) {} void vkp_gpu_busy_device_lost(void) {} void hdrc_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {} @@ -193,6 +206,11 @@ static void setup(int extra) { /* Probe the public GPU entry points after a terminal result. This includes an * active off-screen pass and consumed release fds, not just the render guard. */ +static int blit_one(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { + const struct vkp_blit b = {.src = src, .dst = dst, .wait_fd = wait_fd}; + return vkp_blit_images(&b, 1); +} + static void assert_stopped(void) { assert(g_dev_state == -3 || (g_dev_state == -2 && g_recovery_attempted)); unsigned before = operations, before_destroys = destroys; @@ -211,7 +229,7 @@ static void assert_stopped(void) { assert(vkp_image_readback(&src, &pixel, 1) == -1); assert(vkp_pass_begin(64, 64, NULL, 0, NULL, NULL) == -1); int fd[2]; assert(pipe(fd) == 0); - assert(vkp_blit_image(&src, &dst, fd[0]) == -1); + assert(blit_one(&src, &dst, fd[0]) == -1); errno = 0; assert(close(fd[0]) == -1 && errno == EBADF); close(fd[1]); g_pass.active = 1; assert(pipe(fd) == 0); @@ -254,7 +272,7 @@ static void upload_wait_error(int single_pixel) { memcpy(saved, bytes, sizeof(saved)); struct vkp_image dst = {.image = (VkImage)(uintptr_t)9, .blit_dst = 1, .w = img->w, .h = img->h}; fence_answer = VK_ERROR_OUT_OF_HOST_MEMORY; - assert(vkp_blit_image(img, &dst, -1) == -1); + assert(blit_one(img, &dst, -1) == -1); assert(g_dev_state == -3 && submits == 1 && waits == 1); memset(data, 0x7e, sizeof(data)); if (single_pixel) take_pixel(&s, data, &resource); else take_shm(&s, &b, &resource); @@ -302,12 +320,26 @@ int main(int argc, char **argv) { struct vkp_image src = {.image = (VkImage)(uintptr_t)7, .w = 1, .h = 1}; struct vkp_image dst = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1, .blit_dst = 1}; fence_timeouts = 3; - assert(vkp_blit_image(&src, &dst, -1) == 0); + assert(blit_one(&src, &dst, -1) == 0); assert(g_dev_state == 1 && submits == 1 && waits == 4 && destroys == 0); - assert(vkp_blit_image(&src, &dst, -1) == 0); + assert(blit_one(&src, &dst, -1) == 0); assert(g_dev_state == 1 && submits == 2 && waits == 5 && destroys == 0); free(g_images); } + else if (!strcmp(name, "blit-batched")) { + setup(0); + struct vkp_image a = {.image = (VkImage)(uintptr_t)7, .w = 4, .h = 4}; + struct vkp_image b = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1}; + struct vkp_image da = {.image = (VkImage)(uintptr_t)9, .w = 4, .h = 4, .blit_dst = 1}; + struct vkp_image db = {.image = (VkImage)(uintptr_t)10, .w = 1, .h = 1, .blit_dst = 1}; + const struct vkp_blit both[2] = {{.src = &a, .dst = &da, .wait_fd = -1}, {.src = &b, .dst = &db, .wait_fd = -1}}; + assert(vkp_blit_images(both, 2) == 0); + assert(g_dev_state == 1 && submits == 1 && waits == 1 && destroys == 0); + const struct vkp_blit bad[2] = {{.src = &a, .dst = &da, .wait_fd = -1}, {.src = &b, .dst = &b, .wait_fd = -1}}; + assert(vkp_blit_images(bad, 2) == -1); + assert(submits == 1 && waits == 1); + free(g_images); + } else if (!strcmp(name, "normal") || !strcmp(name, "framegen")) { int extra = !strcmp(name, "framegen"); setup(extra); assert(vkp_render(64, 64, NULL, 0) == 0 && g_dev_state == 1); diff --git a/tools/ubuntu/overlay-desktop/usr/share/applications/droiddeck-return-gaming.desktop b/tools/ubuntu/overlay-desktop/usr/share/applications/droiddeck-return-gaming.desktop deleted file mode 100644 index 67f1d7f218..0000000000 --- a/tools/ubuntu/overlay-desktop/usr/share/applications/droiddeck-return-gaming.desktop +++ /dev/null @@ -1,9 +0,0 @@ -[Desktop Entry] -Name=Return to Gaming Mode -Comment=Log out of the desktop and go back to Steam -Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout -Icon=steamdeck-gaming-return -Terminal=false -Type=Application -StartupNotify=false -NoDisplay=true diff --git a/tools/ubuntu/overlay-runtime/usr/local/bin/sudo b/tools/ubuntu/overlay-runtime/usr/local/bin/sudo index d6f0fb6dc4..0b8c855241 100755 --- a/tools/ubuntu/overlay-runtime/usr/local/bin/sudo +++ b/tools/ubuntu/overlay-runtime/usr/local/bin/sudo @@ -79,7 +79,9 @@ elif ! command -v "$1" >/dev/null 2>&1; then exit 1 fi -if [ "$(id -u)" = 0 ]; then +# An ordinary user of the native userland (droiddeck-user): the hook starts the command as root +[ "${DDNATV_USER:-}" = app ] && export DDNATV_BECOME=root +if [ "$(id -u)" = 0 ] || [ -n "${DDNATV_BECOME:-}" ]; then [ "$background" = 1 ] && { "$@" & exit 0; } exec "$@" fi diff --git a/tools/ubuntu/packages-runtime.txt b/tools/ubuntu/packages-runtime.txt index c6bcd3618e..95269a035b 100644 --- a/tools/ubuntu/packages-runtime.txt +++ b/tools/ubuntu/packages-runtime.txt @@ -28,12 +28,14 @@ gamescope gir1.2-flatpak-1.0 gir1.2-glib-2.0 gir1.2-gtk-3.0 +gir1.2-ibus-1.0 gnu-coreutils gnupg-agent gpgv grep gzip hostname +ibus iproute2 iputils-ping less @@ -218,6 +220,7 @@ psmisc pulseaudio-utils python3 python3-gi +python3-ibus-1.0 python3-zstandard sed sensible-utils diff --git a/tools/ubuntu/protected-runtime.txt b/tools/ubuntu/protected-runtime.txt index 6462252206..fabadc3d0a 100644 --- a/tools/ubuntu/protected-runtime.txt +++ b/tools/ubuntu/protected-runtime.txt @@ -6,6 +6,8 @@ dpkg flatpak fontconfig gamescope +gir1.2-ibus-1.0 +ibus libegl-mesa0 libgl1-mesa-dri libluajit-5.1-2 @@ -16,4 +18,5 @@ mesa-libgallium mesa-vulkan-drivers python3 python3-gi +python3-ibus-1.0 xwayland diff --git a/tools/ubuntu/setup.sh b/tools/ubuntu/setup.sh index a2b0d63e66..0a673b3101 100755 --- a/tools/ubuntu/setup.sh +++ b/tools/ubuntu/setup.sh @@ -103,6 +103,15 @@ record_apt_state() { done > /usr/share/droiddeck/apt/system-sources.txt } +verify_ibus_runtime() { + local path + for path in /usr/bin/ibus /usr/bin/ibus-daemon /usr/libexec/ibus-dconf; do + [ -x "$path" ] || { printf 'Missing executable required for Steam IBus: %s\n' "$path" >&2; return 1; } + done + /usr/bin/ibus-daemon --version + /usr/bin/python3 -c 'import gi; gi.require_version("IBus", "1.0"); from gi.repository import IBus; assert IBus.Bus' +} + finish() { sed -i 's/^Types: deb deb-src$/Types: deb/' /etc/apt/sources.list.d/ubuntu.sources record_apt_state @@ -133,6 +142,7 @@ if [ "$stage" = runtime ]; then grep -v '^$' "$here/packages-runtime.txt" | xargs apt-get install -y --no-install-recommends install_held + verify_ibus_runtime build_package droiddeck-runtime "$here/overlay-runtime" "$here/protected-runtime.txt" "DroidDeck's Ubuntu runtime" update-alternatives --install /usr/bin/sudo sudo /usr/local/bin/sudo 1000 diff --git a/tools/vr/build_windows.py b/tools/vr/build_windows.py index af8fa4d465..d5cd2e6d35 100644 --- a/tools/vr/build_windows.py +++ b/tools/vr/build_windows.py @@ -10,7 +10,7 @@ import subprocess import tempfile ROOT = Path(__file__).resolve().parents[2] -IMAGE = 'droiddeck-local-cross:24.04-v3' +IMAGE = 'droiddeck-local-cross:24.04-v5' MANIFEST = 'vr-build.json' SOURCE_TREES = ('tools/vr/src', 'tools/vr/tests', 'tools/vr/third_party', 'tools/vr/driver_droiddeck', 'tools/vr/layer') @@ -131,14 +131,22 @@ def build(folder, include, root=ROOT, image=IMAGE): snapshot = Path(temp).resolve() if not snapshot.is_relative_to(workspace): raise ValueError('Temporary VR workspace escapes the checkout') - inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}}', image], + inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image], capture_output=True, text=True) - if inspect.returncode: + parts = inspect.stdout.strip().split() if inspect.returncode == 0 else [] + if len(parts) == 2 and parts[1] == 'linux/amd64' and parts[0]: + image_id = parts[0] + else: if image != IMAGE: - raise ValueError('VR compiler image is not available locally: ' + image) - subprocess.run([docker, 'build', '--tag', image, '--file', '-', str(snapshot)], + raise ValueError(f'VR compiler image is not available locally for linux/amd64: {image} (got {inspect.stdout.strip() or "missing"})') + subprocess.run([docker, 'build', '--platform', 'linux/amd64', '--tag', image, '--file', '-', str(snapshot)], input=input_files['tools/local-cross.Dockerfile'], check=True) - image_id = subprocess.check_output([docker, 'image', 'inspect', '--format', '{{.Id}}', image]).decode().strip() + inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image], + capture_output=True, text=True, check=True) + parts = inspect.stdout.strip().split() + if len(parts) != 2 or parts[1] != 'linux/amd64' or not parts[0]: + raise ValueError(f'VR compiler image {image} expected id and linux/amd64, got {inspect.stdout.strip()!r}') + image_id = parts[0] for name, data in input_files.items(): target = snapshot / name target.parent.mkdir(parents=True, exist_ok=True) diff --git a/tools/xbox/README.md b/tools/xbox/README.md index c0a6636aba..2411b7a777 100644 --- a/tools/xbox/README.md +++ b/tools/xbox/README.md @@ -125,6 +125,12 @@ download plus two copies of the largest container, and each container is deleted The download has no control channel: cancelling kills it and the next attempt starts that container from zero. +`droiddeck-legacy-offer-parent.patch` keeps an entitlement whose `satisfiedByProductId` is a GUID. +A purchased original Xbox or Xbox 360 title names its marketplace offer there (Red Faction II did), +not a Store product, so it is not a subscription plan; the backend dropped the whole row as malformed +and the game never reached the library. The row keeps its own status, trial, sharing and expiry +checks, and any other parent that is not a product id is still rejected. + `droiddeck-msixvc2.patch` installs MSIXVC2 packages, the format Xbox 360 backward-compatible titles ship in. The package Windows Update serves is only an index (`XboxPackage.cbor`, chunk and file tables); the files are encrypted, Brotli-compressed segments inside `.box` blobs on the Xbox diff --git a/tools/xbox/droiddeck-legacy-offer-parent.patch b/tools/xbox/droiddeck-legacy-offer-parent.patch new file mode 100644 index 0000000000..3efd79c277 --- /dev/null +++ b/tools/xbox/droiddeck-legacy-offer-parent.patch @@ -0,0 +1,45 @@ +diff --git a/crates/xodus-cli/src/commands/library.rs b/crates/xodus-cli/src/commands/library.rs +index 36191bf..43bf718 100644 +--- a/crates/xodus-cli/src/commands/library.rs ++++ b/crates/xodus-cli/src/commands/library.rs +@@ -11,6 +11,10 @@ fn product_id(id: &str) -> bool { + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()) + } + ++fn legacy_offer(id: &str) -> bool { ++ id.len() == 36 && uuid::Uuid::try_parse(id).is_ok() ++} ++ + fn entry(id: &str, item: &Value) -> Result { + if !product_id(id) || !item.is_object() { return Err("entitlement-product"); } + let status = item["status"].as_str().filter(|s|s.len()<40).ok_or("entitlement-status")?; +@@ -21,6 +25,9 @@ fn entry(id: &str, item: &Value) -> Result { + let parent = match item.get("satisfiedByProductId") { + None | Some(Value::Null) => None, + Some(Value::String(id)) if product_id(id) => Some(id.as_str()), ++ // An original Xbox or Xbox 360 purchase names its marketplace offer, a GUID: not a Store product, so not a ++ // subscription plan either. The row stands on its own status, trial, sharing and expiry checks. ++ Some(Value::String(id)) if legacy_offer(id) => None, + _ => return Err("entitlement-parent"), + }; + // Preserve typed Positron provenance for conditional library access. +@@ -271,6 +278,19 @@ mod tests { + json!({"status":"Active","isTrial":false,"sharingSource":"None","endDate":"2099-01-01T00:00:00Z"}) + } + ++ #[test] ++ fn a_purchase_naming_its_legacy_marketplace_offer_is_owned_on_its_own_checks() { ++ let mut raw = valid(); raw["satisfiedByProductId"] = json!("66acd000-77fe-1000-9115-d80258410896"); ++ assert!(entry(A, &raw).unwrap()["satisfiedByProductId"].is_null()); ++ raw["isTrial"] = json!(true); ++ assert_eq!(entry(A, &raw).unwrap()["isTrial"], json!(true)); ++ for parent in ["{66acd000-77fe-1000-9115-d80258410896}", "66acd00077fe10009115d80258410896", ++ "urn:uuid:66acd000-77fe-1000-9115-d80258410896", "9aaaaaaaaaaa", ""] { ++ let mut raw = valid(); raw["satisfiedByProductId"] = json!(parent); ++ assert_eq!(entry(A, &raw), Err("entitlement-parent"), "{parent}"); ++ } ++ } ++ + #[test] + fn positron_provenance_is_explicit_boolean_and_never_copied_from_untrusted_fields() { + for flag in [None, Some(json!(false)), Some(json!(true)), Some(Value::Null), diff --git a/tools/xbox/prepare.py b/tools/xbox/prepare.py index 5ff45b9c64..c74e3b7937 100755 --- a/tools/xbox/prepare.py +++ b/tools/xbox/prepare.py @@ -12,7 +12,7 @@ local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', ' 'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch', 'droiddeck-licensing-device-ticket.patch', 'droiddeck-dlc-mount.patch', 'droiddeck-legacy-packages.patch', 'droiddeck-legacy-install.patch', 'droiddeck-legacy-run.patch', - 'droiddeck-msixvc2.patch'] + 'droiddeck-msixvc2.patch', 'droiddeck-legacy-offer-parent.patch'] identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest() source = cache / ('source-' + identity[:16]) if not (source / '.prepared').is_file():